You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@brooklyn.apache.org by he...@apache.org on 2015/08/19 13:09:19 UTC

[01/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Repository: incubator-brooklyn
Updated Branches:
  refs/heads/master ce5ddaf2a -> 1811c4b08


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/ByonLocationsYamlTest.java
----------------------------------------------------------------------
diff --git a/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/ByonLocationsYamlTest.java b/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/ByonLocationsYamlTest.java
index c3d17f8..431fec1 100644
--- a/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/ByonLocationsYamlTest.java
+++ b/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/ByonLocationsYamlTest.java
@@ -29,6 +29,7 @@ import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.location.MachineLocation;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.DoNothingSoftwareProcess;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
@@ -41,8 +42,6 @@ import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
 import com.google.common.net.HostAndPort;
 
-import brooklyn.entity.basic.DoNothingSoftwareProcess;
-
 import org.apache.brooklyn.location.access.PortForwardManager;
 import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
 import org.apache.brooklyn.location.basic.LocationPredicates;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptySoftwareProcessYamlTest.java
----------------------------------------------------------------------
diff --git a/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptySoftwareProcessYamlTest.java b/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptySoftwareProcessYamlTest.java
index a6a4411..19ac3a2 100644
--- a/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptySoftwareProcessYamlTest.java
+++ b/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptySoftwareProcessYamlTest.java
@@ -24,13 +24,11 @@ import java.util.Map;
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.EmptySoftwareProcess;
-
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.Jsonya;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/EntitiesYamlTest.java
----------------------------------------------------------------------
diff --git a/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/EntitiesYamlTest.java b/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/EntitiesYamlTest.java
index 423b576..c82418c 100644
--- a/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/EntitiesYamlTest.java
+++ b/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/EntitiesYamlTest.java
@@ -52,6 +52,7 @@ import org.apache.brooklyn.entity.core.EntityInternal;
 import org.apache.brooklyn.entity.core.EntityPredicates;
 import org.apache.brooklyn.entity.group.DynamicCluster;
 import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.software.base.SameServerEntity;
 import org.apache.brooklyn.entity.stock.BasicEntity;
 import org.apache.brooklyn.sensor.core.Sensors;
 import org.apache.brooklyn.util.collections.MutableMap;
@@ -66,8 +67,6 @@ import org.testng.Assert;
 import org.testng.annotations.Test;
 import org.testng.collections.Lists;
 
-import brooklyn.entity.basic.SameServerEntity;
-
 import com.google.common.base.Suppliers;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/camp/src/test/resources/same-server-entity-test.yaml
----------------------------------------------------------------------
diff --git a/usage/camp/src/test/resources/same-server-entity-test.yaml b/usage/camp/src/test/resources/same-server-entity-test.yaml
index da327f1..9e9a768 100644
--- a/usage/camp/src/test/resources/same-server-entity-test.yaml
+++ b/usage/camp/src/test/resources/same-server-entity-test.yaml
@@ -19,7 +19,7 @@
 name: SameServerEntityYamlTest
 location: localhost
 services:
-- serviceType: brooklyn.entity.basic.SameServerEntity
+- serviceType: org.apache.brooklyn.entity.software.base.SameServerEntity
   name: Entities
   brooklyn.children:
   - serviceType: org.apache.brooklyn.entity.stock.BasicEntity

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/cli/src/main/java/org/apache/brooklyn/cli/lister/ClassFinder.java
----------------------------------------------------------------------
diff --git a/usage/cli/src/main/java/org/apache/brooklyn/cli/lister/ClassFinder.java b/usage/cli/src/main/java/org/apache/brooklyn/cli/lister/ClassFinder.java
index 485b10b..99a4263 100644
--- a/usage/cli/src/main/java/org/apache/brooklyn/cli/lister/ClassFinder.java
+++ b/usage/cli/src/main/java/org/apache/brooklyn/cli/lister/ClassFinder.java
@@ -33,6 +33,7 @@ import org.apache.brooklyn.api.policy.Policy;
 import org.apache.brooklyn.api.sensor.Enricher;
 import org.apache.brooklyn.entity.core.AbstractApplication;
 import org.apache.brooklyn.entity.core.AbstractEntity;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.policy.core.AbstractPolicy;
 import org.apache.brooklyn.sensor.enricher.AbstractEnricher;
 import org.apache.brooklyn.util.core.ResourceUtils;
@@ -47,8 +48,6 @@ import org.reflections.util.ConfigurationBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import com.google.common.annotations.Beta;
 import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/jsgui/src/main/webapp/assets/js/view/script-groovy.js
----------------------------------------------------------------------
diff --git a/usage/jsgui/src/main/webapp/assets/js/view/script-groovy.js b/usage/jsgui/src/main/webapp/assets/js/view/script-groovy.js
index 80ecb8f..045e4f1 100644
--- a/usage/jsgui/src/main/webapp/assets/js/view/script-groovy.js
+++ b/usage/jsgui/src/main/webapp/assets/js/view/script-groovy.js
@@ -51,7 +51,7 @@ define([
         },
         loadExample: function() {
             $(".input textarea").val(
-                    'import static brooklyn.entity.basic.Entities.*\n'+
+                    'import static org.apache.brooklyn.entity.software.base.Entities.*\n'+
                     '\n'+
                     'println "Last result: "+last\n'+
                     'data.exampleRunCount = (data.exampleRunCount ?: 0) + 1\n'+

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/jsgui/src/test/javascript/specs/model/catalog-application-spec.js
----------------------------------------------------------------------
diff --git a/usage/jsgui/src/test/javascript/specs/model/catalog-application-spec.js b/usage/jsgui/src/test/javascript/specs/model/catalog-application-spec.js
index df2bb94..d6a1c27 100644
--- a/usage/jsgui/src/test/javascript/specs/model/catalog-application-spec.js
+++ b/usage/jsgui/src/test/javascript/specs/model/catalog-application-spec.js
@@ -30,7 +30,7 @@ define([
             expect(catalogApplication.get('name')).toEqual('My example application')
             expect(catalogApplication.get('version')).toEqual('1.1')
             expect(catalogApplication.get('description')).toEqual('My awesome example application, as a catalog item')
-            expect(catalogApplication.get('planYaml')).toEqual('services:\n- type: brooklyn.entity.basic.VanillaSoftwareProcess\n  launch.command: echo \"Launch application\"\n  checkRunning.command: echo \"Check running application\"')
+            expect(catalogApplication.get('planYaml')).toEqual('services:\n- type: org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess\n  launch.command: echo \"Launch application\"\n  checkRunning.command: echo \"Check running application\"')
             expect(catalogApplication.get('iconUrl')).toEqual('http://my.example.com/icon.png')
         })
     })
@@ -54,7 +54,7 @@ define([
             expect(catalogApplication1.get('name')).toEqual('My example application')
             expect(catalogApplication1.get('version')).toEqual('1.1')
             expect(catalogApplication1.get('description')).toEqual('My awesome example application, as a catalog item')
-            expect(catalogApplication1.get('planYaml')).toEqual('services:\n- type: brooklyn.entity.basic.VanillaSoftwareProcess\n  launch.command: echo \"Launch application\"\n  checkRunning.command: echo \"Check running application\"')
+            expect(catalogApplication1.get('planYaml')).toEqual('services:\n- type: org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess\n  launch.command: echo \"Launch application\"\n  checkRunning.command: echo \"Check running application\"')
             expect(catalogApplication1.get('iconUrl')).toEqual('http://my.example.com/icon.png')
 
             var catalogApplication2 = catalogApplicationFixture.at(1)
@@ -63,7 +63,7 @@ define([
             expect(catalogApplication2.get('name')).toEqual('My example application')
             expect(catalogApplication2.get('version')).toEqual('2.0')
             expect(catalogApplication2.get('description')).toEqual('My awesome example application, as a catalog item')
-            expect(catalogApplication2.get('planYaml')).toEqual('services:\n- type: brooklyn.entity.basic.VanillaSoftwareProcess\n  launch.command: echo \"Launch application\"\n  checkRunning.command: echo \"Check running application\"')
+            expect(catalogApplication2.get('planYaml')).toEqual('services:\n- type: org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess\n  launch.command: echo \"Launch application\"\n  checkRunning.command: echo \"Check running application\"')
             expect(catalogApplication2.get('iconUrl')).toEqual('http://my.example.com/icon.png')
 
             var catalogApplication3 = catalogApplicationFixture.at(2)
@@ -72,7 +72,7 @@ define([
             expect(catalogApplication3.get('name')).toEqual('Another example application')
             expect(catalogApplication3.get('version')).toEqual('1.0')
             expect(catalogApplication3.get('description')).toEqual('Another awesome example application, as a catalog item')
-            expect(catalogApplication3.get('planYaml')).toEqual('services:\n- type: brooklyn.entity.basic.VanillaSoftwareProcess\n  launch.command: echo \"Launch other application\"\n  checkRunning.command: echo \"Check running other application\"')
+            expect(catalogApplication3.get('planYaml')).toEqual('services:\n- type: org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess\n  launch.command: echo \"Launch other application\"\n  checkRunning.command: echo \"Check running other application\"')
             expect(catalogApplication3.get('iconUrl')).toEqual('http://my.other.example.com/icon.png')
         })
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/jsgui/src/test/javascript/specs/model/sensor-summary-spec.js
----------------------------------------------------------------------
diff --git a/usage/jsgui/src/test/javascript/specs/model/sensor-summary-spec.js b/usage/jsgui/src/test/javascript/specs/model/sensor-summary-spec.js
index 63db6f2..b1bd2fd 100644
--- a/usage/jsgui/src/test/javascript/specs/model/sensor-summary-spec.js
+++ b/usage/jsgui/src/test/javascript/specs/model/sensor-summary-spec.js
@@ -32,7 +32,7 @@ define(['model/sensor-summary'], function (SensorSummary) {
             expect(filteredSensors.length).toBe(1)
             var ourSensor = filteredSensors.pop()
             expect(ourSensor.get("name")).toBe('service.state')
-            expect(ourSensor.get("type")).toBe('brooklyn.entity.basic.Lifecycle')
+            expect(ourSensor.get("type")).toBe('org.apache.brooklyn.entity.software.base.Lifecycle')
             expect(ourSensor.get("description")).toBe('Service lifecycle state')
             expect(ourSensor.getLinkByName('self')).toBe('fixtures/service-state.json')
             expect(ourSensor.getLinkByName()).toBe(undefined)

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/launcher/src/main/java/org/apache/brooklyn/launcher/BrooklynLauncher.java
----------------------------------------------------------------------
diff --git a/usage/launcher/src/main/java/org/apache/brooklyn/launcher/BrooklynLauncher.java b/usage/launcher/src/main/java/org/apache/brooklyn/launcher/BrooklynLauncher.java
index 205f18b..b5d2eec 100644
--- a/usage/launcher/src/main/java/org/apache/brooklyn/launcher/BrooklynLauncher.java
+++ b/usage/launcher/src/main/java/org/apache/brooklyn/launcher/BrooklynLauncher.java
@@ -70,9 +70,12 @@ import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
 import org.apache.brooklyn.core.mgmt.rebind.transformer.CompoundTransformer;
 import org.apache.brooklyn.core.server.BrooklynServerConfig;
 import org.apache.brooklyn.core.server.BrooklynServerPaths;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+import org.apache.brooklyn.entity.brooklynnode.LocalBrooklynNode;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.core.StartableApplication;
 import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -85,10 +88,6 @@ import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.brooklynnode.BrooklynNode;
-import brooklyn.entity.brooklynnode.LocalBrooklynNode;
-
 import org.apache.brooklyn.launcher.config.StopWhichAppsOnShutdown;
 import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine;
 import org.apache.brooklyn.location.basic.PortRanges;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/launcher/src/test/java/org/apache/brooklyn/entity/basic/VanillaSoftwareYamlTest.java
----------------------------------------------------------------------
diff --git a/usage/launcher/src/test/java/org/apache/brooklyn/entity/basic/VanillaSoftwareYamlTest.java b/usage/launcher/src/test/java/org/apache/brooklyn/entity/basic/VanillaSoftwareYamlTest.java
index 8ba6d73..12e3694 100644
--- a/usage/launcher/src/test/java/org/apache/brooklyn/entity/basic/VanillaSoftwareYamlTest.java
+++ b/usage/launcher/src/test/java/org/apache/brooklyn/entity/basic/VanillaSoftwareYamlTest.java
@@ -22,11 +22,9 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.api.entity.Application;
 import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.launcher.SimpleYamlLauncherForTests;
 import org.apache.brooklyn.launcher.camp.SimpleYamlLauncher;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/launcher/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynEntityMirrorIntegrationTest.java
----------------------------------------------------------------------
diff --git a/usage/launcher/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynEntityMirrorIntegrationTest.java b/usage/launcher/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynEntityMirrorIntegrationTest.java
index b6823da..89f1d05 100644
--- a/usage/launcher/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynEntityMirrorIntegrationTest.java
+++ b/usage/launcher/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynEntityMirrorIntegrationTest.java
@@ -32,15 +32,13 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.brooklynnode.BrooklynEntityMirror;
-
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.mgmt.ManagementContext;
 import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
 import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynEntityMirror;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.core.EntityInternal;
 import org.apache.brooklyn.entity.factory.ApplicationBuilder;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/launcher/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeRestTest.java
----------------------------------------------------------------------
diff --git a/usage/launcher/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeRestTest.java b/usage/launcher/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeRestTest.java
index bcce4ce..6141101 100644
--- a/usage/launcher/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeRestTest.java
+++ b/usage/launcher/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeRestTest.java
@@ -37,11 +37,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.brooklynnode.BrooklynEntityMirror;
-import brooklyn.entity.brooklynnode.BrooklynNode;
-import brooklyn.entity.brooklynnode.SameBrooklynNodeImpl;
-
 import org.apache.brooklyn.api.entity.Application;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
@@ -49,6 +44,10 @@ import org.apache.brooklyn.api.mgmt.Task;
 import org.apache.brooklyn.core.config.BasicConfigKey;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynEntityMirror;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNodeTest;
+import org.apache.brooklyn.entity.brooklynnode.SameBrooklynNodeImpl;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.core.EntityInternal;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/launcher/src/test/java/org/apache/brooklyn/launcher/blueprints/AbstractBlueprintTest.java
----------------------------------------------------------------------
diff --git a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/blueprints/AbstractBlueprintTest.java b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/blueprints/AbstractBlueprintTest.java
index 3606f0e..6e228bf 100644
--- a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/blueprints/AbstractBlueprintTest.java
+++ b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/blueprints/AbstractBlueprintTest.java
@@ -36,6 +36,7 @@ import org.apache.brooklyn.core.mgmt.rebind.persister.FileBasedObjectStore;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.apache.brooklyn.util.core.ResourceUtils;
@@ -44,9 +45,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.launcher.BrooklynLauncher;
 import org.apache.brooklyn.launcher.SimpleYamlLauncherForTests;
 import org.apache.brooklyn.launcher.camp.BrooklynCampPlatformLauncher;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedMySqlNodeImpl.java
----------------------------------------------------------------------
diff --git a/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedMySqlNodeImpl.java b/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedMySqlNodeImpl.java
index 1ef7a7d..af7d7db 100644
--- a/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedMySqlNodeImpl.java
+++ b/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedMySqlNodeImpl.java
@@ -26,18 +26,17 @@ import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.entity.database.mysql.MySqlNode;
 import org.apache.brooklyn.entity.database.mysql.MySqlNodeImpl;
 import org.apache.brooklyn.entity.database.mysql.MySqlSshDriver;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.function.FunctionFeed;
 import org.apache.brooklyn.sensor.feed.function.FunctionPollConfig;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.task.DynamicTasks;
 import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
 import org.apache.brooklyn.util.time.CountdownTimer;
 import org.apache.brooklyn.util.time.Duration;
 
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-import brooklyn.entity.software.SshEffectorTasks;
-
 /**
  * @see SimulatedJBoss7ServerImpl for description of purpose and configuration options.
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedTheeTierApp.java
----------------------------------------------------------------------
diff --git a/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedTheeTierApp.java b/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedTheeTierApp.java
index 76b1ecf..7423322 100644
--- a/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedTheeTierApp.java
+++ b/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedTheeTierApp.java
@@ -33,6 +33,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.core.StartableApplication;
 import org.apache.brooklyn.entity.database.mysql.MySqlNode;
 import org.apache.brooklyn.entity.group.DynamicCluster;
+import org.apache.brooklyn.entity.java.JavaEntityMethods;
 import org.apache.brooklyn.entity.proxy.nginx.NginxController;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.entity.webapp.ControlledDynamicWebAppCluster;
@@ -54,8 +55,6 @@ import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Lists;
 
-import brooklyn.entity.java.JavaEntityMethods;
-
 /**
  * A 3-tier app where all components are just "simulated" - they don't actually run 
  * real app-servers or databases, instead just executing a "sleep" command to simulate 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/qa/src/test/java/org/apache/brooklyn/qa/brooklynnode/SoftlayerObtainPrivateLiveTest.java
----------------------------------------------------------------------
diff --git a/usage/qa/src/test/java/org/apache/brooklyn/qa/brooklynnode/SoftlayerObtainPrivateLiveTest.java b/usage/qa/src/test/java/org/apache/brooklyn/qa/brooklynnode/SoftlayerObtainPrivateLiveTest.java
index a1fb6d9..9ddc283 100644
--- a/usage/qa/src/test/java/org/apache/brooklyn/qa/brooklynnode/SoftlayerObtainPrivateLiveTest.java
+++ b/usage/qa/src/test/java/org/apache/brooklyn/qa/brooklynnode/SoftlayerObtainPrivateLiveTest.java
@@ -29,6 +29,9 @@ import org.apache.brooklyn.api.mgmt.ManagementContext;
 import org.apache.brooklyn.core.objs.BrooklynObjectInternal.ConfigurationSupportInternal;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
 import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynEntityMirror;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode.DeployBlueprintEffector;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.lifecycle.Lifecycle;
@@ -54,10 +57,6 @@ import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 
-import brooklyn.entity.brooklynnode.BrooklynEntityMirror;
-import brooklyn.entity.brooklynnode.BrooklynNode;
-import brooklyn.entity.brooklynnode.BrooklynNode.DeployBlueprintEffector;
-
 /**
  * Tests obtaining a machine with a private IP only. For the machine to be
  * accessible we should have a gateway machine already running in the same

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/rest-server/src/main/resources/reset-catalog.xml
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/main/resources/reset-catalog.xml b/usage/rest-server/src/main/resources/reset-catalog.xml
index ce43857..5e6d0f8 100644
--- a/usage/rest-server/src/main/resources/reset-catalog.xml
+++ b/usage/rest-server/src/main/resources/reset-catalog.xml
@@ -20,7 +20,7 @@
 <catalog>
     <name>Brooklyn Demos</name>
 
-    <template type="brooklyn.entity.basic.BasicApplication" name="Basic application" />
+    <template type="org.apache.brooklyn.entity.software.base.BasicApplication" name="Basic application" />
     <template type="brooklyn.osgi.tests.SimpleApplication" name="Simple OSGi application">
         <libraries>
             <bundle>${bundle-location}</bundle>

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ServerResourceTest.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ServerResourceTest.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ServerResourceTest.java
index f5e0c78..7260205 100644
--- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ServerResourceTest.java
+++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ServerResourceTest.java
@@ -29,6 +29,9 @@ import org.apache.brooklyn.api.mgmt.ManagementContext;
 import org.apache.brooklyn.core.BrooklynVersion;
 import org.apache.brooklyn.core.internal.BrooklynProperties;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcessImpl;
 import org.apache.brooklyn.rest.domain.HighAvailabilitySummary;
 import org.apache.brooklyn.rest.domain.VersionSummary;
 import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
@@ -41,10 +44,6 @@ import org.testng.annotations.Test;
 import com.google.common.collect.ImmutableSet;
 import com.sun.jersey.api.client.UniformInterfaceException;
 
-import brooklyn.entity.basic.EmptySoftwareProcess;
-import brooklyn.entity.basic.EmptySoftwareProcessDriver;
-import brooklyn.entity.basic.EmptySoftwareProcessImpl;
-
 @Test(singleThreaded = true)
 public class ServerResourceTest extends BrooklynRestResourceTest {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/UsageResourceTest.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/UsageResourceTest.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/UsageResourceTest.java
index c341e38..6250992 100644
--- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/UsageResourceTest.java
+++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/UsageResourceTest.java
@@ -35,9 +35,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcessEntityTest;
-
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.api.location.LocationSpec;
 import org.apache.brooklyn.api.location.NoMachinesAvailableException;
@@ -45,6 +42,7 @@ import org.apache.brooklyn.core.mgmt.internal.LocalUsageManager;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessEntityTest;
 import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.rest.domain.ApplicationSpec;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/rest-server/src/test/java/org/apache/brooklyn/rest/test/entity/brooklynnode/DeployBlueprintTest.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/test/entity/brooklynnode/DeployBlueprintTest.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/test/entity/brooklynnode/DeployBlueprintTest.java
index d0c29c3..a4cf64d 100644
--- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/test/entity/brooklynnode/DeployBlueprintTest.java
+++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/test/entity/brooklynnode/DeployBlueprintTest.java
@@ -27,6 +27,8 @@ import java.util.Map;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.internal.EntityLocal;
 import org.apache.brooklyn.api.mgmt.EntityManager;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode.DeployBlueprintEffector;
 import org.apache.brooklyn.entity.stock.BasicApplication;
 import org.apache.brooklyn.rest.BrooklynRestApiLauncherTestFixture;
 import org.apache.brooklyn.sensor.feed.http.JsonFunctions;
@@ -42,9 +44,6 @@ import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 
-import brooklyn.entity.brooklynnode.BrooklynNode;
-import brooklyn.entity.brooklynnode.BrooklynNode.DeployBlueprintEffector;
-
 public class DeployBlueprintTest extends BrooklynRestApiLauncherTestFixture {
 
     private static final Logger log = LoggerFactory.getLogger(DeployBlueprintTest.class);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/rest-server/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimpleEntity.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimpleEntity.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimpleEntity.java
index aaa7179..d5e608f 100644
--- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimpleEntity.java
+++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimpleEntity.java
@@ -28,12 +28,10 @@ import org.apache.brooklyn.core.config.BasicConfigKey;
 import org.apache.brooklyn.effector.core.MethodEffector;
 import org.apache.brooklyn.entity.annotation.Effector;
 import org.apache.brooklyn.entity.annotation.EffectorParam;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/rest-server/src/test/java/org/apache/brooklyn/rest/util/EntityLocationUtilsTest.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/util/EntityLocationUtilsTest.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/util/EntityLocationUtilsTest.java
index 3200f5d..ace877b 100644
--- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/util/EntityLocationUtilsTest.java
+++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/util/EntityLocationUtilsTest.java
@@ -27,9 +27,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.location.basic.AbstractLocation;
 import org.apache.brooklyn.location.basic.LocationInternal;
 import org.apache.brooklyn.location.geo.HostGeoInfo;
@@ -37,6 +34,7 @@ import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.rest.testing.mocks.RestMockSimpleEntity;
 
 import com.google.common.collect.ImmutableList;


[42/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/RebindJcloudsLocationTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/RebindJcloudsLocationTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/RebindJcloudsLocationTest.java
index 225b7f7..598e2fd 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/RebindJcloudsLocationTest.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/RebindJcloudsLocationTest.java
@@ -25,7 +25,7 @@ import org.jclouds.domain.LoginCredentials;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 import org.apache.brooklyn.core.mgmt.rebind.RebindTestFixtureWithApp;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 
 import com.google.common.net.HostAndPort;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/SimpleJcloudsLocationUserLoginAndConfigLiveTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/SimpleJcloudsLocationUserLoginAndConfigLiveTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/SimpleJcloudsLocationUserLoginAndConfigLiveTest.java
index c30c50e..9429329 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/SimpleJcloudsLocationUserLoginAndConfigLiveTest.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/SimpleJcloudsLocationUserLoginAndConfigLiveTest.java
@@ -24,7 +24,7 @@ import java.util.List;
 import java.util.Map;
 
 import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.ssh.BashCommands;
 import org.apache.brooklyn.util.text.Identifiers;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/SingleMachineProvisioningLocationJcloudsLiveTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/SingleMachineProvisioningLocationJcloudsLiveTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/SingleMachineProvisioningLocationJcloudsLiveTest.java
index b1cd3ba..7c24565 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/SingleMachineProvisioningLocationJcloudsLiveTest.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/SingleMachineProvisioningLocationJcloudsLiveTest.java
@@ -31,7 +31,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
 import org.apache.brooklyn.api.location.MachineLocation;
 import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.location.basic.SingleMachineProvisioningLocation;
+import org.apache.brooklyn.location.byon.SingleMachineProvisioningLocation;
 
 public class SingleMachineProvisioningLocationJcloudsLiveTest extends AbstractJcloudsLiveTest {
 private static final Logger log = LoggerFactory.getLogger(SingleMachineProvisioningLocation.class);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AbstractJcloudsLocationTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AbstractJcloudsLocationTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AbstractJcloudsLocationTest.java
index 5a8fa82..b55bc28 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AbstractJcloudsLocationTest.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AbstractJcloudsLocationTest.java
@@ -34,8 +34,8 @@ import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
 import org.testng.collections.Lists;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.location.jclouds.JcloudsLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.exceptions.Exceptions;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AwsEc2LocationWindowsLiveTest.groovy
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AwsEc2LocationWindowsLiveTest.groovy b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AwsEc2LocationWindowsLiveTest.groovy
index ccf9ecd..cabc31c 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AwsEc2LocationWindowsLiveTest.groovy
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AwsEc2LocationWindowsLiveTest.groovy
@@ -22,9 +22,9 @@ import static org.testng.Assert.*
 
 import org.apache.brooklyn.api.mgmt.ManagementContext
 import org.apache.brooklyn.entity.core.Entities
-import org.apache.brooklyn.location.basic.SshMachineLocation
 import org.apache.brooklyn.location.jclouds.JcloudsLocation
 import org.apache.brooklyn.location.jclouds.JcloudsSshMachineLocation
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.slf4j.Logger
 import org.slf4j.LoggerFactory
 import org.testng.annotations.AfterMethod

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/CarrenzaLocationLiveTest.groovy
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/CarrenzaLocationLiveTest.groovy b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/CarrenzaLocationLiveTest.groovy
index d8f0efa..0c2197f 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/CarrenzaLocationLiveTest.groovy
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/CarrenzaLocationLiveTest.groovy
@@ -22,9 +22,9 @@ import static org.testng.Assert.*
 
 import org.apache.brooklyn.core.internal.BrooklynProperties
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext
-import org.apache.brooklyn.location.basic.SshMachineLocation
 import org.apache.brooklyn.location.jclouds.JcloudsLocation
 import org.apache.brooklyn.location.jclouds.JcloudsSshMachineLocation
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap
 import org.slf4j.Logger
 import org.slf4j.LoggerFactory

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/RackspaceLocationLiveTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/RackspaceLocationLiveTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/RackspaceLocationLiveTest.java
index 9bae000..908c239 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/RackspaceLocationLiveTest.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/RackspaceLocationLiveTest.java
@@ -27,9 +27,9 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.location.jclouds.JcloudsLocation;
 import org.apache.brooklyn.location.jclouds.JcloudsSshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 
 public class RackspaceLocationLiveTest extends AbstractJcloudsLocationTest {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/policy/jclouds/os/CreateUserPolicyLiveTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/policy/jclouds/os/CreateUserPolicyLiveTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/policy/jclouds/os/CreateUserPolicyLiveTest.java
new file mode 100644
index 0000000..0fe9b24
--- /dev/null
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/policy/jclouds/os/CreateUserPolicyLiveTest.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.policy.jclouds.os;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.policy.PolicySpec;
+import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.policy.jclouds.os.CreateUserPolicy;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.core.internal.ssh.SshTool;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+
+public class CreateUserPolicyLiveTest extends BrooklynAppLiveTestSupport {
+
+    private static final Logger LOG = LoggerFactory.getLogger(CreateUserPolicyLiveTest.class);
+
+    // TODO Fails on OS X
+    @Test(groups={"Integration", "WIP"})
+    public void testIntegrationCreatesUser() throws Exception {
+        LocalhostMachineProvisioningLocation loc = app.newLocalhostProvisioningLocation();
+        runTestCreatesUser(loc);
+    }
+    
+    @Test(groups="Live")
+    @SuppressWarnings("unchecked")
+    public void testLiveCreatesUser() throws Exception {
+        String locSpec = "jclouds:softlayer:ams01";
+        ImmutableMap<String, String> locArgs = ImmutableMap.of("imageId", "CENTOS_6_64");
+        Location loc = mgmt.getLocationRegistry().resolve(locSpec, locArgs);
+        runTestCreatesUser((MachineProvisioningLocation<SshMachineLocation>) loc);
+    }
+    
+    public void runTestCreatesUser(MachineProvisioningLocation<SshMachineLocation> loc) throws Exception {
+        String newUsername = Identifiers.makeRandomId(16);
+        SshMachineLocation machine = loc.obtain(ImmutableMap.of());
+        
+        try {
+            app.createAndManageChild(EntitySpec.create(TestEntity.class)
+                    .policy(PolicySpec.create(CreateUserPolicy.class)
+                            .configure(CreateUserPolicy.GRANT_SUDO, true)
+                            .configure(CreateUserPolicy.VM_USERNAME, newUsername)));
+            TestEntity entity = (TestEntity) Iterables.getOnlyElement(app.getChildren());
+
+            app.start(ImmutableList.of(machine));
+            
+            String creds = EntityTestUtils.assertAttributeEventuallyNonNull(entity, CreateUserPolicy.VM_USER_CREDENTIALS);
+            Pattern pattern = Pattern.compile("(.*) : (.*) @ (.*):(.*)");
+            Matcher matcher = pattern.matcher(creds);
+            assertTrue(matcher.matches());
+            String username = matcher.group(1).trim();
+            String password = matcher.group(2).trim();
+            String hostname = matcher.group(3).trim();
+            String port = matcher.group(4).trim();
+            
+            assertEquals(newUsername, username);
+            assertEquals(hostname, machine.getAddress().getHostName());
+            assertEquals(port, ""+machine.getPort());
+    
+            SshMachineLocation machine2 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                    .configure(SshTool.PROP_USER, newUsername)
+                    .configure(SshMachineLocation.PASSWORD, password)
+                    .configure("address", hostname)
+                    .configure(SshMachineLocation.SSH_PORT, Integer.parseInt(port)));
+            
+            LOG.info("Checking ssh'able for auto-generated user: machine="+machine+"; creds="+creds);
+            assertTrue(machine2.isSshable(), "machine="+machine+"; creds="+creds);
+            
+        } catch (Exception e) {
+            throw e;
+        } finally {
+            LOG.info("Deleting auto-generated user "+newUsername);
+            machine.execScript("delete-user-"+newUsername, ImmutableList.of("sudo userdel -f "+newUsername));
+            
+            loc.release(machine);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/policy/jclouds/os/CreateUserPolicyTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/policy/jclouds/os/CreateUserPolicyTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/policy/jclouds/os/CreateUserPolicyTest.java
new file mode 100644
index 0000000..e423528
--- /dev/null
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/policy/jclouds/os/CreateUserPolicyTest.java
@@ -0,0 +1,137 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.policy.jclouds.os;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.policy.PolicySpec;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.policy.jclouds.os.CreateUserPolicy;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.core.internal.ssh.SshTool;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+
+public class CreateUserPolicyTest extends BrooklynAppUnitTestSupport {
+
+    @SuppressWarnings("unused")
+    private static final Logger LOG = LoggerFactory.getLogger(CreateUserPolicyTest.class);
+
+    public static class RecordingSshMachineLocation extends SshMachineLocation {
+        private static final long serialVersionUID = 1641930081769106380L;
+        
+        public static List<List<String>> execScriptCalls = Lists.newArrayList();
+
+        @Override 
+        public int execScript(String summary, List<String> cmds) {
+            execScriptCalls.add(cmds);
+            return 0;
+        }
+        @Override 
+        public int execScript(Map<String,?> props, String summaryForLogging, List<String> cmds) {
+            execScriptCalls.add(cmds);
+            return 0;
+        }
+        @Override 
+        public int execScript(String summaryForLogging, List<String> cmds, Map<String,?> env) {
+            execScriptCalls.add(cmds);
+            return 0;
+        }
+        @Override 
+        public int execScript(Map<String,?> props, String summaryForLogging, List<String> cmds, Map<String,?> env) {
+            execScriptCalls.add(cmds);
+            return 0;
+        }
+    }
+
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        RecordingSshMachineLocation.execScriptCalls.clear();
+    }
+
+    @AfterMethod(alwaysRun=true)
+    @Override
+    public void tearDown() throws Exception {
+        try {
+            super.tearDown();
+        } finally {
+            RecordingSshMachineLocation.execScriptCalls.clear();
+        }
+    }
+    
+    @Test
+    public void testCallsCreateUser() throws Exception {
+        SshMachineLocation machine = mgmt.getLocationManager().createLocation(LocationSpec.create(RecordingSshMachineLocation.class)
+                .configure(SshTool.PROP_USER, "myuser")
+                .configure(SshTool.PROP_PASSWORD, "mypassword")
+                .configure("address", "1.2.3.4")
+                .configure(SshTool.PROP_PORT, 1234));
+    
+        String newUsername = "mynewuser";
+        
+        app.createAndManageChild(EntitySpec.create(TestEntity.class)
+                .policy(PolicySpec.create(CreateUserPolicy.class)
+                        .configure(CreateUserPolicy.GRANT_SUDO, true)
+                        .configure(CreateUserPolicy.VM_USERNAME, newUsername)));
+        TestEntity entity = (TestEntity) Iterables.getOnlyElement(app.getChildren());
+        app.start(ImmutableList.of(machine));
+        
+        String creds = EntityTestUtils.assertAttributeEventuallyNonNull(entity, CreateUserPolicy.VM_USER_CREDENTIALS);
+        Pattern pattern = Pattern.compile("(.*) : (.*) @ (.*):(.*)");
+        Matcher matcher = pattern.matcher(creds);
+        assertTrue(matcher.matches());
+        String username2 = matcher.group(1).trim();
+        String password = matcher.group(2).trim();
+        String hostname = matcher.group(3).trim();
+        String port = matcher.group(4).trim();
+        
+        assertEquals(newUsername, username2);
+        assertEquals(hostname, "1.2.3.4");
+        assertEquals(password.length(), 12);
+        assertEquals(port, "1234");
+
+        boolean found = false;
+        for (List<String> cmds : RecordingSshMachineLocation.execScriptCalls) {
+            if (cmds.toString().contains("useradd")) {
+                found = true;
+                break;
+            }
+        }
+        assertTrue(found, "useradd not found in: "+RecordingSshMachineLocation.execScriptCalls);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/policy/src/main/java/org/apache/brooklyn/policy/followthesun/DefaultFollowTheSunModel.java
----------------------------------------------------------------------
diff --git a/policy/src/main/java/org/apache/brooklyn/policy/followthesun/DefaultFollowTheSunModel.java b/policy/src/main/java/org/apache/brooklyn/policy/followthesun/DefaultFollowTheSunModel.java
index fef3d7f..e5c328c 100644
--- a/policy/src/main/java/org/apache/brooklyn/policy/followthesun/DefaultFollowTheSunModel.java
+++ b/policy/src/main/java/org/apache/brooklyn/policy/followthesun/DefaultFollowTheSunModel.java
@@ -33,7 +33,7 @@ import java.util.concurrent.ConcurrentHashMap;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.location.basic.AbstractLocation;
+import org.apache.brooklyn.location.core.AbstractLocation;
 
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.ImmutableSet;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/policy/src/main/java/org/apache/brooklyn/policy/ha/SshMachineFailureDetector.java
----------------------------------------------------------------------
diff --git a/policy/src/main/java/org/apache/brooklyn/policy/ha/SshMachineFailureDetector.java b/policy/src/main/java/org/apache/brooklyn/policy/ha/SshMachineFailureDetector.java
index 037d150..00c9515 100644
--- a/policy/src/main/java/org/apache/brooklyn/policy/ha/SshMachineFailureDetector.java
+++ b/policy/src/main/java/org/apache/brooklyn/policy/ha/SshMachineFailureDetector.java
@@ -25,8 +25,8 @@ import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.api.catalog.Catalog;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.location.basic.Machines;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.Machines;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.policy.ha.HASensors.FailureDescriptor;
 import org.apache.brooklyn.sensor.core.BasicNotificationSensor;
 import org.apache.brooklyn.util.core.internal.ssh.SshTool;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/policy/src/test/java/org/apache/brooklyn/policy/autoscaling/AutoScalerPolicyRebindTest.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/autoscaling/AutoScalerPolicyRebindTest.java b/policy/src/test/java/org/apache/brooklyn/policy/autoscaling/AutoScalerPolicyRebindTest.java
index 72eace9..55ee1d7 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/autoscaling/AutoScalerPolicyRebindTest.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/autoscaling/AutoScalerPolicyRebindTest.java
@@ -37,7 +37,7 @@ import org.apache.brooklyn.test.EntityTestUtils;
 import org.apache.brooklyn.util.time.Duration;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/policy/src/test/java/org/apache/brooklyn/policy/enricher/HttpLatencyDetectorTest.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/enricher/HttpLatencyDetectorTest.java b/policy/src/test/java/org/apache/brooklyn/policy/enricher/HttpLatencyDetectorTest.java
index 9b0b591..40dd244 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/enricher/HttpLatencyDetectorTest.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/enricher/HttpLatencyDetectorTest.java
@@ -37,7 +37,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.mockwebserver.MockResponse;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/policy/src/test/java/org/apache/brooklyn/policy/followthesun/AbstractFollowTheSunPolicyTest.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/followthesun/AbstractFollowTheSunPolicyTest.java b/policy/src/test/java/org/apache/brooklyn/policy/followthesun/AbstractFollowTheSunPolicyTest.java
index d2f7cd5..f16ce77 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/followthesun/AbstractFollowTheSunPolicyTest.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/followthesun/AbstractFollowTheSunPolicyTest.java
@@ -44,7 +44,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 import org.apache.brooklyn.policy.loadbalancing.BalanceableContainer;
 import org.apache.brooklyn.policy.loadbalancing.MockContainerEntity;
 import org.apache.brooklyn.policy.loadbalancing.MockItemEntity;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunModelTest.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunModelTest.java b/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunModelTest.java
index 0edf888..89b53d5 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunModelTest.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunModelTest.java
@@ -26,8 +26,7 @@ import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
-
+import org.apache.brooklyn.location.core.SimulatedLocation;
 import org.apache.brooklyn.policy.loadbalancing.MockContainerEntity;
 import org.apache.brooklyn.policy.loadbalancing.MockContainerEntityImpl;
 import org.apache.brooklyn.policy.loadbalancing.MockItemEntity;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunPolicySoakTest.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunPolicySoakTest.java b/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunPolicySoakTest.java
index 1b56974..94edbdf 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunPolicySoakTest.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunPolicySoakTest.java
@@ -34,7 +34,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 import org.apache.brooklyn.policy.loadbalancing.BalanceableContainer;
 import org.apache.brooklyn.policy.loadbalancing.MockContainerEntity;
 import org.apache.brooklyn.policy.loadbalancing.MockItemEntity;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunPolicyTest.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunPolicyTest.java b/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunPolicyTest.java
index dffe610..80cb05c 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunPolicyTest.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunPolicyTest.java
@@ -36,7 +36,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 import org.apache.brooklyn.policy.loadbalancing.MockContainerEntity;
 import org.apache.brooklyn.policy.loadbalancing.MockItemEntity;
 import org.apache.brooklyn.policy.loadbalancing.Movable;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/policy/src/test/java/org/apache/brooklyn/policy/ha/HaPolicyRebindTest.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/ha/HaPolicyRebindTest.java b/policy/src/test/java/org/apache/brooklyn/policy/ha/HaPolicyRebindTest.java
index 392798a..84830fc 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/ha/HaPolicyRebindTest.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/ha/HaPolicyRebindTest.java
@@ -45,7 +45,7 @@ import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 import org.apache.brooklyn.policy.ha.HASensors.FailureDescriptor;
 
 import com.google.common.base.Predicate;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/policy/src/test/java/org/apache/brooklyn/policy/ha/ServiceReplacerTest.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/ha/ServiceReplacerTest.java b/policy/src/test/java/org/apache/brooklyn/policy/ha/ServiceReplacerTest.java
index 7243623..6262978 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/ha/ServiceReplacerTest.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/ha/ServiceReplacerTest.java
@@ -57,7 +57,7 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 import org.apache.brooklyn.policy.ha.HASensors.FailureDescriptor;
 
 import com.google.common.base.Predicate;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/AbstractLoadBalancingPolicyTest.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/AbstractLoadBalancingPolicyTest.java b/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/AbstractLoadBalancingPolicyTest.java
index bdc1fcd..0d3a591 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/AbstractLoadBalancingPolicyTest.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/AbstractLoadBalancingPolicyTest.java
@@ -44,7 +44,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Function;
 import com.google.common.base.Preconditions;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/BalanceableWorkerPoolTest.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/BalanceableWorkerPoolTest.java b/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/BalanceableWorkerPoolTest.java
index 4e9dfb9..b1b327e 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/BalanceableWorkerPoolTest.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/BalanceableWorkerPoolTest.java
@@ -38,7 +38,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/ItemsInContainersGroupTest.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/ItemsInContainersGroupTest.java b/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/ItemsInContainersGroupTest.java
index 04bf7d1..2420eae 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/ItemsInContainersGroupTest.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/ItemsInContainersGroupTest.java
@@ -32,7 +32,7 @@ import org.apache.brooklyn.util.collections.MutableMap;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/sandbox/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/zabbix/ZabbixFeed.java
----------------------------------------------------------------------
diff --git a/sandbox/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/zabbix/ZabbixFeed.java b/sandbox/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/zabbix/ZabbixFeed.java
index ce527eb..1d6128b 100644
--- a/sandbox/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/zabbix/ZabbixFeed.java
+++ b/sandbox/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/zabbix/ZabbixFeed.java
@@ -38,7 +38,7 @@ import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.EntityFunctions;
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
-import org.apache.brooklyn.location.basic.SupportsPortForwarding;
+import org.apache.brooklyn.location.core.SupportsPortForwarding;
 import org.apache.brooklyn.sensor.feed.AbstractFeed;
 import org.apache.brooklyn.sensor.feed.AttributePollHandler;
 import org.apache.brooklyn.sensor.feed.PollHandler;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/sandbox/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/zabbix/ZabbixServerImpl.java
----------------------------------------------------------------------
diff --git a/sandbox/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/zabbix/ZabbixServerImpl.java b/sandbox/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/zabbix/ZabbixServerImpl.java
index 1adfc4c..3596488 100644
--- a/sandbox/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/zabbix/ZabbixServerImpl.java
+++ b/sandbox/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/zabbix/ZabbixServerImpl.java
@@ -28,7 +28,7 @@ import org.apache.brooklyn.entity.core.AbstractEntity;
 import org.apache.brooklyn.entity.group.AbstractMembershipTrackingPolicy;
 import org.apache.brooklyn.entity.group.DynamicGroup;
 import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.http.HttpFeed;
 import org.apache.brooklyn.sensor.feed.http.HttpPollConfig;
 import org.apache.brooklyn.sensor.feed.http.HttpValueFunctions;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeImpl.java
index 4e76f70..c68c0a2 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeImpl.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeImpl.java
@@ -53,7 +53,7 @@ import org.apache.http.HttpStatus;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
-import org.apache.brooklyn.location.basic.Locations;
+import org.apache.brooklyn.location.core.Locations;
 import org.apache.brooklyn.sensor.enricher.Enrichers;
 import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
 import org.apache.brooklyn.sensor.feed.http.HttpFeed;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java
index 3ba710a..9f8c942 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java
@@ -33,7 +33,7 @@ import org.apache.brooklyn.entity.brooklynnode.BrooklynNode.ExistingFileBehaviou
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.drivers.downloads.DownloadSubstituters;
 import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.file.ArchiveBuilder;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefLifecycleEffectorTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefLifecycleEffectorTasks.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefLifecycleEffectorTasks.java
index e4cbf1c..1880a78 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefLifecycleEffectorTasks.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefLifecycleEffectorTasks.java
@@ -29,7 +29,7 @@ import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.software.base.lifecycle.MachineLifecycleEffectorTasks;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.Machines;
+import org.apache.brooklyn.location.core.Machines;
 import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.Jsonya;
 import org.apache.brooklyn.util.collections.MutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefServerTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefServerTasks.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefServerTasks.java
index d8132be..c81ff9d 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefServerTasks.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefServerTasks.java
@@ -24,7 +24,7 @@ import java.io.IOException;
 import java.nio.charset.Charset;
 import java.security.KeyPair;
 
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.crypto.SecureKeys;
 
 import com.google.common.base.Throwables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefSoloDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefSoloDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefSoloDriver.java
index 0f4dd40..b0780e2 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefSoloDriver.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefSoloDriver.java
@@ -24,7 +24,7 @@ import org.apache.brooklyn.api.mgmt.TaskFactory;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.task.DynamicTasks;
 
 import com.google.common.annotations.Beta;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/chef/KnifeConvergeTaskFactory.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/KnifeConvergeTaskFactory.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/KnifeConvergeTaskFactory.java
index 39e31b8..b66cd4e 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/chef/KnifeConvergeTaskFactory.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/KnifeConvergeTaskFactory.java
@@ -32,7 +32,7 @@ import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.effector.core.EffectorTasks;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.Jsonya;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriver.java
index f162ca4..6b77ef3 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriver.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriver.java
@@ -47,7 +47,7 @@ import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import com.google.gson.internal.Primitives;
 
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.collections.MutableSet;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxSupport.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxSupport.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxSupport.java
index 5e67d30..838b5d9 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxSupport.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxSupport.java
@@ -32,8 +32,8 @@ import org.apache.brooklyn.entity.core.EntityInternal;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.Locations;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.jmx.JmxHelper;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJmx.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJmx.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJmx.java
index 4831826..7939dae 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJmx.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJmx.java
@@ -27,7 +27,7 @@ import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.BasicConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.sensor.core.AttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppSshDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppSshDriver.java
index 011f4ff..2fd57b3 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppSshDriver.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppSshDriver.java
@@ -28,7 +28,7 @@ import java.util.Map;
 import javax.annotation.Nullable;
 
 import org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelper;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.file.ArchiveBuilder;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineEntityImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineEntityImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineEntityImpl.java
index d656102..ef5d0ba 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineEntityImpl.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineEntityImpl.java
@@ -26,8 +26,8 @@ import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.apache.brooklyn.entity.software.base.EmptySoftwareProcessDriver;
 import org.apache.brooklyn.entity.software.base.EmptySoftwareProcessImpl;
-import org.apache.brooklyn.location.basic.Machines;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.Machines;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.ssh.SshFeed;
 import org.apache.brooklyn.sensor.feed.ssh.SshPollConfig;
 import org.apache.brooklyn.sensor.feed.ssh.SshPollValue;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineInitTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineInitTasks.java b/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineInitTasks.java
index 91b0411..4fa564f 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineInitTasks.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineInitTasks.java
@@ -32,7 +32,7 @@ import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.task.DynamicTasks;
 import org.apache.brooklyn.util.core.task.Tasks;
 import org.apache.brooklyn.util.core.task.ssh.SshTasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolImpl.java
index d1d4bee..7706545 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolImpl.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolImpl.java
@@ -42,8 +42,8 @@ import org.apache.brooklyn.entity.lifecycle.Lifecycle;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.BasicLocationDefinition;
-import org.apache.brooklyn.location.basic.Machines;
+import org.apache.brooklyn.location.core.BasicLocationDefinition;
+import org.apache.brooklyn.location.core.Machines;
 import org.apache.brooklyn.location.dynamic.DynamicLocation;
 import org.apache.brooklyn.sensor.core.Sensors;
 import org.apache.brooklyn.util.collections.MutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocation.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocation.java b/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocation.java
index 6c50f94..c9d4fbb 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocation.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocation.java
@@ -33,7 +33,7 @@ import org.apache.brooklyn.api.location.MachineProvisioningLocation;
 import org.apache.brooklyn.api.location.NoMachinesAvailableException;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.location.basic.AbstractLocation;
+import org.apache.brooklyn.location.core.AbstractLocation;
 import org.apache.brooklyn.location.dynamic.DynamicLocation;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolver.java b/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolver.java
index 4bcb1a3..c6165ab 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolver.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolver.java
@@ -39,9 +39,9 @@ import com.google.common.base.Joiner;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Sets;
 
-import org.apache.brooklyn.location.basic.BasicLocationRegistry;
-import org.apache.brooklyn.location.basic.LocationInternal;
-import org.apache.brooklyn.location.basic.LocationPropertiesFromBrooklynProperties;
+import org.apache.brooklyn.location.core.BasicLocationRegistry;
+import org.apache.brooklyn.location.core.LocationPropertiesFromBrooklynProperties;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 import org.apache.brooklyn.location.dynamic.DynamicLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.text.KeyValueParser;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessSshDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessSshDriver.java
index 195e8f8..3bcdbf9 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessSshDriver.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessSshDriver.java
@@ -47,7 +47,7 @@ import com.google.common.collect.Iterables;
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
 
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
 import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.core.internal.ssh.SshTool;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessWinRmDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessWinRmDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessWinRmDriver.java
index 42d0d45..7c18ac3 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessWinRmDriver.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessWinRmDriver.java
@@ -29,7 +29,7 @@ import org.apache.brooklyn.api.internal.EntityLocal;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.python.core.PyException;
-import org.apache.brooklyn.location.basic.WinRmMachineLocation;
+import org.apache.brooklyn.location.winrm.WinRmMachineLocation;
 import org.apache.brooklyn.sensor.core.Sensors;
 import org.apache.brooklyn.util.exceptions.ReferenceWithError;
 import org.apache.brooklyn.util.repeat.Repeater;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessSshDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessSshDriver.java
index 4ddf540..2c82148 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessSshDriver.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessSshDriver.java
@@ -21,7 +21,7 @@ package org.apache.brooklyn.entity.software.base;
 import java.util.Map;
 import java.util.concurrent.atomic.AtomicBoolean;
 
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 
 public class EmptySoftwareProcessSshDriver extends AbstractSoftwareProcessSshDriver implements EmptySoftwareProcessDriver {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerDriverLifecycleEffectorTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerDriverLifecycleEffectorTasks.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerDriverLifecycleEffectorTasks.java
index 7f605e5..490f2fb 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerDriverLifecycleEffectorTasks.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerDriverLifecycleEffectorTasks.java
@@ -40,7 +40,7 @@ import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
 import com.google.common.reflect.TypeToken;
 
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
 import org.apache.brooklyn.util.collections.MutableSet;
 import org.apache.brooklyn.util.core.flags.TypeCoercions;
 import org.apache.brooklyn.util.core.task.DynamicTasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessImpl.java
index a3e8bcd..ce0505b 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessImpl.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessImpl.java
@@ -51,9 +51,9 @@ import org.apache.brooklyn.entity.lifecycle.Lifecycle.Transition;
 import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic.ServiceNotUpLogic;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.location.cloud.CloudLocationConfig;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.enricher.AbstractEnricher;
 import org.apache.brooklyn.sensor.feed.function.FunctionFeed;
 import org.apache.brooklyn.sensor.feed.function.FunctionPollConfig;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessSshDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessSshDriver.java
index 7edb047..4dac567 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessSshDriver.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessSshDriver.java
@@ -26,7 +26,7 @@ import org.apache.brooklyn.api.entity.drivers.downloads.DownloadResolver;
 import org.apache.brooklyn.api.internal.EntityLocal;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelper;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.file.ArchiveUtils;
 import org.apache.brooklyn.util.guava.Maybe;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessWinRmDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessWinRmDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessWinRmDriver.java
index f7d6ccf..0c65ddb 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessWinRmDriver.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessWinRmDriver.java
@@ -20,7 +20,7 @@ package org.apache.brooklyn.entity.software.base;
 
 import org.apache.brooklyn.api.internal.EntityLocal;
 import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.location.basic.WinRmMachineLocation;
+import org.apache.brooklyn.location.winrm.WinRmMachineLocation;
 import org.apache.brooklyn.util.net.UserAndHostAndPort;
 
 public class VanillaWindowsProcessWinRmDriver extends AbstractSoftwareProcessWinRmDriver implements VanillaWindowsProcessDriver {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasks.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasks.java
index c46277b..3014ce7 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasks.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasks.java
@@ -69,12 +69,12 @@ import com.google.common.base.Suppliers;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 
-import org.apache.brooklyn.location.basic.AbstractLocation;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.location.basic.Machines;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.location.cloud.CloudLocationConfig;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.location.core.Locations;
+import org.apache.brooklyn.location.core.Machines;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
 import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.MutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelper.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelper.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelper.java
index bb974c5..ae33c53 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelper.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelper.java
@@ -38,7 +38,7 @@ import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.GroovyJavaMethods;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.internal.ssh.ShellTool;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/system_service/InitdServiceInstaller.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/system_service/InitdServiceInstaller.java b/software/base/src/main/java/org/apache/brooklyn/entity/system_service/InitdServiceInstaller.java
index a0724f2..95b56c2 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/system_service/InitdServiceInstaller.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/system_service/InitdServiceInstaller.java
@@ -33,8 +33,8 @@ import org.apache.brooklyn.effector.core.EffectorTasks;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.EntityInternal;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.location.cloud.names.AbstractCloudMachineNamer;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.ResourceUtils;
 import org.apache.brooklyn.util.core.task.Tasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricher.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricher.java b/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricher.java
index 0bc98d1..d6e6e53 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricher.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricher.java
@@ -33,7 +33,7 @@ import org.apache.brooklyn.effector.core.EffectorTasks;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.enricher.AbstractEnricher;
 import org.apache.brooklyn.util.core.task.BasicExecutionManager;
 import org.apache.brooklyn.util.core.task.DynamicTasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasks.java b/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasks.java
index 4ea5ed5..d1b7cca 100644
--- a/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasks.java
+++ b/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasks.java
@@ -39,8 +39,8 @@ import org.apache.brooklyn.entity.core.EntityInternal;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.LocationInternal;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 import org.apache.brooklyn.util.core.internal.ssh.SshTool;
 import org.apache.brooklyn.util.core.task.Tasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/main/resources/META-INF/services/org.apache.brooklyn.api.location.LocationResolver
----------------------------------------------------------------------
diff --git a/software/base/src/main/resources/META-INF/services/org.apache.brooklyn.api.location.LocationResolver b/software/base/src/main/resources/META-INF/services/org.apache.brooklyn.api.location.LocationResolver
index 8ab42e7..5392b0e 100644
--- a/software/base/src/main/resources/META-INF/services/org.apache.brooklyn.api.location.LocationResolver
+++ b/software/base/src/main/resources/META-INF/services/org.apache.brooklyn.api.location.LocationResolver
@@ -16,4 +16,4 @@
 # specific language governing permissions and limitations
 # under the License.
 #
-brooklyn.entity.pool.ServerPoolLocationResolver
+org.apache.brooklyn.entity.machine.pool.ServerPoolLocationResolver

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java
index 1879e4b..a5b0609 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java
@@ -36,7 +36,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java
index 948a42a..0092612 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java
@@ -74,10 +74,10 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.location.basic.PortRanges;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.Locations;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Charsets;
 import com.google.common.base.Function;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeTest.java
index 60d2c6b..280d4c4 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeTest.java
@@ -46,7 +46,7 @@ import org.testng.annotations.Test;
 
 import com.google.common.collect.ImmutableMap;
 
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 public class BrooklynNodeTest {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefLiveTestSupport.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefLiveTestSupport.java b/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefLiveTestSupport.java
index 5ea8315..c42f85e 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefLiveTestSupport.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefLiveTestSupport.java
@@ -31,7 +31,7 @@ import org.apache.brooklyn.entity.core.EntityInternal;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.ResourceUtils;
 import org.apache.brooklyn.util.io.FileUtil;
 import org.apache.brooklyn.util.stream.InputStreamSupplier;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/AbstractChefToyMySqlEntityLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/AbstractChefToyMySqlEntityLiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/AbstractChefToyMySqlEntityLiveTest.java
index 3250ee3..83fb6bb 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/AbstractChefToyMySqlEntityLiveTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/AbstractChefToyMySqlEntityLiveTest.java
@@ -22,7 +22,7 @@ import org.testng.annotations.Test;
 import org.apache.brooklyn.api.location.MachineProvisioningLocation;
 import org.apache.brooklyn.entity.chef.ChefLiveTestSupport;
 import org.apache.brooklyn.entity.software.base.test.mysql.AbstractToyMySqlEntityTest;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 public abstract class AbstractChefToyMySqlEntityLiveTest extends AbstractToyMySqlEntityTest {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/java/EntityPollingTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/java/EntityPollingTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/java/EntityPollingTest.java
index b49e235..a895830 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/java/EntityPollingTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/java/EntityPollingTest.java
@@ -42,7 +42,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaOptsTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaOptsTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaOptsTest.java
index a9da253..3d14b7f 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaOptsTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaOptsTest.java
@@ -41,7 +41,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.collections.MutableSet;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriverIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriverIntegrationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriverIntegrationTest.java
index 68cdc61..8c9a549 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriverIntegrationTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriverIntegrationTest.java
@@ -41,7 +41,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Optional;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppRebindTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppRebindTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppRebindTest.java
index d3a97d3..67e9627 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppRebindTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppRebindTest.java
@@ -43,7 +43,7 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppTest.java
index e4d30c3..25de72a 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppTest.java
@@ -63,8 +63,8 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/AbstractServerPoolTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/AbstractServerPoolTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/AbstractServerPoolTest.java
index c31e458..25fbe76 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/AbstractServerPoolTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/AbstractServerPoolTest.java
@@ -39,7 +39,7 @@ import org.apache.brooklyn.test.EntityTestUtils;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolverTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolverTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolverTest.java
index fb3974b..ab8656b 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolverTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolverTest.java
@@ -43,8 +43,8 @@ import org.testng.annotations.Test;
 
 import com.google.common.collect.ImmutableList;
 
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.location.dynamic.DynamicLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 public class ServerPoolLocationResolverTest {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolTest.java
index 9d9b3a2..2ab689c 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolTest.java
@@ -35,7 +35,7 @@ import org.apache.brooklyn.test.EntityTestUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation.LocalhostMachine;
 
 import com.google.common.base.Joiner;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessRestartIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessRestartIntegrationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessRestartIntegrationTest.java
index 67f5fc4..9eb6264 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessRestartIntegrationTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessRestartIntegrationTest.java
@@ -34,7 +34,7 @@ import org.apache.brooklyn.util.collections.CollectionFunctionals;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcessDriver.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcessDriver.java
index 2e0ea00..65de389 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcessDriver.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcessDriver.java
@@ -20,7 +20,7 @@ package org.apache.brooklyn.entity.software.base;
 
 import org.apache.brooklyn.api.internal.EntityLocal;
 import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 /**
  * Implements methods in {@link org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver}



[14/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/java/JavaSoftwareProcessSshDriverIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/java/JavaSoftwareProcessSshDriverIntegrationTest.java b/software/base/src/test/java/brooklyn/entity/java/JavaSoftwareProcessSshDriverIntegrationTest.java
deleted file mode 100644
index 2aae686..0000000
--- a/software/base/src/test/java/brooklyn/entity/java/JavaSoftwareProcessSshDriverIntegrationTest.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertTrue;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.text.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.basic.lifecycle.MyEntity;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.ImmutableList;
-
-public class JavaSoftwareProcessSshDriverIntegrationTest extends BrooklynAppLiveTestSupport {
-
-    private static final long TIMEOUT_MS = 10 * 1000;
-
-    private static final Logger LOG = LoggerFactory.getLogger(JavaSoftwareProcessSshDriverIntegrationTest.class);
-
-    private MachineProvisioningLocation<?> localhost;
-
-    private static class ConcreteJavaSoftwareProcessSshDriver extends JavaSoftwareProcessSshDriver {
-        public ConcreteJavaSoftwareProcessSshDriver(EntityLocal entity, SshMachineLocation machine) {
-            super(entity, machine);
-        }
-        @Override protected String getLogFileLocation() { return null; }
-        @Override public boolean isRunning() { return false; }
-        @Override public void stop() {}
-        @Override public void install() {}
-        @Override public void customize() {}
-        @Override public void launch() {}
-    }
-
-    @BeforeMethod(alwaysRun=true)
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-        localhost = app.newLocalhostProvisioningLocation();
-    }
-
-    @Test(groups = "Integration")
-    public void testJavaStartStopSshDriverStartsAndStopsApp() throws Exception {
-        final MyEntity entity = app.createAndManageChild(EntitySpec.create(MyEntity.class));
-        app.start(ImmutableList.of(localhost));
-        Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
-            public void run() {
-                assertTrue(entity.getAttribute(SoftwareProcess.SERVICE_UP));
-            }});
-
-        entity.stop();
-        assertFalse(entity.getAttribute(SoftwareProcess.SERVICE_UP));
-    }
-
-    @Test(groups = "Integration")
-    public void testGetJavaVersion() throws Exception {
-        SshMachineLocation sshLocation = app.getManagementContext().getLocationManager().createLocation(
-                LocationSpec.create(SshMachineLocation.class).configure("address", "localhost"));
-        JavaSoftwareProcessSshDriver driver = new ConcreteJavaSoftwareProcessSshDriver(app, sshLocation);
-        Optional<String> version = driver.getInstalledJavaVersion();
-        assertNotNull(version);
-        assertTrue(version.isPresent());
-        LOG.info("{}.testGetJavaVersion found: {} on localhost", getClass(), version.get());
-    }
-
-    @Test(groups = "Integration")
-    public void testStartsInMgmtSpecifiedDirectory() throws Exception {
-        String dir = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4));
-        tearDown();
-        mgmt = new LocalManagementContextForTests();
-        mgmt.getBrooklynProperties().put(BrooklynConfigKeys.ONBOX_BASE_DIR, dir);
-        setUp();
-
-        doTestSpecifiedDirectory(dir, dir);
-        Os.deleteRecursively(dir);
-    }
-
-    @Test(groups = "Integration")
-    public void testStartsInAppSpecifiedDirectoryUnderHome() throws Exception {
-        String dir = Os.mergePathsUnix("~/.brooklyn-test-"+Strings.makeRandomId(4));
-        try {
-            app.config().set(BrooklynConfigKeys.ONBOX_BASE_DIR, dir);
-            doTestSpecifiedDirectory(dir, dir);
-        } finally {
-            Os.deleteRecursively(dir);
-        }
-    }
-
-    @Test(groups = "Integration")
-    public void testStartsInDifferentRunAndInstallSpecifiedDirectories() throws Exception {
-        String dir1 = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4));
-        String dir2 = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4));
-        app.config().set(BrooklynConfigKeys.INSTALL_DIR, dir1);
-        app.config().set(BrooklynConfigKeys.RUN_DIR, dir2);
-        doTestSpecifiedDirectory(dir1, dir2);
-        Os.deleteRecursively(dir1);
-        Os.deleteRecursively(dir2);
-    }
-
-    @Test(groups = "Integration")
-    public void testStartsInLegacySpecifiedDirectory() throws Exception {
-        String dir1 = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4));
-        String dir2 = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4));
-        tearDown();
-        mgmt = new LocalManagementContextForTests();
-        mgmt.getBrooklynProperties().put("brooklyn.dirs.install", dir1);
-        mgmt.getBrooklynProperties().put("brooklyn.dirs.run", dir2);
-        setUp();
-
-        app.config().set(BrooklynConfigKeys.RUN_DIR, dir2);
-        doTestSpecifiedDirectory(dir1, dir2);
-        Os.deleteRecursively(dir1);
-        Os.deleteRecursively(dir2);
-    }
-
-    protected void doTestSpecifiedDirectory(final String installDirPrefix, final String runDirPrefix) throws Exception {
-        final MyEntity entity = app.createAndManageChild(EntitySpec.create(MyEntity.class));
-        app.start(ImmutableList.of(localhost));
-        Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
-            public void run() {
-                assertTrue(entity.getAttribute(SoftwareProcess.SERVICE_UP));
-
-                String installDir = entity.getAttribute(SoftwareProcess.INSTALL_DIR);
-                Assert.assertNotNull(installDir);
-
-                String runDir = entity.getAttribute(SoftwareProcess.RUN_DIR);
-                Assert.assertNotNull(runDir);
-            }});
-
-        String installDir = entity.getAttribute(SoftwareProcess.INSTALL_DIR);
-        String runDir = entity.getAttribute(SoftwareProcess.RUN_DIR);
-        LOG.info("dirs for " + app + " are: install=" + installDir + ", run=" + runDir);
-        assertTrue(installDir.startsWith(Os.tidyPath(installDirPrefix)), "INSTALL_DIR is "+installDir+", does not start with expected prefix "+installDirPrefix);
-        assertTrue(runDir.startsWith(Os.tidyPath(runDirPrefix)), "RUN_DIR is "+runDir+", does not start with expected prefix "+runDirPrefix);
-
-        entity.stop();
-        assertFalse(entity.getAttribute(SoftwareProcess.SERVICE_UP));
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/java/JmxSupportTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/java/JmxSupportTest.java b/software/base/src/test/java/brooklyn/entity/java/JmxSupportTest.java
deleted file mode 100644
index 5f9ed0f..0000000
--- a/software/base/src/test/java/brooklyn/entity/java/JmxSupportTest.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import static org.testng.Assert.assertEquals;
-
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.util.core.ResourceUtils;
-import org.apache.brooklyn.util.core.flags.TypeCoercions;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.javalang.JavaClassNames;
-import org.apache.brooklyn.util.maven.MavenRetriever;
-import org.apache.brooklyn.util.stream.Streams;
-import org.apache.brooklyn.util.text.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.java.UsesJmx.JmxAgentModes;
-
-@Test
-public class JmxSupportTest {
-
-    private static final Logger log = LoggerFactory.getLogger(JmxSupportTest.class);
-    
-    private TestApplication app;
-
-    @AfterMethod(alwaysRun = true)
-    public void tearDown() {
-        if (app!=null) Entities.destroyAll(app.getManagementContext());
-    }
-    
-    // defaults to JMXMP for most locations (or, in this case, if it does not yet know the location)
-    public void testJmxAutodetect() {
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        JmxSupport support = new JmxSupport(app, null);
-        
-        Assert.assertEquals(support.getJmxAgentMode(), JmxAgentModes.JMXMP_AND_RMI);
-    }
-
-    public void testJmxmpJarExistence() {
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        app.setConfig(JmxSupport.JMX_AGENT_MODE, JmxAgentModes.JMXMP);
-        JmxSupport support = new JmxSupport(app, null);
-        
-        Assert.assertEquals(support.getJmxAgentJarMavenArtifact().getArtifactId(),
-                "brooklyn-jmxmp-agent");
-        
-        Assert.assertTrue(ResourceUtils.create(this).doesUrlExist(support.getJmxAgentJarUrl()), support.getJmxAgentJarUrl());
-        Assert.assertTrue(support.getJmxAgentJarUrl().contains("-shaded-"), support.getJmxAgentJarUrl());
-    }
-    
-    public void testJmxrmiJarExistence() {
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        JmxSupport support = new JmxSupport(app, null);
-        app.setConfig(JmxSupport.JMX_AGENT_MODE, JmxAgentModes.JMX_RMI_CUSTOM_AGENT);
-        
-        Assert.assertEquals(support.getJmxAgentJarMavenArtifact().getArtifactId(),
-                "brooklyn-jmxrmi-agent");
-        
-        Assert.assertTrue(ResourceUtils.create(this).doesUrlExist(support.getJmxAgentJarUrl()), support.getJmxAgentJarUrl());
-    }
-
-    @Test
-    public void testCoerceStringtoJmxAgentModes() {
-        // Test coercions
-        assertEquals(TypeCoercions.coerce("AUTODETECT", JmxAgentModes.class), JmxAgentModes.AUTODETECT);
-        assertEquals(TypeCoercions.coerce("JMXMP_AND_RMI", JmxAgentModes.class), JmxAgentModes.JMXMP_AND_RMI);
-        assertEquals(TypeCoercions.coerce("JMX_RMI_CUSTOM_AGENT", JmxAgentModes.class), JmxAgentModes.JMX_RMI_CUSTOM_AGENT);
-
-        // Test different case format options
-        assertEquals(TypeCoercions.coerce("jmxRmiCustomAgent", JmxAgentModes.class), JmxAgentModes.JMX_RMI_CUSTOM_AGENT);
-        assertEquals(TypeCoercions.coerce("jmx_rmi_custom_agent", JmxAgentModes.class), JmxAgentModes.JMX_RMI_CUSTOM_AGENT);
-        assertEquals(TypeCoercions.coerce("jmx-rmi-custom-agent", JmxAgentModes.class), JmxAgentModes.JMX_RMI_CUSTOM_AGENT);
-        assertEquals(TypeCoercions.coerce("JmxRmiCustomAgent", JmxAgentModes.class), JmxAgentModes.JMX_RMI_CUSTOM_AGENT);
-    }
-
-
-    @Test(groups="Integration")
-    public void testJmxmpJarHostedValidity() {
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        app.setConfig(JmxSupport.JMX_AGENT_MODE, JmxAgentModes.JMXMP);
-        JmxSupport support = new JmxSupport(app, null);
-
-        // make sure we get a valid jar, big enough (no redirect, and classifier correclty set for this!)
-        // (we don't want the unshaded jar, that would be no good!)
-        checkValidArchive(MavenRetriever.hostedUrl(support.getJmxAgentJarMavenArtifact()), 100*1000);
-    }
-    
-    @Test(groups="Integration")
-    public void testJmxrmiJarHostedValidity() {
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        JmxSupport support = new JmxSupport(app, null);
-        app.setConfig(JmxSupport.JMX_AGENT_MODE, JmxAgentModes.JMX_RMI_CUSTOM_AGENT);
-        
-        // make sure we get a valid jar, big enough (no redirect)
-        checkValidArchive(MavenRetriever.hostedUrl(support.getJmxAgentJarMavenArtifact()), 4000);
-    }
-
-    private void checkValidArchive(String url, long minSize) {
-        byte[] bytes;
-        try {
-            bytes = Streams.readFully(ResourceUtils.create(this).getResourceFromUrl(url));
-            log.info("read "+bytes.length+" bytes from "+url+" for "+JavaClassNames.callerNiceClassAndMethod(1));
-        } catch (Exception e) {
-            log.warn("Unable to read URL "+url+" for " +JavaClassNames.callerNiceClassAndMethod(1)+
-                    "; this test may require hosted (sonatype/mavencentral) repo to be populated");
-            Assert.fail("Unable to read URL "+url+"; this test may require hosted (sonatype/mavencentral) repo to be populated");
-            throw Exceptions.propagate(e);
-        }
-        // confirm this follow redirects!
-        Assert.assertTrue(bytes.length > minSize, "download of "+url+" is suspect ("+Strings.makeSizeString(bytes.length)+")");
-        // (could also check it is a zip etc)
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/java/SslKeyConfigTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/java/SslKeyConfigTest.java b/software/base/src/test/java/brooklyn/entity/java/SslKeyConfigTest.java
deleted file mode 100644
index 954bb43..0000000
--- a/software/base/src/test/java/brooklyn/entity/java/SslKeyConfigTest.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.security.Key;
-import java.security.KeyStore;
-import java.security.cert.Certificate;
-
-import org.apache.brooklyn.util.core.crypto.FluentKeySigner;
-import org.apache.brooklyn.util.core.crypto.SecureKeys;
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-public class SslKeyConfigTest {
-
-    @Test
-    public void testWriteKeyAndCertThenReadThem() throws Exception {
-        FluentKeySigner signer = new FluentKeySigner("brooklyn-test").selfsign();
-        
-        KeyStore ks = SecureKeys.newKeyStore();
-        ks.setKeyEntry("key1", 
-                signer.getKey().getPrivate(), "s3cr3t".toCharArray(), new Certificate[] { signer.getAuthorityCertificate() });
-        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
-        ks.store(bytes, "5t0r3".toCharArray());
-        
-        KeyStore ks2 = SecureKeys.newKeyStore(new ByteArrayInputStream(bytes.toByteArray()), "5t0r3");
-        String firstAlias = ks2.aliases().nextElement();
-        Assert.assertEquals(firstAlias, "key1");
-        Key k = ks2.getKey(firstAlias, "s3cr3t".toCharArray());
-        Assert.assertEquals(k, signer.getKey().getPrivate());
-        Certificate[] cc = ks2.getCertificateChain(firstAlias);
-        Assert.assertEquals(cc, new Certificate[] { signer.getAuthorityCertificate() });
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/java/VanillaJavaAppRebindTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/java/VanillaJavaAppRebindTest.java b/software/base/src/test/java/brooklyn/entity/java/VanillaJavaAppRebindTest.java
deleted file mode 100644
index 6f1b179..0000000
--- a/software/base/src/test/java/brooklyn/entity/java/VanillaJavaAppRebindTest.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import static org.testng.Assert.assertTrue;
-
-import java.io.File;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.policy.enricher.RollingTimeWindowMeanEnricher;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.ResourceUtils;
-import org.apache.brooklyn.util.time.Duration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.java.JavaOptsTest.TestingJavaOptsVanillaJavaAppImpl;
-
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-
-import com.google.common.base.Predicates;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.io.Files;
-
-public class VanillaJavaAppRebindTest {
-
-    private static final Logger LOG = LoggerFactory.getLogger(VanillaJavaAppRebindTest.class);
-    
-    private static String BROOKLYN_THIS_CLASSPATH = null;
-    private static Class<?> MAIN_CLASS = ExampleVanillaMain.class;
-
-    private ClassLoader classLoader = getClass().getClassLoader();
-    private LocalManagementContext managementContext;
-    private File mementoDir;
-    private TestApplication app;
-    private LocalhostMachineProvisioningLocation loc;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        mementoDir = Files.createTempDir();
-        managementContext = RebindTestUtils.newPersistingManagementContext(mementoDir, classLoader);
-        
-        if (BROOKLYN_THIS_CLASSPATH==null) {
-            BROOKLYN_THIS_CLASSPATH = ResourceUtils.create(MAIN_CLASS).getClassLoaderDir();
-        }
-        app = TestApplication.Factory.newManagedInstanceForTests(managementContext);
-        loc = app.newLocalhostProvisioningLocation(MutableMap.of("address", "localhost"));
-    }
-
-    @AfterMethod(alwaysRun = true)
-    public void tearDown() throws Exception {
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-        if (mementoDir != null) RebindTestUtils.deleteMementoDir(mementoDir);
-    }
-    
-    private void rebind() throws Exception {
-        RebindTestUtils.waitForPersisted(app);
-        managementContext.terminate();
-        
-        app = (TestApplication) RebindTestUtils.rebind(mementoDir, getClass().getClassLoader());
-        managementContext = (LocalManagementContext) app.getManagementContext();
-        loc = (LocalhostMachineProvisioningLocation) Iterables.get(app.getLocations(), 0, null);
-    }
-    
-    @Test(groups="Integration")
-    public void testRebindToJavaApp() throws Exception {
-        VanillaJavaApp javaProcess = app.addChild(EntitySpec.create(VanillaJavaApp.class, TestingJavaOptsVanillaJavaAppImpl.class)
-            .configure("main", MAIN_CLASS.getCanonicalName()).configure("classpath", ImmutableList.of(BROOKLYN_THIS_CLASSPATH)));
-
-        Entities.manage(javaProcess);
-        app.start(ImmutableList.of(loc));
-
-        rebind();
-        VanillaJavaApp javaProcess2 = (VanillaJavaApp) Iterables.find(app.getChildren(), Predicates.instanceOf(VanillaJavaApp.class));
-        
-        EntityTestUtils.assertAttributeEqualsEventually(javaProcess2, VanillaJavaApp.SERVICE_UP, true);
-    }
-
-    @Test(groups="Integration")
-    public void testRebindToKilledJavaApp() throws Exception {
-        VanillaJavaApp javaProcess = app.addChild(EntitySpec.create(VanillaJavaApp.class, TestingJavaOptsVanillaJavaAppImpl.class)
-            .configure("main", MAIN_CLASS.getCanonicalName()).configure("classpath", ImmutableList.of(BROOKLYN_THIS_CLASSPATH)));
-        Entities.manage(javaProcess);
-        app.start(ImmutableList.of(loc));
-        javaProcess.kill();
-        
-        long starttime = System.currentTimeMillis();
-        rebind();
-        long rebindTime = System.currentTimeMillis() - starttime;
-        
-        VanillaJavaApp javaProcess2 = (VanillaJavaApp) Iterables.find(app.getChildren(), Predicates.instanceOf(VanillaJavaApp.class));
-        EntityTestUtils.assertAttributeEqualsEventually(javaProcess2, VanillaJavaApp.SERVICE_UP, false);
-        
-        // check that it was quick (previously it hung)
-        assertTrue(rebindTime < 30*1000, "rebindTime="+rebindTime);
-    }
-    
-    
-    @Test(groups="Integration")
-    public void testEnrichersOnRebindJavaApp() throws Exception {
-        VanillaJavaApp javaProcess = app.addChild(EntitySpec.create(VanillaJavaApp.class, EnrichedVanillaJavaAppImpl.class)
-            .configure("main", MAIN_CLASS.getCanonicalName()).configure("classpath", ImmutableList.of(BROOKLYN_THIS_CLASSPATH)));
-
-        Entities.manage(javaProcess);
-        app.start(ImmutableList.of(loc));
-
-        EntityTestUtils.assertAttributeEventuallyNonNull(javaProcess, EnrichedVanillaJavaAppImpl.AVG1);
-        EntityTestUtils.assertAttributeEventuallyNonNull(javaProcess, EnrichedVanillaJavaAppImpl.AVG2);
-        LOG.info("Got avg "+javaProcess.getAttribute(EnrichedVanillaJavaAppImpl.AVG1));
-
-        rebind();
-        VanillaJavaApp javaProcess2 = (VanillaJavaApp) Iterables.find(app.getChildren(), Predicates.instanceOf(VanillaJavaApp.class));
-
-        // check sensors working
-        EntityTestUtils.assertAttributeChangesEventually(javaProcess2, EnrichedVanillaJavaAppImpl.PROCESS_CPU_TIME); 
-        LOG.info("Avg now "+javaProcess2.getAttribute(EnrichedVanillaJavaAppImpl.AVG1));
-        
-        // check enrichers are functioning
-        EntityTestUtils.assertAttributeChangesEventually(javaProcess2, EnrichedVanillaJavaAppImpl.AVG1); 
-        EntityTestUtils.assertAttributeChangesEventually(javaProcess2, EnrichedVanillaJavaAppImpl.AVG2);
-        LOG.info("Avg now "+javaProcess2.getAttribute(EnrichedVanillaJavaAppImpl.AVG1));
-        
-        // and check we don't have too many
-        Assert.assertEquals(javaProcess2.getEnrichers().size(), javaProcess.getEnrichers().size());
-    }
-
-    public static class EnrichedVanillaJavaAppImpl extends VanillaJavaAppImpl {
-        private static final AttributeSensor<Double> AVG1 = Sensors.newDoubleSensor("avg1");
-        private static final AttributeSensor<Double> AVG2 = Sensors.newDoubleSensor("avg2");
-        
-        @Override
-        public void onManagementStarted() {
-            super.onManagementStarted();
-            LOG.info("mgmt started for "+this);
-            addEnricher(new RollingTimeWindowMeanEnricher<Double>(this, PROCESS_CPU_TIME, AVG1, Duration.TEN_SECONDS));
-        }
-        @Override
-        protected void connectSensors() {
-            super.connectSensors();
-            LOG.info("connecting sensors for "+this);
-            addEnricher(new RollingTimeWindowMeanEnricher<Double>(this, PROCESS_CPU_TIME, AVG2, Duration.TEN_SECONDS));
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/java/VanillaJavaAppTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/java/VanillaJavaAppTest.java b/software/base/src/test/java/brooklyn/entity/java/VanillaJavaAppTest.java
deleted file mode 100644
index 072c7f8..0000000
--- a/software/base/src/test/java/brooklyn/entity/java/VanillaJavaAppTest.java
+++ /dev/null
@@ -1,350 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertTrue;
-
-import java.net.MalformedURLException;
-import java.security.KeyStore;
-import java.security.PrivateKey;
-import java.security.cert.Certificate;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-import javax.management.remote.JMXConnector;
-import javax.management.remote.JMXConnectorFactory;
-import javax.management.remote.JMXServiceURL;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.sensor.SensorEvent;
-import org.apache.brooklyn.api.sensor.SensorEventListener;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.ResourceUtils;
-import org.apache.brooklyn.util.core.crypto.FluentKeySigner;
-import org.apache.brooklyn.util.core.crypto.SecureKeys;
-import org.apache.brooklyn.util.crypto.SslTrustUtils;
-import org.apache.brooklyn.util.jmx.jmxmp.JmxmpAgent;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.event.feed.jmx.JmxHelper;
-
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.PortRanges;
-
-import com.google.common.base.Predicate;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Maps;
-
-public class VanillaJavaAppTest {
-
-    private static final Logger LOG = LoggerFactory.getLogger(VanillaJavaAppTest.class);
-    
-    private static final long TIMEOUT_MS = 10*1000;
-
-    // Static attributes such as number of processors and start time are only polled every 60 seconds
-    // so if they are not immediately available, it will be 60 seconds before they are polled again
-    private static final Object LONG_TIMEOUT_MS = 61*1000;
-
-    private static String BROOKLYN_THIS_CLASSPATH = null;
-    private static Class<?> MAIN_CLASS = ExampleVanillaMain.class;
-    private static Class<?> MAIN_CPU_HUNGRY_CLASS = ExampleVanillaMainCpuHungry.class;
-    
-    private TestApplication app;
-    private LocalhostMachineProvisioningLocation loc;
-
-    @BeforeMethod(alwaysRun = true)
-    public void setUp() throws Exception {
-        if (BROOKLYN_THIS_CLASSPATH==null) {
-            BROOKLYN_THIS_CLASSPATH = ResourceUtils.create(MAIN_CLASS).getClassLoaderDir();
-        }
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        loc = app.newLocalhostProvisioningLocation(MutableMap.of("address", "localhost"));
-    }
-
-    @AfterMethod(alwaysRun = true)
-    public void tearDown() throws Exception {
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-    }
-
-    @Test
-    public void testReadsConfigFromFlags() throws Exception {
-        final VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
-            .configure("main", "my.Main").configure("classpath", ImmutableList.of("c1", "c2"))
-            .configure("args", ImmutableList.of("a1", "a2")));
-
-        assertEquals(javaProcess.getMainClass(), "my.Main");
-        assertEquals(javaProcess.getClasspath(), ImmutableList.of("c1","c2"));
-        assertEquals(javaProcess.getConfig(VanillaJavaApp.ARGS), ImmutableList.of("a1", "a2"));
-    }
-
-    @Test(groups={"WIP", "Integration"})
-    public void testJavaSystemProperties() throws Exception {
-        final VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
-            .configure("main", "my.Main").configure("classpath", ImmutableList.of("c1", "c2"))
-            .configure("args", ImmutableList.of("a1", "a2")));
-        ((EntityLocal)javaProcess).setConfig(UsesJava.JAVA_SYSPROPS, ImmutableMap.of("fooKey", "fooValue", "barKey", "barValue"));
-        // TODO: how to test: launch standalone app that outputs system properties to stdout? Probe via JMX?
-    }
-
-    @Test(groups={"Integration"})
-    public void testStartsAndStops() throws Exception {
-        String main = MAIN_CLASS.getCanonicalName();
-        final VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
-            .configure("main", main).configure("classpath", ImmutableList.of(BROOKLYN_THIS_CLASSPATH))
-            .configure("args", ImmutableList.of()));
-        app.start(ImmutableList.of(loc));
-        assertEquals(javaProcess.getAttribute(VanillaJavaApp.SERVICE_STATE_ACTUAL), Lifecycle.RUNNING);
-
-        javaProcess.stop();
-        assertEquals(javaProcess.getAttribute(VanillaJavaApp.SERVICE_STATE_ACTUAL), Lifecycle.STOPPED);
-    }
-
-    @Test(groups={"Integration"})
-    public void testHasJvmMXBeanSensorVals() throws Exception {
-        String main = MAIN_CLASS.getCanonicalName();
-        final VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
-            .configure("main", main).configure("classpath", ImmutableList.of(BROOKLYN_THIS_CLASSPATH))
-            .configure("args", ImmutableList.of()));
-        app.start(ImmutableList.of(loc));
-        
-        // Memory MXBean
-        Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
-            public void run() {
-                assertNotNull(javaProcess.getAttribute(VanillaJavaApp.NON_HEAP_MEMORY_USAGE));
-                long init = javaProcess.getAttribute(VanillaJavaApp.INIT_HEAP_MEMORY);
-                long used = javaProcess.getAttribute(VanillaJavaApp.USED_HEAP_MEMORY);
-                long committed = javaProcess.getAttribute(VanillaJavaApp.COMMITTED_HEAP_MEMORY);
-                long max = javaProcess.getAttribute(VanillaJavaApp.MAX_HEAP_MEMORY);
-    
-                assertNotNull(used);
-                assertNotNull(init);
-                assertNotNull(committed);
-                assertNotNull(max);
-                assertTrue(init <= max, String.format("init %d > max %d heap memory", init, max));
-                assertTrue(used <= committed, String.format("used %d > committed %d heap memory", used, committed));
-                assertTrue(committed <= max, String.format("committed %d > max %d heap memory", committed, max));
-            }});
-        
-        // Threads MX Bean
-        Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
-            public void run() {
-                long current = javaProcess.getAttribute(VanillaJavaApp.CURRENT_THREAD_COUNT);
-                long peak = javaProcess.getAttribute(VanillaJavaApp.PEAK_THREAD_COUNT);
-    
-                assertNotNull(current);
-                assertNotNull(peak);
-                assertTrue(current <= peak, String.format("current %d > peak %d thread count", current, peak));
-            }});
-
-        // Runtime MX Bean
-        Asserts.succeedsEventually(MutableMap.of("timeout", LONG_TIMEOUT_MS), new Runnable() {
-            public void run() {
-                assertNotNull(javaProcess.getAttribute(VanillaJavaApp.START_TIME));
-                assertNotNull(javaProcess.getAttribute(VanillaJavaApp.UP_TIME));
-            }});
-        
-        // Operating System MX Bean
-        Asserts.succeedsEventually(MutableMap.of("timeout", LONG_TIMEOUT_MS), new Runnable() {
-            public void run() {
-                assertNotNull(javaProcess.getAttribute(VanillaJavaApp.PROCESS_CPU_TIME));
-                assertNotNull(javaProcess.getAttribute(VanillaJavaApp.SYSTEM_LOAD_AVERAGE));
-                assertNotNull(javaProcess.getAttribute(VanillaJavaApp.AVAILABLE_PROCESSORS));
-                assertNotNull(javaProcess.getAttribute(VanillaJavaApp.TOTAL_PHYSICAL_MEMORY_SIZE));
-                assertNotNull(javaProcess.getAttribute(VanillaJavaApp.FREE_PHYSICAL_MEMORY_SIZE));
-            }});
-        // TODO work on providing useful metrics from garbage collector MX Bean
-        // assertNotNull(javaProcess.getAttribute(VanillaJavaApp.GARBAGE_COLLECTION_TIME)) TODO: work on providing this
-    }
-    
-    @Test(groups={"Integration"})
-    public void testJvmMXBeanProcessCpuTimeGivesNonZeroPercentage() throws Exception {
-        String main = MAIN_CPU_HUNGRY_CLASS.getCanonicalName();
-        final VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
-            .configure("main", main).configure("classpath", ImmutableList.of(BROOKLYN_THIS_CLASSPATH))
-            .configure("args", ImmutableList.of()));
-        app.start(ImmutableList.of(loc));
-
-        JavaAppUtils.connectJavaAppServerPolicies((EntityLocal)javaProcess);
-        
-        final List<Double> fractions = new CopyOnWriteArrayList<Double>();
-        app.getManagementContext().getSubscriptionManager().subscribe(javaProcess, VanillaJavaApp.PROCESS_CPU_TIME_FRACTION_LAST, new SensorEventListener<Double>() {
-                public void onEvent(SensorEvent<Double> event) {
-                    fractions.add(event.getValue());
-                }});
-        
-        // Expect non-trivial load to be generated by the process.
-        // Expect load to be in the right order of magnitude (to ensure we haven't got a decimal point in the wrong place etc);
-        // But with multi-core could get big number; and on jenkins@releng3 we once saw [11.9, 0.6, 0.5]!
-        Asserts.succeedsEventually(new Runnable() {
-            public void run() {
-                Iterable<Double> nonTrivialFractions = Iterables.filter(fractions, new Predicate<Double>() {
-                        public boolean apply(Double input) {
-                            return input > 0.01;
-                        }});
-                assertTrue(Iterables.size(nonTrivialFractions) > 3, "fractions="+fractions); 
-            }});
-
-        Iterable<Double> tooBigFractions = Iterables.filter(fractions, new Predicate<Double>() {
-                public boolean apply(Double input) {
-                    return input > 50;
-                }});
-        assertTrue(Iterables.isEmpty(tooBigFractions), "fractions="+fractions); 
-        
-        Iterable<Double> ballparkRightFractions = Iterables.filter(fractions, new Predicate<Double>() {
-                public boolean apply(Double input) {
-                    return input > 0.01 && input < 4;
-                }});
-        assertTrue(Iterables.size(ballparkRightFractions) >= (fractions.size() / 2), "fractions="+fractions);
-        
-        LOG.info("VanillaJavaApp->ExampleVanillaMainCpuHuntry: ProcessCpuTime fractions="+fractions);
-    }
-
-    @Test(groups={"Integration"})
-    public void testStartsWithJmxPortSpecifiedInConfig() throws Exception {
-        int port = 53405;
-        String main = MAIN_CLASS.getCanonicalName();
-        VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
-            .configure("main", main).configure("classpath", ImmutableList.of(BROOKLYN_THIS_CLASSPATH))
-            .configure("args", ImmutableList.of()));
-        ((EntityLocal)javaProcess).setConfig(UsesJmx.JMX_PORT, PortRanges.fromInteger(port));
-        app.start(ImmutableList.of(loc));
-
-        assertEquals(javaProcess.getAttribute(UsesJmx.JMX_PORT), (Integer)port);
-    }
-
-    // FIXME Way test was written requires JmxSensorAdapter; need to rewrite...  
-    @Test(groups={"Integration", "WIP"})
-    public void testStartsWithSecureJmxPortSpecifiedInConfig() throws Exception {
-        int port = 53406;
-        String main = MAIN_CLASS.getCanonicalName();
-        final VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
-            .configure("main", main).configure("classpath", ImmutableList.of(BROOKLYN_THIS_CLASSPATH))
-            .configure("args", ImmutableList.of()));
-        ((EntityLocal)javaProcess).setConfig(UsesJmx.JMX_PORT, PortRanges.fromInteger(port));
-        ((EntityLocal)javaProcess).setConfig(UsesJmx.JMX_SSL_ENABLED, true);
-        
-        app.start(ImmutableList.of(loc));
-        // will fail above if JMX can't connect, but also do some add'l checks
-        
-        assertEquals(javaProcess.getAttribute(UsesJmx.JMX_PORT), (Integer)port);
-
-        // good key+cert succeeds
-        new AsserterForJmxConnection(javaProcess)
-                .customizeSocketFactory(null, null)
-                .connect();
-        
-        // bad cert fails
-        Asserts.assertFails(new Callable<Void>() {
-            public Void call() throws Exception {
-                new AsserterForJmxConnection(javaProcess)
-                        .customizeSocketFactory(null, new FluentKeySigner("cheater").newCertificateFor("jmx-access-key", SecureKeys.newKeyPair()))
-                        .connect();
-                return null;
-            }});
-
-        // bad key fails
-        Asserts.assertFails(new Callable<Void>() {
-            public Void call() throws Exception {
-                new AsserterForJmxConnection(javaProcess)
-                        .customizeSocketFactory(SecureKeys.newKeyPair().getPrivate(), null)
-                        .connect();
-                return null;
-            }});
-        
-        // bad profile fails
-        Asserts.assertFails(new Callable<Void>() {
-            public Void call() throws Exception {
-                AsserterForJmxConnection asserter = new AsserterForJmxConnection(javaProcess);
-                asserter.putEnv("jmx.remote.profiles", JmxmpAgent.TLS_JMX_REMOTE_PROFILES);
-                asserter.customizeSocketFactory(SecureKeys.newKeyPair().getPrivate(), null)
-                        .connect();
-                return null;
-            }});
-    }
-
-    private static class AsserterForJmxConnection {
-        final VanillaJavaApp entity;
-        final JMXServiceURL url;
-        final Map<String,Object> env;
-        
-        @SuppressWarnings("unchecked")
-        public AsserterForJmxConnection(VanillaJavaApp e) throws MalformedURLException {
-            this.entity = e;
-            
-            JmxHelper jmxHelper = new JmxHelper((EntityLocal)entity);
-            this.url = new JMXServiceURL(jmxHelper.getUrl());
-            this.env = Maps.newLinkedHashMap(jmxHelper.getConnectionEnvVars());
-        }
-        
-        public JMXServiceURL getJmxUrl() throws MalformedURLException {
-            return url;
-        }
-        
-        public void putEnv(String key, Object val) {
-            env.put(key, val);
-        }
-        
-        public AsserterForJmxConnection customizeSocketFactory(PrivateKey customKey, Certificate customCert) throws Exception {
-            PrivateKey key = (customKey == null) ? entity.getConfig(UsesJmx.JMX_SSL_ACCESS_KEY) : customKey;
-            Certificate cert = (customCert == null) ? entity.getConfig(UsesJmx.JMX_SSL_ACCESS_CERT) : customCert;
-            
-            KeyStore ks = SecureKeys.newKeyStore();
-            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
-            if (key!=null) {
-                ks.setKeyEntry("brooklyn-jmx-access", key, "".toCharArray(), new Certificate[] {cert});
-            }
-            kmf.init(ks, "".toCharArray());
-
-            TrustManager tms =
-            // TODO use root cert for trusting server
-            //trustStore!=null ? SecureKeys.getTrustManager(trustStore) :
-                SslTrustUtils.TRUST_ALL;
-
-            SSLContext ctx = SSLContext.getInstance("TLSv1");
-            ctx.init(kmf.getKeyManagers(), new TrustManager[] {tms}, null);
-            SSLSocketFactory ssf = ctx.getSocketFactory();
-            env.put(JmxmpAgent.TLS_SOCKET_FACTORY_PROPERTY, ssf);
-            
-            return this;
-        }
-        
-        public JMXConnector connect() throws Exception {
-            return JMXConnectorFactory.connect(getJmxUrl(), env);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/machine/MachineEntityEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/machine/MachineEntityEc2LiveTest.java b/software/base/src/test/java/brooklyn/entity/machine/MachineEntityEc2LiveTest.java
deleted file mode 100644
index 717ee30..0000000
--- a/software/base/src/test/java/brooklyn/entity/machine/MachineEntityEc2LiveTest.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.machine;
-
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertTrue;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.test.Asserts;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-
-import brooklyn.entity.AbstractEc2LiveTest;
-
-public class MachineEntityEc2LiveTest extends AbstractEc2LiveTest {
-
-    @Override
-    protected void doTest(Location loc) throws Exception {
-        final MachineEntity server = app.createAndManageChild(EntitySpec.create(MachineEntity.class));
-        
-        app.start(ImmutableList.of(loc));
-        
-        Asserts.succeedsEventually(new Runnable() {
-            @Override public void run() {
-                assertNotNull(server.getAttribute(MachineEntity.UPTIME));
-                assertNotNull(server.getAttribute(MachineEntity.LOAD_AVERAGE));
-                assertNotNull(server.getAttribute(MachineEntity.CPU_USAGE));
-                assertNotNull(server.getAttribute(MachineEntity.FREE_MEMORY));
-                assertNotNull(server.getAttribute(MachineEntity.TOTAL_MEMORY));
-                assertNotNull(server.getAttribute(MachineEntity.USED_MEMORY));
-            }});
-        
-        String result = server.execCommand("MY_ENV=myval && echo start $MY_ENV");
-        assertTrue(result.contains("start myval"), "result="+result);
-    }
-    
-    @Test(enabled=false)
-    public void testDummy() {} // Convince testng IDE integration that this really does have test methods
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/machine/MachineEntityRebindTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/machine/MachineEntityRebindTest.java b/software/base/src/test/java/brooklyn/entity/machine/MachineEntityRebindTest.java
deleted file mode 100644
index ae85c23..0000000
--- a/software/base/src/test/java/brooklyn/entity/machine/MachineEntityRebindTest.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.machine;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestFixtureWithApp;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-
-import brooklyn.entity.basic.EmptySoftwareProcess;
-
-public class MachineEntityRebindTest extends RebindTestFixtureWithApp {
-
-    @Test(groups = "Integration")
-    public void testRebindToMachineEntity() throws Exception {
-        EmptySoftwareProcess machine = origApp.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class));
-        origApp.start(ImmutableList.of(origManagementContext.getLocationRegistry().resolve("localhost")));
-        EntityTestUtils.assertAttributeEqualsEventually(machine, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
-        rebind(false);
-        Entity machine2 = newManagementContext.getEntityManager().getEntity(machine.getId());
-        EntityTestUtils.assertAttributeEqualsEventually(machine2, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/pool/AbstractServerPoolTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/pool/AbstractServerPoolTest.java b/software/base/src/test/java/brooklyn/entity/pool/AbstractServerPoolTest.java
deleted file mode 100644
index 2470dd9..0000000
--- a/software/base/src/test/java/brooklyn/entity/pool/AbstractServerPoolTest.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.pool;
-
-import static org.testng.Assert.fail;
-
-import java.util.List;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-
-import brooklyn.entity.basic.EmptySoftwareProcess;
-
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-
-public abstract class AbstractServerPoolTest {
-
-    // Note not extending BrooklynAppUnitTestSupport because sub-classes of this are for live and for unit tests.
-    // Instead, we have to repeat that logic for setting SKIP_ON_BOX_BASE_DIR_RESOLUTION
-    
-    private static final int DEFAULT_POOL_SIZE = 3;
-
-    protected Location location;
-    protected ManagementContext mgmt;
-    protected TestApplication poolApp;
-    protected ServerPool pool;
-    private List<TestApplication> createdApps = Lists.newLinkedList();
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        createdApps.clear();
-        mgmt = createManagementContext();
-        location = createLocation();
-        EntitySpec<TestApplication> appSpec = EntitySpec.create(TestApplication.class)
-                .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, shouldSkipOnBoxBaseDirResolution());
-        poolApp = ApplicationBuilder.newManagedApp(appSpec, mgmt);
-
-        pool = poolApp.createAndManageChild(EntitySpec.create(ServerPool.class)
-                .configure(ServerPool.INITIAL_SIZE, getInitialPoolSize())
-                .configure(ServerPool.MEMBER_SPEC, EntitySpec.create(EmptySoftwareProcess.class)));
-        poolApp.start(ImmutableList.of(location));
-        EntityTestUtils.assertAttributeEqualsEventually(pool, Attributes.SERVICE_UP, true);
-        assertAvailableCountEventuallyEquals(getInitialPoolSize());
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        // Kills the apps before terminating the pool
-        for (TestApplication app : createdApps) {
-            Entities.destroy(app);
-        }
-        if (mgmt != null) {
-            Entities.destroyAll(mgmt);
-            mgmt = null;
-        }
-    }
-
-    protected int getInitialPoolSize() {
-        return DEFAULT_POOL_SIZE;
-    }
-
-    protected ManagementContext createManagementContext() {
-        return new LocalManagementContextForTests();
-    }
-    
-    protected boolean shouldSkipOnBoxBaseDirResolution() {
-        return true;
-    }
-
-    /** @return Creates a LocalhostMachineProvisioningLocation */
-    protected Location createLocation() {
-        return mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class));
-    }
-
-    protected void assertNoMachinesAvailableForApp(TestApplication app) {
-        try {
-            app.start(ImmutableList.of(pool.getDynamicLocation()));
-            fail("Expected exception when starting app with too many entities for pool");
-        } catch (Exception e) {
-            Throwable t = Exceptions.getFirstThrowableOfType(e, NoMachinesAvailableException.class);
-            if (t == null) {
-                throw new RuntimeException(e);
-            }
-        }
-    }
-
-    protected void assertAvailableCountEventuallyEquals(int count) {
-        assertAvailableCountEventuallyEquals(pool, count);
-    }
-
-    protected void assertAvailableCountEventuallyEquals(ServerPool pool, int count) {
-        EntityTestUtils.assertAttributeEqualsEventually(pool, ServerPool.AVAILABLE_COUNT, count);
-    }
-
-    protected void assertClaimedCountEventuallyEquals(int count) {
-        assertClaimedCountEventuallyEquals(pool, count);
-    }
-
-    protected void assertClaimedCountEventuallyEquals(ServerPool pool, Integer count) {
-        EntityTestUtils.assertAttributeEqualsEventually(pool, ServerPool.CLAIMED_COUNT, count);
-    }
-
-    protected TestApplication createAppWithChildren(int numChildren) {
-        if (numChildren < 0) fail("Invalid number of children for app: " + numChildren);
-        EntitySpec<TestApplication> appSpec = EntitySpec.create(TestApplication.class)
-                .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, shouldSkipOnBoxBaseDirResolution());
-        TestApplication app = ApplicationBuilder.newManagedApp(appSpec, mgmt);
-        while (numChildren-- > 0) {
-            app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class));
-        }
-        createdApps.add(app);
-        return app;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/pool/ServerPoolLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/pool/ServerPoolLiveTest.java b/software/base/src/test/java/brooklyn/entity/pool/ServerPoolLiveTest.java
deleted file mode 100644
index 8520a88..0000000
--- a/software/base/src/test/java/brooklyn/entity/pool/ServerPoolLiveTest.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.pool;
-
-import static org.testng.Assert.assertTrue;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.testng.annotations.Test;
-
-import com.google.common.base.CaseFormat;
-import com.google.common.collect.ImmutableList;
-
-public class ServerPoolLiveTest extends AbstractServerPoolTest {
-
-    public static final String PROVIDER = "softlayer";
-
-    protected BrooklynProperties brooklynProperties;
-
-    @Override
-    protected Location createLocation() {
-        // Image: {id=CENTOS_6_64, providerId=CENTOS_6_64, os={family=centos, version=6.5, description=CentOS / CentOS / 6.5-64 LAMP for Bare Metal, is64Bit=true}, description=CENTOS_6_64, status=AVAILABLE, loginUser=root}
-        Map<String, ?> allFlags = MutableMap.<String, Object>builder()
-                .put("provider", PROVIDER)
-                .put("tags", ImmutableList.of(getClass().getName()))
-                .put("vmNameMaxLength", 30)
-                .put("imageId", "CENTOS_6_64")
-                .build();
-        return mgmt.getLocationRegistry().resolve(PROVIDER, allFlags);
-    }
-
-    @Override
-    protected ManagementContext createManagementContext() {
-        String[] propsToRemove = new String[]{"imageId", "imageDescriptionRegex", "imageNameRegex", "inboundPorts", "hardwareId", "minRam"};
-
-        // Don't let any defaults from brooklyn.properties (except credentials) interfere with test
-        brooklynProperties = BrooklynProperties.Factory.newDefault();
-        for (String propToRemove : propsToRemove) {
-            for (String propVariant : ImmutableList.of(propToRemove, CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propToRemove))) {
-                brooklynProperties.remove("brooklyn.locations.jclouds." + PROVIDER + "." + propVariant);
-                brooklynProperties.remove("brooklyn.locations." + propVariant);
-                brooklynProperties.remove("brooklyn.jclouds." + PROVIDER + "." + propVariant);
-                brooklynProperties.remove("brooklyn.jclouds." + propVariant);
-            }
-        }
-
-        // Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can cause "stdin: is not a tty")
-        brooklynProperties.remove("brooklyn.ssh.config.scriptHeader");
-        return new LocalManagementContextForTests(brooklynProperties);
-    }
-
-    protected boolean shouldSkipOnBoxBaseDirResolution() {
-        return false;
-    }
-
-    @Override
-    protected int getInitialPoolSize() {
-        return 1;
-    }
-
-    @Test(groups = "Live")
-    public void testAppCanBeDeployedToPool() {
-        TestApplication app = createAppWithChildren(1);
-        app.start(ImmutableList.of(pool.getDynamicLocation()));
-        assertTrue(app.getAttribute(Attributes.SERVICE_UP));
-        for (Entity child : app.getChildren()) {
-            assertTrue(child.getAttribute(Attributes.SERVICE_UP));
-        }
-        TestApplication app2 = createAppWithChildren(1);
-        assertNoMachinesAvailableForApp(app2);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/pool/ServerPoolLocationResolverTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/pool/ServerPoolLocationResolverTest.java b/software/base/src/test/java/brooklyn/entity/pool/ServerPoolLocationResolverTest.java
deleted file mode 100644
index 7edbb90..0000000
--- a/software/base/src/test/java/brooklyn/entity/pool/ServerPoolLocationResolverTest.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.pool;
-
-import static org.testng.Assert.assertEquals;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-
-import brooklyn.entity.basic.EmptySoftwareProcess;
-
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.dynamic.DynamicLocation;
-
-public class ServerPoolLocationResolverTest {
-
-    private LocalManagementContext managementContext;
-    private Entity locationOwner;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        managementContext = new LocalManagementContextForTests(BrooklynProperties.Factory.newEmpty());
-        TestApplication t = ApplicationBuilder.newManagedApp(TestApplication.class, managementContext);
-        locationOwner = t.createAndManageChild(EntitySpec.create(ServerPool.class)
-                .configure(ServerPool.INITIAL_SIZE, 0)
-                .configure(ServerPool.MEMBER_SPEC, EntitySpec.create(EmptySoftwareProcess.class)));
-        Location poolLocation = managementContext.getLocationManager()
-                .createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class));
-        t.start(ImmutableList.of(poolLocation));
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (managementContext != null) Entities.destroyAll(managementContext);
-    }
-
-    @Test
-    public void testResolve() {
-        ServerPoolLocation location = resolve("pool:" + locationOwner.getId());
-        assertEquals(location.getOwner().getId(), locationOwner.getId());
-    }
-
-    @Test
-    public void testSetsDisplayName() {
-        ServerPoolLocation location = resolve("pool:" + locationOwner.getId() + ":(displayName=xyz)");
-        assertEquals(location.getDisplayName(), "xyz");
-    }
-
-    private ServerPoolLocation resolve(String val) {
-        Map<String, Object> flags = MutableMap.<String, Object>of(DynamicLocation.OWNER.getName(), locationOwner);
-        Location l = managementContext.getLocationRegistry().resolve(val, flags);
-        Assert.assertNotNull(l);
-        return (ServerPoolLocation) l;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/pool/ServerPoolRebindTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/pool/ServerPoolRebindTest.java b/software/base/src/test/java/brooklyn/entity/pool/ServerPoolRebindTest.java
deleted file mode 100644
index 19c3e36..0000000
--- a/software/base/src/test/java/brooklyn/entity/pool/ServerPoolRebindTest.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.pool;
-
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertTrue;
-
-import java.io.File;
-import java.util.Collection;
-
-import org.apache.brooklyn.api.entity.Application;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.mgmt.rebind.RebindOptions;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Predicates;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.io.Files;
-
-public class ServerPoolRebindTest extends AbstractServerPoolTest {
-
-    private static final Logger LOG = LoggerFactory.getLogger(ServerPoolRebindTest.class);
-    private ClassLoader classLoader = getClass().getClassLoader();
-    private File mementoDir;
-
-    @Override
-    protected ManagementContext createManagementContext() {
-        mementoDir = Files.createTempDir();
-        return RebindTestUtils.newPersistingManagementContext(mementoDir, classLoader);
-    }
-
-    @Override
-    @AfterMethod(alwaysRun = true)
-    public void tearDown() throws Exception {
-        super.tearDown();
-        if (mementoDir != null) RebindTestUtils.deleteMementoDir(mementoDir);
-    }
-
-    private Collection<Application> rebind(TestApplication app) throws Exception {
-        LOG.info("Rebind start");
-        RebindTestUtils.waitForPersisted(app);
-        ((LocalManagementContext) app.getManagementContext()).terminate();
-        Collection<Application> r = RebindTestUtils.rebindAll(RebindOptions.create().mementoDir(mementoDir).classLoader(classLoader));
-        LOG.info("Rebind complete");
-        return r;
-    }
-
-    @Test(enabled = false)
-    public void testRebindingToPool() throws Exception {
-        TestApplication app = createAppWithChildren(1);
-        app.start(ImmutableList.of(pool.getDynamicLocation()));
-        assertTrue(app.getAttribute(Attributes.SERVICE_UP));
-        assertAvailableCountEventuallyEquals(pool, getInitialPoolSize() - 1);
-        assertClaimedCountEventuallyEquals(pool, 1);
-
-        Collection<Application> reboundApps = rebind(poolApp);
-        ServerPool reboundPool = null;
-        for (Application reboundApp : reboundApps) {
-            Optional<Entity> np = Iterables.tryFind(reboundApp.getChildren(), Predicates.instanceOf(ServerPool.class));
-            if (np.isPresent()) {
-                mgmt = reboundApp.getManagementContext();
-                reboundPool = (ServerPool) np.get();
-                break;
-            }
-        }
-
-        assertNotNull(reboundPool, "No app in rebound context has " + ServerPool.class.getName() +
-                " child. Apps: " + reboundApps);
-        assertNotNull(reboundPool.getDynamicLocation());
-        assertTrue(reboundPool.getAttribute(Attributes.SERVICE_UP));
-        assertAvailableCountEventuallyEquals(reboundPool, getInitialPoolSize() - 1);
-        assertClaimedCountEventuallyEquals(reboundPool, 1);
-
-        TestApplication app2 = createAppWithChildren(1);
-        app2.start(ImmutableList.of(reboundPool.getDynamicLocation()));
-        assertTrue(app2.getAttribute(Attributes.SERVICE_UP));
-        assertAvailableCountEventuallyEquals(reboundPool, getInitialPoolSize() - 2);
-        assertClaimedCountEventuallyEquals(reboundPool, 2);
-
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/pool/ServerPoolTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/pool/ServerPoolTest.java b/software/base/src/test/java/brooklyn/entity/pool/ServerPoolTest.java
deleted file mode 100644
index d0310e2..0000000
--- a/software/base/src/test/java/brooklyn/entity/pool/ServerPoolTest.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.pool;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
-import java.util.Collection;
-import java.util.Iterator;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine;
-
-import com.google.common.base.Joiner;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-
-public class ServerPoolTest extends AbstractServerPoolTest {
-
-    private static final Logger LOG = LoggerFactory.getLogger(ServerPoolTest.class);
-
-    @Test
-    public void testAppCanBeDeployedToServerPool() {
-        TestApplication app = createAppWithChildren(1);
-        app.start(ImmutableList.of(pool.getDynamicLocation()));
-        assertTrue(app.getAttribute(Attributes.SERVICE_UP));
-        for (Entity child : app.getChildren()) {
-            assertTrue(child.getAttribute(Attributes.SERVICE_UP));
-        }
-    }
-
-    @Test
-    public void testFailureWhenNotEnoughServersAvailable() {
-        TestApplication app = createAppWithChildren(getInitialPoolSize() + 1);
-        assertNoMachinesAvailableForApp(app);
-        EntityTestUtils.assertAttributeEqualsEventually(app, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);
-    }
-
-    @Test
-    public void testDeployReleaseDeploy() {
-        TestApplication app = createAppWithChildren(getInitialPoolSize());
-        TestApplication app2 = createAppWithChildren(1);
-
-        app.start(ImmutableList.of(pool.getDynamicLocation()));
-        EntityTestUtils.assertAttributeEqualsEventually(app, Attributes.SERVICE_UP, true);
-        assertAvailableCountEventuallyEquals(0);
-        assertNoMachinesAvailableForApp(app2);
-
-        app.stop();
-        assertFalse(app.getAttribute(Attributes.SERVICE_UP));
-        assertAvailableCountEventuallyEquals(getInitialPoolSize());
-
-        app2.start(ImmutableList.of(pool.getDynamicLocation()));
-        EntityTestUtils.assertAttributeEqualsEventually(app2, Attributes.SERVICE_UP, true);
-        
-        assertAvailableCountEventuallyEquals(getInitialPoolSize() - 1);
-        assertClaimedCountEventuallyEquals(1);
-    }
-
-    @Test
-    public void testResizingPoolUp() {
-        TestApplication app = createAppWithChildren(getInitialPoolSize());
-        app.start(ImmutableList.of(pool.getDynamicLocation()));
-        assertTrue(app.getAttribute(Attributes.SERVICE_UP));
-
-        TestApplication app2 = createAppWithChildren(1);
-        assertNoMachinesAvailableForApp(app2);
-
-        pool.resizeByDelta(1);
-        
-        assertAvailableCountEventuallyEquals(1);
-
-        assertEquals((int) pool.getCurrentSize(), getInitialPoolSize() + 1);
-        app2.start(ImmutableList.of(pool.getDynamicLocation()));
-        assertTrue(app2.getAttribute(Attributes.SERVICE_UP));
-    }
-
-    @Test
-    public void testResizePoolDownSucceedsWhenEnoughMachinesAreFree() {
-        TestApplication app = createAppWithChildren(1);
-        app.start(ImmutableList.of(pool.getDynamicLocation()));
-        assertAvailableCountEventuallyEquals(getInitialPoolSize() - 1);
-
-        pool.resize(1);
-
-        assertAvailableCountEventuallyEquals(0);
-    }
-
-    @Test
-    public void testResizeDownDoesNotReleaseClaimedMachines() {
-        TestApplication app = createAppWithChildren(getInitialPoolSize() - 1);
-        app.start(ImmutableList.of(pool.getDynamicLocation()));
-        assertAvailableCountEventuallyEquals(1);
-        assertClaimedCountEventuallyEquals(getInitialPoolSize() - 1);
-
-        LOG.info("Test attempting to resize to 0 members. Should only drop the one available machine.");
-        pool.resize(0);
-
-        assertAvailableCountEventuallyEquals(0);
-        assertEquals(Iterables.size(pool.getMembers()), getInitialPoolSize() - 1);
-        assertAvailableCountEventuallyEquals(0);
-        assertClaimedCountEventuallyEquals(getInitialPoolSize() - 1);
-    }
-
-    @Test
-    public void testCanAddExistingMachinesToPool() {
-        TestApplication app = createAppWithChildren(getInitialPoolSize());
-        app.start(ImmutableList.of(pool.getDynamicLocation()));
-        assertAvailableCountEventuallyEquals(0);
-
-        LocalhostMachine loc = mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachine.class));
-        Entity added = pool.addExistingMachine(loc);
-        assertFalse(added.getConfig(ServerPoolImpl.REMOVABLE));
-        assertAvailableCountEventuallyEquals(1);
-
-        TestApplication app2 = createAppWithChildren(1);
-        app2.start(ImmutableList.of(pool.getDynamicLocation()));
-        assertAvailableCountEventuallyEquals(0);
-    }
-
-    @Test
-    public void testExistingMachinesAreNotRemovedFromThePoolOnShrinkButAreOnStop() {
-        LocalhostMachine loc = mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachine.class));
-        pool.addExistingMachine(loc);
-        assertAvailableCountEventuallyEquals(getInitialPoolSize() + 1);
-        pool.resize(0);
-        assertAvailableCountEventuallyEquals(1);
-        pool.stop();
-        assertAvailableCountEventuallyEquals(0);
-    }
-
-    @Test
-    public void testAddExistingMachineFromSpec() {
-        TestApplication app = createAppWithChildren(getInitialPoolSize());
-        app.start(ImmutableList.of(pool.getDynamicLocation()));
-        assertAvailableCountEventuallyEquals(0);
-
-        Collection<Entity> added = pool.addExistingMachinesFromSpec("byon:(hosts=\"localhost,localhost\")");
-        assertEquals(added.size(), 2, "Added: " + Joiner.on(", ").join(added));
-        Iterator<Entity> it = added.iterator();
-        assertFalse(it.next().getConfig(ServerPoolImpl.REMOVABLE));
-        assertFalse(it.next().getConfig(ServerPoolImpl.REMOVABLE));
-        assertAvailableCountEventuallyEquals(2);
-
-        TestApplication app2 = createAppWithChildren(2);
-        app2.start(ImmutableList.of(pool.getDynamicLocation()));
-        assertAvailableCountEventuallyEquals(0);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/service/SystemServiceEnricherTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/service/SystemServiceEnricherTest.java b/software/base/src/test/java/brooklyn/entity/service/SystemServiceEnricherTest.java
deleted file mode 100644
index 4406f4f..0000000
--- a/software/base/src/test/java/brooklyn/entity/service/SystemServiceEnricherTest.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.service;
-
-import static org.testng.Assert.assertEquals;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.sensor.EnricherSpec;
-import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
-import org.apache.brooklyn.effector.core.EffectorTasks;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.core.EntityPredicates;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.VanillaSoftwareProcess;
-import brooklyn.entity.basic.VanillaSoftwareProcessImpl;
-import brooklyn.entity.basic.VanillaSoftwareProcessSshDriver;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.location.jclouds.JcloudsLocation;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.ssh.BashCommands;
-import org.apache.brooklyn.util.time.Duration;
-
-import com.google.common.base.Suppliers;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-public class SystemServiceEnricherTest extends BrooklynAppLiveTestSupport {
-    //requires /etc/init.d OS, for example CentOS 6.5
-    private static final String LOCATION_SPEC = "named:service-live-test-location";
-    private JcloudsLocation location;
-
-    @Override
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        super.setUp();
-        location = (JcloudsLocation) mgmt.getLocationRegistry().resolve(LOCATION_SPEC);
-    }
-
-    @Test(groups = "Live")
-    public void testRestartLaunchesService() {
-        String launchCmd = "nohup bash -c \"echo \\$\\$ > $PID_FILE; while true; do sleep 1000; done\" &";
-        EntitySpec<VanillaSoftwareProcess> procSpec = EntitySpec.create(VanillaSoftwareProcess.class)
-                .configure(VanillaSoftwareProcess.LAUNCH_COMMAND, launchCmd)
-                .enricher(EnricherSpec.create(SystemServiceEnricher.class));
-        VanillaSoftwareProcess proc = app.createAndManageChild(procSpec);
-        app.start(ImmutableList.of(location));
-
-        waitHealthy(proc);
-
-        SshMachineLocation machine = EffectorTasks.getSshMachine(proc);
-        String pidFile = getPidFile(proc);
-        String killCmd = "kill -9 `cat " + pidFile + "`";
-        machine.execCommands("kill process", ImmutableList.of(killCmd));
-
-        waitFailed(proc);
-
-        int restartCode = machine.execCommands("restart machine", ImmutableList.of(BashCommands.sudo("/sbin/shutdown -r now")));
-        assertEquals(restartCode, 0);
-
-        waitHealthy(proc);
-    }
-
-    private String getPidFile(VanillaSoftwareProcess proc) {
-        VanillaSoftwareProcessImpl impl = (VanillaSoftwareProcessImpl)Entities.deproxy(proc);
-        return ((VanillaSoftwareProcessSshDriver)impl.getDriver()).getPidFile();
-    }
-
-    private void waitFailed(VanillaSoftwareProcess proc) {
-        Asserts.eventually(ImmutableMap.of("timeout", Duration.FIVE_MINUTES), Suppliers.ofInstance(proc), EntityPredicates.attributeEqualTo(Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE));
-    }
-
-    private void waitHealthy(VanillaSoftwareProcess proc) {
-        Asserts.eventually(ImmutableMap.of("timeout", Duration.FIVE_MINUTES), Suppliers.ofInstance(proc), EntityPredicates.attributeEqualTo(Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING));
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/AbstractDockerLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/software/AbstractDockerLiveTest.java b/software/base/src/test/java/brooklyn/entity/software/AbstractDockerLiveTest.java
deleted file mode 100644
index 1dea4ca..0000000
--- a/software/base/src/test/java/brooklyn/entity/software/AbstractDockerLiveTest.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software;
-
-import com.google.common.base.CaseFormat;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import java.util.List;
-import java.util.Map;
-
-/**
- * Runs a test with many different distros and versions.
- */
-public abstract class AbstractDockerLiveTest {
-    
-    public static final String PROVIDER = "docker";
-
-    protected BrooklynProperties brooklynProperties;
-    protected ManagementContext ctx;
-    
-    protected TestApplication app;
-    protected Location jcloudsLocation;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        List<String> propsToRemove = ImmutableList.of("imageDescriptionRegex", "imageNameRegex", "inboundPorts",
-                "hardwareId", "minRam");
-        
-     // Don't let any defaults from brooklyn.properties (except credentials) interfere with test
-        brooklynProperties = BrooklynProperties.Factory.newDefault();
-        for (String propToRemove : propsToRemove) {
-            for (String propVariant : ImmutableList.of(propToRemove, CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propToRemove))) {
-                brooklynProperties.remove("brooklyn.locations.jclouds."+PROVIDER+"."+propVariant);
-                brooklynProperties.remove("brooklyn.locations."+propVariant);
-                brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+"."+propVariant);
-                brooklynProperties.remove("brooklyn.jclouds."+propVariant);
-            }
-        }
-
-        // Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can cause "stdin: is not a tty")
-        brooklynProperties.remove("brooklyn.ssh.config.scriptHeader");
-        
-        ctx = new LocalManagementContext(brooklynProperties);
-        app = ApplicationBuilder.newManagedApp(TestApplication.class, ctx);
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (app != null) Entities.destroyAllCatching(app.getManagementContext());
-    }
-
-    @Test(groups={"Live", "WIP"})
-    public void test_Ubuntu_13_10() throws Exception {
-          runTest(ImmutableMap.of("imageId", "7fe2ec2ff748c411cf0d6833120741778c00e1b07a83c4104296b6258b5331c4",
-              "loginUser", "root",
-              "loginUser.password", "password"));
-     }
-
-    protected void runTest(Map<String,?> flags) throws Exception {
-        String tag = getClass().getSimpleName().toLowerCase();
-        Map<String,?> allFlags = MutableMap.<String,Object>builder()
-                .put("tags", ImmutableList.of(tag))
-                .putAll(flags)
-                .build();
-        jcloudsLocation = ctx.getLocationRegistry().resolve(PROVIDER, allFlags);
-        doTest(jcloudsLocation);
-    }
-
-    protected abstract void doTest(Location loc) throws Exception;
-}



[12/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/event/feed/jmx/JmxHelperTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/event/feed/jmx/JmxHelperTest.java b/software/base/src/test/java/brooklyn/event/feed/jmx/JmxHelperTest.java
deleted file mode 100644
index 91bed65..0000000
--- a/software/base/src/test/java/brooklyn/event/feed/jmx/JmxHelperTest.java
+++ /dev/null
@@ -1,311 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.event.feed.jmx;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.fail;
-
-import java.io.IOException;
-import java.util.List;
-
-import javax.management.DynamicMBean;
-import javax.management.MBeanOperationInfo;
-import javax.management.MBeanParameterInfo;
-import javax.management.Notification;
-import javax.management.NotificationListener;
-import javax.management.ObjectName;
-import javax.management.StandardEmitterMBean;
-
-import org.apache.brooklyn.test.TestUtils;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.jclouds.util.Throwables2;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.testng.collections.Lists;
-
-import brooklyn.test.GeneralisedDynamicMBean;
-import brooklyn.test.JmxService;
-
-import com.google.common.base.Function;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-public class JmxHelperTest {
-
-    private static final Logger log = LoggerFactory.getLogger(JmxHelperTest.class);
-    
-    private static final String LOCALHOST_NAME = "localhost";
-    
-    private static final int TIMEOUT_MS = 5000;
-    private static final int SHORT_WAIT_MS = 250;
-
-    private JmxService jmxService;
-    private JmxHelper jmxHelper;
-    
-    private String objectName = "Brooklyn:type=MyTestMBean,name=myname";
-    private String objectNameWithWildcard = "Brooklyn:type=MyTestMBean,name=mynam*";
-    private ObjectName jmxObjectName;
-    private ObjectName jmxObjectNameWithWildcard;
-    private String attributeName = "myattrib";
-    private String opName = "myop";
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        jmxObjectName = new ObjectName(objectName);
-        jmxObjectNameWithWildcard = new ObjectName(objectNameWithWildcard);
-        jmxService = newJmxServiceRetrying(LOCALHOST_NAME, 5);
-        jmxHelper = new JmxHelper(jmxService.getUrl());
-        jmxHelper.setMinTimeBetweenReconnectAttempts(0);
-        jmxHelper.connect(TIMEOUT_MS);
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (jmxHelper != null) jmxHelper.disconnect();
-        if (jmxService != null) jmxService.shutdown();
-        jmxHelper = null;
-        jmxService = null;
-    }
-
-    @Test
-    public void testGetAttribute() throws Exception {
-        GeneralisedDynamicMBean mbean = jmxService.registerMBean(MutableMap.of("myattr", "myval"), objectName);
-        assertEquals(jmxHelper.getAttribute(jmxObjectName, "myattr"), "myval");
-    }
-
-    @Test
-    public void testGetAttributeUsingObjectNameWildcard() throws Exception {
-        GeneralisedDynamicMBean mbean = jmxService.registerMBean(MutableMap.of("myattr", "myval"), objectName);
-        assertEquals(jmxHelper.getAttribute(jmxObjectNameWithWildcard, "myattr"), "myval");
-    }
-
-    @Test
-    public void testSetAttribute() throws Exception {
-        DynamicMBean mbean = jmxService.registerMBean(MutableMap.of("myattr", "myval"), objectName);
-
-        jmxHelper.setAttribute(jmxObjectName, "myattr", "abc");
-        Object actual = jmxHelper.getAttribute(jmxObjectName, "myattr");
-        assertEquals(actual, "abc");
-    }
-
-    @Test
-    public void testSetAttributeUsingObjectNameWildcard() throws Exception {
-        DynamicMBean mbean = jmxService.registerMBean(MutableMap.of("myattr", "myval"), objectName);
-
-        jmxHelper.setAttribute(jmxObjectNameWithWildcard, "myattr", "abc");
-        Object actual = jmxHelper.getAttribute(jmxObjectName, "myattr");
-        assertEquals(actual, "abc");
-    }
-
-    @Test
-    public void testInvokeOperationWithNoArgs() throws Exception {
-        final String opReturnVal = "my result";
-        MBeanOperationInfo opInfo = new MBeanOperationInfo(opName, "my descr", new MBeanParameterInfo[0], String.class.getName(), MBeanOperationInfo.ACTION);
-        Function<Object[], String> opImpl = new Function<Object[], String>() {
-            @Override public String apply(Object[] args) {
-                assertEquals(args.length, 0, "args="+args);
-                return opReturnVal;
-            }
-        };
-        GeneralisedDynamicMBean mbean = jmxService.registerMBean(ImmutableMap.of(), ImmutableMap.of(opInfo, opImpl), objectName);
-        
-        assertEquals(jmxHelper.operation(objectName, opName), opReturnVal);
-    }
-
-    @Test
-    public void testInvokeOperationUsingObjectNameWildcard() throws Exception {
-        final String opReturnVal = "my result";
-        MBeanOperationInfo opInfo = new MBeanOperationInfo(opName, "my descr", new MBeanParameterInfo[0], String.class.getName(), MBeanOperationInfo.ACTION);
-        Function<Object[], String> opImpl = new Function<Object[], String>() {
-            @Override public String apply(Object[] args) {
-                assertEquals(args.length, 0, "args="+args);
-                return opReturnVal;
-            }
-        };
-        GeneralisedDynamicMBean mbean = jmxService.registerMBean(ImmutableMap.of(), ImmutableMap.of(opInfo, opImpl), objectName);
-        
-        assertEquals(jmxHelper.operation(objectNameWithWildcard, opName), opReturnVal);
-    }
-
-    @Test
-    public void testInvokeOperationWithArgs() throws Exception {
-        final String opReturnPrefix = "my result prefix/";
-        String opParam1 = "my param 1";
-        MBeanOperationInfo opInfo = new MBeanOperationInfo(
-                opName, 
-                "my descr", 
-                new MBeanParameterInfo[] {new MBeanParameterInfo("myParam1", String.class.getName(), "my param1 descr")}, 
-                String.class.getName(), 
-                MBeanOperationInfo.ACTION);
-        Function<Object[],String> opImpl = new Function<Object[],String>() {
-            public String apply(Object[] input) {
-                return opReturnPrefix+input[0];
-            }
-        };
-        GeneralisedDynamicMBean mbean = jmxService.registerMBean(ImmutableMap.of(), ImmutableMap.of(opInfo, opImpl), objectName);
-        
-        assertEquals(jmxHelper.operation(objectName, opName, opParam1), opReturnPrefix+opParam1);
-    }
-
-    @Test
-    public void testReconnectsOnJmxServerTemporaryFailure() throws Exception {
-        int port = jmxService.getJmxPort();
-        GeneralisedDynamicMBean mbean = jmxService.registerMBean(MutableMap.of("myattr", "myval"), objectName);
-        assertEquals(jmxHelper.getAttribute(jmxObjectName, "myattr"), "myval");
-        
-        // Simulate temporary network-failure
-        jmxService.shutdown();
-
-        // Ensure that we have a failed query while the "network is down"         
-        try {
-            jmxHelper.getAttribute(jmxObjectName, attributeName);
-            fail();
-        } catch (Exception e) {
-            if (Throwables2.getFirstThrowableOfType(e, IOException.class) == null) {
-                throw e;
-            }
-        }
-
-        // Simulate the network restarting
-        jmxService = new JmxService(LOCALHOST_NAME, port);
-        
-        GeneralisedDynamicMBean mbean2 = jmxService.registerMBean(MutableMap.of("myattr", "myval2"), objectName);
-        assertEquals(jmxHelper.getAttribute(jmxObjectName, "myattr"), "myval2");
-    }
-    
-    @Test(expectedExceptions = {IllegalStateException.class})
-    public void testJmxCheckInstanceExistsEventuallyThrowsIfNotFound() throws Exception {
-        jmxHelper.assertMBeanExistsEventually(new ObjectName("Brooklyn:type=DoesNotExist,name=doesNotExist"), 1L);
-    }
-
-    @Test
-    public void testJmxObjectCheckExistsEventuallyReturnsIfFoundImmediately() throws Exception {
-        GeneralisedDynamicMBean mbean = jmxService.registerMBean(objectName);
-        jmxHelper.assertMBeanExistsEventually(jmxObjectName, 1L);
-    }
-
-    @Test
-    public void testJmxObjectCheckExistsEventuallyTakingLongReturnsIfFoundImmediately() throws Exception {
-        GeneralisedDynamicMBean mbean = jmxService.registerMBean(objectName);
-        jmxHelper.assertMBeanExistsEventually(jmxObjectName, 1L);
-    }
-
-    @Test
-    public void testJmxObjectCheckExistsEventuallyReturnsIfCreatedDuringPolling() throws Exception {
-        Thread t = new Thread(new Runnable() {
-                public void run() {
-                    try {
-                        Thread.sleep(SHORT_WAIT_MS);
-                        GeneralisedDynamicMBean mbean = jmxService.registerMBean(objectName);
-                    } catch (InterruptedException e) {
-                        return; // graceful return
-                    } catch (Exception e) {
-                        throw Exceptions.propagate(e);
-                    }
-                }});
-        try {
-            t.start();
-            
-            jmxHelper.assertMBeanExistsEventually(jmxObjectName, TIMEOUT_MS);
-        } finally {
-            t.interrupt();
-            t.join(TIMEOUT_MS);
-            assertFalse(t.isAlive());
-        }        
-    }
-
-    @Test
-    public void testSubscribeToJmxNotificationsDirectlyWithJmxHelper() throws Exception {
-        StandardEmitterMBean mbean = jmxService.registerMBean(ImmutableList.of("one"), objectName);
-        int sequence = 0;
-        final List<Notification> received = Lists.newArrayList();
-
-        jmxHelper.addNotificationListener(jmxObjectName, new NotificationListener() {
-            public void handleNotification(Notification notif, Object callback) {
-                received.add(notif);
-            }});
-                    
-
-        final Notification notif = sendNotification(mbean, "one", sequence++, "abc");
-
-        TestUtils.executeUntilSucceeds(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
-            public void run() {
-                assertEquals(received.size(), 1);
-                assertNotificationsEqual(received.get(0), notif);
-            }});
-    }
-
-    // Visual-inspection test that LOG.warn happens only once; TODO setup a listener to the logging output
-    @Test
-    public void testMBeanNotFoundLoggedOnlyOncePerUrl() throws Exception {
-        ObjectName wrongObjectName = new ObjectName("DoesNotExist:type=DoesNotExist");
-
-        // Expect just one log message about:
-        //     JMX object DoesNotExist:type=DoesNotExist not found at service:jmx:rmi://localhost:1099/jndi/rmi://localhost:9001/jmxrmi"
-        for (int i = 0; i < 10; i++) {
-            jmxHelper.findMBean(wrongObjectName);
-        }
-
-        jmxService.shutdown();
-        jmxHelper.disconnect();
-        
-        jmxService = newJmxServiceRetrying(LOCALHOST_NAME, 5);
-        jmxHelper = new JmxHelper(jmxService.getUrl());
-        jmxHelper.connect();
-        
-        // Expect just one log message about:
-        //     JMX object DoesNotExist:type=DoesNotExist not found at service:jmx:rmi://localhost:1099/jndi/rmi://localhost:9001/jmxrmi"
-        for (int i = 0; i < 10; i++) {
-            jmxHelper.findMBean(wrongObjectName);
-        }
-    }
-
-    private JmxService newJmxServiceRetrying(String host, int retries) throws Exception {
-        Exception lastexception = null;
-        for (int i = 0; i < retries; i++) {
-            try {
-                return new JmxService(host, (int)(11000+(500*Math.random())));
-            } catch (Exception e) {
-                log.debug("Unable to create JMX service during test - "+retries+" retries remaining");
-                lastexception = e;
-            }
-        }
-        throw lastexception;
-    }
-
-    private Notification sendNotification(StandardEmitterMBean mbean, String type, long seq, Object userData) {
-        Notification notif = new Notification(type, mbean, seq);
-        notif.setUserData(userData);
-        mbean.sendNotification(notif);
-        return notif;
-    }
-    
-    private void assertNotificationsEqual(Notification n1, Notification n2) {
-        assertEquals(n1.getType(), n2.getType());
-        assertEquals(n1.getSequenceNumber(), n2.getSequenceNumber());
-        assertEquals(n1.getUserData(), n2.getUserData());
-        assertEquals(n1.getTimeStamp(), n2.getTimeStamp());
-        assertEquals(n1.getMessage(), n2.getMessage());
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/event/feed/jmx/RebindJmxFeedTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/event/feed/jmx/RebindJmxFeedTest.java b/software/base/src/test/java/brooklyn/event/feed/jmx/RebindJmxFeedTest.java
deleted file mode 100644
index 271fd98..0000000
--- a/software/base/src/test/java/brooklyn/event/feed/jmx/RebindJmxFeedTest.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.event.feed.jmx;
-
-import static org.testng.Assert.assertEquals;
-
-import java.util.Collection;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.api.sensor.Feed;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestFixtureWithApp;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.core.test.entity.TestEntityImpl;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.java.UsesJmx;
-import brooklyn.entity.java.UsesJmx.JmxAgentModes;
-
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.PortRanges;
-
-import brooklyn.test.GeneralisedDynamicMBean;
-import brooklyn.test.JmxService;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-
-public class RebindJmxFeedTest extends RebindTestFixtureWithApp {
-
-    private static final Logger log = LoggerFactory.getLogger(RebindJmxFeedTest.class);
-
-    private static final String LOCALHOST_NAME = "localhost";
-
-    static final AttributeSensor<String> SENSOR_STRING = Sensors.newStringSensor("aString", "");
-    static final AttributeSensor<Integer> SENSOR_INT = Sensors.newIntegerSensor( "aLong", "");
-
-    static final String JMX_ATTRIBUTE_NAME = "myattr";
-    static final String OBJECT_NAME = "Brooklyn:type=MyTestMBean,name=myname";
-    
-    private JmxService jmxService;
-    
-    @BeforeMethod(alwaysRun=true)
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-        
-        // Create an entity and configure it with the above JMX service
-        //jmxService = newJmxServiceRetrying(LOCALHOST_NAME, 5);
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    @Override
-    public void tearDown() throws Exception {
-        if (jmxService != null) jmxService.shutdown();
-        super.tearDown();
-    }
-
-    @Test
-    public void testJmxFeedIsPersisted() throws Exception {
-        runJmxFeedIsPersisted(false);
-    }
-
-    @Test
-    public void testJmxFeedIsPersistedWithPreCreatedJmxHelper() throws Exception {
-        runJmxFeedIsPersisted(true);
-    }
-
-    protected void runJmxFeedIsPersisted(boolean preCreateJmxHelper) throws Exception {
-        TestEntity origEntity = origApp.createAndManageChild(EntitySpec.create(TestEntity.class).impl(MyEntityWithJmxFeedImpl.class)
-                .configure(MyEntityWithJmxFeedImpl.PRE_CREATE_JMX_HELPER, preCreateJmxHelper));
-        origApp.start(ImmutableList.<Location>of());
-        
-        jmxService = new JmxService(origEntity);
-        GeneralisedDynamicMBean mbean = jmxService.registerMBean(MutableMap.of(JMX_ATTRIBUTE_NAME, "myval"), OBJECT_NAME);
-        
-        EntityTestUtils.assertAttributeEqualsEventually(origEntity, SENSOR_STRING, "myval");
-        assertEquals(origEntity.feeds().getFeeds().size(), 1);
-
-        newApp = rebind();
-        TestEntity newEntity = (TestEntity) Iterables.getOnlyElement(newApp.getChildren());
-        
-        Collection<Feed> newFeeds = newEntity.feeds().getFeeds();
-        assertEquals(newFeeds.size(), 1);
-        
-        // Expect the feed to still be polling
-        newEntity.setAttribute(SENSOR_STRING, null);
-        EntityTestUtils.assertAttributeEqualsEventually(newEntity, SENSOR_STRING, "myval");
-    }
-
-    public static class MyEntityWithJmxFeedImpl extends TestEntityImpl {
-        public static final ConfigKey<Boolean> PRE_CREATE_JMX_HELPER = ConfigKeys.newBooleanConfigKey("test.rebindjmx.preCreateJmxHelper", "", false);
-        
-        @Override
-        public void start(Collection<? extends Location> locs) {
-            // TODO Auto-generated method stub
-            super.start(locs);
-            
-            setAttribute(Attributes.HOSTNAME, "localhost");
-            setAttribute(UsesJmx.JMX_PORT, 
-                    LocalhostMachineProvisioningLocation.obtainPort(PortRanges.fromString("40123+")));
-            // only supports no-agent, at the moment
-            setConfig(UsesJmx.JMX_AGENT_MODE, JmxAgentModes.NONE);
-            setAttribute(UsesJmx.RMI_REGISTRY_PORT, -1);  // -1 means to use the JMX_PORT only
-            ConfigToAttributes.apply(this, UsesJmx.JMX_CONTEXT);
-            
-            JmxFeed.Builder feedBuilder = JmxFeed.builder()
-                    .entity(this)
-                    .pollAttribute(new JmxAttributePollConfig<String>(SENSOR_STRING)
-                            .objectName(OBJECT_NAME)
-                            .period(50)
-                            .attributeName(JMX_ATTRIBUTE_NAME));
-            if (getConfig(PRE_CREATE_JMX_HELPER)) {
-                JmxHelper jmxHelper = new JmxHelper(this);
-                feedBuilder.helper(jmxHelper);
-            }
-            addFeed(feedBuilder.build());
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/management/usage/ApplicationUsageTrackingTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/management/usage/ApplicationUsageTrackingTest.java b/software/base/src/test/java/brooklyn/management/usage/ApplicationUsageTrackingTest.java
deleted file mode 100644
index 9b275c9..0000000
--- a/software/base/src/test/java/brooklyn/management/usage/ApplicationUsageTrackingTest.java
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.management.usage;
-
-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.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.brooklyn.api.entity.Application;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.core.mgmt.internal.UsageListener.ApplicationMetadata;
-import org.apache.brooklyn.core.mgmt.usage.ApplicationUsage;
-import org.apache.brooklyn.core.mgmt.usage.ApplicationUsage.ApplicationEvent;
-import org.apache.brooklyn.core.objs.proxy.EntityProxy;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.time.Time;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Predicates;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-
-public class ApplicationUsageTrackingTest {
-
-    private static final Logger LOG = LoggerFactory.getLogger(ApplicationUsageTrackingTest.class);
-
-    protected TestApplication app;
-    protected ManagementContextInternal mgmt;
-
-    protected boolean shouldSkipOnBoxBaseDirResolution() {
-        return true;
-    }
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        mgmt = LocalManagementContextForTests.newInstance();
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        try {
-            if (mgmt != null) Entities.destroyAll(mgmt);
-        } catch (Throwable t) {
-            LOG.error("Caught exception in tearDown method", t);
-        } finally {
-            mgmt = null;
-        }
-    }
-
-    @Test
-    public void testUsageInitiallyEmpty() {
-        Set<ApplicationUsage> usage = mgmt.getUsageManager().getApplicationUsage(Predicates.alwaysTrue());
-        assertEquals(usage, ImmutableSet.of());
-    }
-
-    @Test
-    @SuppressWarnings("deprecation")
-    public void testAddAndRemoveLegacyUsageListener() throws Exception {
-        final RecordingLegacyUsageListener listener = new RecordingLegacyUsageListener();
-        mgmt.getUsageManager().addUsageListener(listener);
-        
-        app = TestApplication.Factory.newManagedInstanceForTests(mgmt);
-        app.setCatalogItemId("testCatalogItem");
-        app.start(ImmutableList.<Location>of());
-
-        Asserts.succeedsEventually(new Runnable() {
-            @Override public void run() {
-                List<List<?>> events = listener.getApplicationEvents();
-                assertEquals(events.size(), 2, "events="+events); // expect STARTING and RUNNING
-                
-                String appId = (String) events.get(0).get(1);
-                String appName = (String) events.get(0).get(2);
-                String entityType = (String) events.get(0).get(3);
-                String catalogItemId = (String) events.get(0).get(4);
-                Map<?,?> metadata = (Map<?, ?>) events.get(0).get(5);
-                ApplicationEvent appEvent = (ApplicationEvent) events.get(0).get(6);
-                
-                assertEquals(appId, app.getId(), "events="+events);
-                assertNotNull(appName, "events="+events);
-                assertEquals(catalogItemId, app.getCatalogItemId(), "events="+events);
-                assertNotNull(entityType, "events="+events);
-                assertNotNull(metadata, "events="+events);
-                assertEquals(appEvent.getState(), Lifecycle.STARTING, "events="+events);
-            }});
-
-
-        // Remove the listener; will get no more notifications
-        listener.clearEvents();
-        mgmt.getUsageManager().removeUsageListener(listener);
-        
-        app.start(ImmutableList.<Location>of());
-        Asserts.succeedsContinually(new Runnable() {
-            @Override public void run() {
-                List<List<?>> events = listener.getLocationEvents();
-                assertEquals(events.size(), 0, "events="+events);
-            }});
-    }
-
-    @Test
-    public void testAddAndRemoveUsageListener() throws Exception {
-        final RecordingUsageListener listener = new RecordingUsageListener();
-        mgmt.getUsageManager().addUsageListener(listener);
-        
-        app = TestApplication.Factory.newManagedInstanceForTests(mgmt);
-        app.setCatalogItemId("testCatalogItem");
-        app.start(ImmutableList.<Location>of());
-
-        Asserts.succeedsEventually(new Runnable() {
-            @Override public void run() {
-                List<List<?>> events = listener.getApplicationEvents();
-                assertEquals(events.size(), 2, "events="+events); // expect STARTING and RUNNING
-                ApplicationMetadata appMetadata = (ApplicationMetadata) events.get(0).get(1);
-                ApplicationEvent appEvent = (ApplicationEvent) events.get(0).get(2);
-                
-                assertEquals(appMetadata.getApplication(), app, "events="+events);
-                assertTrue(appMetadata.getApplication() instanceof EntityProxy, "events="+events);
-                assertEquals(appMetadata.getApplicationId(), app.getId(), "events="+events);
-                assertNotNull(appMetadata.getApplicationName(), "events="+events);
-                assertEquals(appMetadata.getCatalogItemId(), app.getCatalogItemId(), "events="+events);
-                assertNotNull(appMetadata.getEntityType(), "events="+events);
-                assertNotNull(appMetadata.getMetadata(), "events="+events);
-                assertEquals(appEvent.getState(), Lifecycle.STARTING, "events="+events);
-            }});
-
-
-        // Remove the listener; will get no more notifications
-        listener.clearEvents();
-        mgmt.getUsageManager().removeUsageListener(listener);
-        
-        app.start(ImmutableList.<Location>of());
-        Asserts.succeedsContinually(new Runnable() {
-            @Override public void run() {
-                List<List<?>> events = listener.getLocationEvents();
-                assertEquals(events.size(), 0, "events="+events);
-            }});
-    }
-    
-    @Test
-    public void testUsageIncludesStartAndStopEvents() {
-        // Start event
-        long preStart = System.currentTimeMillis();
-        app = TestApplication.Factory.newManagedInstanceForTests(mgmt);
-        app.start(ImmutableList.<Location>of());
-        long postStart = System.currentTimeMillis();
-
-        Set<ApplicationUsage> usages1 = mgmt.getUsageManager().getApplicationUsage(Predicates.alwaysTrue());
-        ApplicationUsage usage1 = Iterables.getOnlyElement(usages1);
-        assertApplicationUsage(usage1, app);
-        assertApplicationEvent(usage1.getEvents().get(0), Lifecycle.STARTING, preStart, postStart);
-        assertApplicationEvent(usage1.getEvents().get(1), Lifecycle.RUNNING, preStart, postStart);
-
-        // Stop events
-        long preStop = System.currentTimeMillis();
-        app.stop();
-        long postStop = System.currentTimeMillis();
-
-        Set<ApplicationUsage> usages2 = mgmt.getUsageManager().getApplicationUsage(Predicates.alwaysTrue());
-        ApplicationUsage usage2 = Iterables.getOnlyElement(usages2);
-        assertApplicationUsage(usage2, app);
-        assertApplicationEvent(usage2.getEvents().get(2), Lifecycle.STOPPING, preStop, postStop);
-        assertApplicationEvent(usage2.getEvents().get(3), Lifecycle.STOPPED, preStop, postStop);
-        //Apps unmanage themselves on stop
-        assertApplicationEvent(usage2.getEvents().get(4), Lifecycle.DESTROYED, preStop, postStop);
-        
-        assertFalse(mgmt.getEntityManager().isManaged(app), "App should already be unmanaged");
-        
-        Set<ApplicationUsage> usages3 = mgmt.getUsageManager().getApplicationUsage(Predicates.alwaysTrue());
-        ApplicationUsage usage3 = Iterables.getOnlyElement(usages3);
-        assertApplicationUsage(usage3, app);
-        
-        assertEquals(usage3.getEvents().size(), 5, "usage="+usage3);
-    }
-    
-    private void assertApplicationUsage(ApplicationUsage usage, Application expectedApp) {
-        assertEquals(usage.getApplicationId(), expectedApp.getId());
-        assertEquals(usage.getApplicationName(), expectedApp.getDisplayName());
-        assertEquals(usage.getEntityType(), expectedApp.getEntityType().getName());
-    }
-    
-    private void assertApplicationEvent(ApplicationEvent event, Lifecycle expectedState, long preEvent, long postEvent) {
-        // Saw times differ by 1ms - perhaps different threads calling currentTimeMillis() can get out-of-order times?!
-        final int TIMING_GRACE = 5;
-        
-        assertEquals(event.getState(), expectedState);
-        long eventTime = event.getDate().getTime();
-        if (eventTime < (preEvent - TIMING_GRACE) || eventTime > (postEvent + TIMING_GRACE)) {
-            fail("for "+expectedState+": event=" + Time.makeDateString(eventTime) + "("+eventTime + "); "
-                    + "pre=" + Time.makeDateString(preEvent) + " ("+preEvent+ "); "
-                    + "post=" + Time.makeDateString(postEvent) + " ("+postEvent + ")");
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/management/usage/LocationUsageTrackingTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/management/usage/LocationUsageTrackingTest.java b/software/base/src/test/java/brooklyn/management/usage/LocationUsageTrackingTest.java
deleted file mode 100644
index ce1ea1d..0000000
--- a/software/base/src/test/java/brooklyn/management/usage/LocationUsageTrackingTest.java
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.management.usage;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.fail;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.core.mgmt.internal.UsageListener.LocationMetadata;
-import org.apache.brooklyn.core.mgmt.usage.LocationUsage;
-import org.apache.brooklyn.core.mgmt.usage.LocationUsage.LocationEvent;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcessEntityTest;
-
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.time.Time;
-
-import com.google.common.base.Predicates;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-
-public class LocationUsageTrackingTest extends BrooklynAppUnitTestSupport {
-
-    private DynamicLocalhostMachineProvisioningLocation loc;
-
-    @BeforeMethod(alwaysRun = true)
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-        loc = mgmt.getLocationManager().createLocation(LocationSpec.create(DynamicLocalhostMachineProvisioningLocation.class));
-    }
-
-    @Test
-    public void testUsageInitiallyEmpty() {
-        Set<LocationUsage> usage = mgmt.getUsageManager().getLocationUsage(Predicates.alwaysTrue());
-        assertEquals(usage, ImmutableSet.of());
-    }
-
-    @Test
-    @SuppressWarnings("deprecation")
-    public void testAddAndRemoveLegacyUsageListener() throws Exception {
-        final RecordingLegacyUsageListener listener = new RecordingLegacyUsageListener();
-        mgmt.getUsageManager().addUsageListener(listener);
-        
-        app.createAndManageChild(EntitySpec.create(SoftwareProcessEntityTest.MyService.class));
-        app.start(ImmutableList.of(loc));
-        final SshMachineLocation machine = Iterables.getOnlyElement(loc.getAllMachines());
-        
-        Asserts.succeedsEventually(new Runnable() {
-            @Override public void run() {
-                List<List<?>> events = listener.getLocationEvents();
-                String locId = (String) events.get(0).get(1);
-                LocationEvent locEvent = (LocationEvent) events.get(0).get(3);
-                Map<?,?> metadata = (Map<?, ?>) events.get(0).get(2);
-                
-                assertEquals(events.size(), 1, "events="+events);
-                assertEquals(locId, machine.getId(), "events="+events);
-                assertNotNull(metadata, "events="+events);
-                assertEquals(locEvent.getApplicationId(), app.getId(), "events="+events);
-                assertEquals(locEvent.getState(), Lifecycle.CREATED, "events="+events);
-            }});
-
-        // Remove the listener; will get no more notifications
-        listener.clearEvents();
-        mgmt.getUsageManager().removeUsageListener(listener);
-        
-        app.stop();
-        Asserts.succeedsContinually(new Runnable() {
-            @Override public void run() {
-                List<List<?>> events = listener.getLocationEvents();
-                assertEquals(events.size(), 0, "events="+events);
-            }});
-    }
-
-    @Test
-    public void testAddAndRemoveUsageListener() throws Exception {
-        final RecordingUsageListener listener = new RecordingUsageListener();
-        mgmt.getUsageManager().addUsageListener(listener);
-        
-        app.createAndManageChild(EntitySpec.create(SoftwareProcessEntityTest.MyService.class));
-        app.start(ImmutableList.of(loc));
-        final SshMachineLocation machine = Iterables.getOnlyElement(loc.getAllMachines());
-        
-        Asserts.succeedsEventually(new Runnable() {
-            @Override public void run() {
-                List<List<?>> events = listener.getLocationEvents();
-                LocationMetadata locMetadata = (LocationMetadata) events.get(0).get(1);
-                LocationEvent locEvent = (LocationEvent) events.get(0).get(2);
-                
-                assertEquals(events.size(), 1, "events="+events);
-                assertEquals(locMetadata.getLocation(), machine, "events="+events);
-                assertEquals(locMetadata.getLocationId(), machine.getId(), "events="+events);
-                assertNotNull(locMetadata.getMetadata(), "events="+events);
-                assertEquals(locEvent.getApplicationId(), app.getId(), "events="+events);
-                assertEquals(locEvent.getState(), Lifecycle.CREATED, "events="+events);
-            }});
-
-        // Remove the listener; will get no more notifications
-        listener.clearEvents();
-        mgmt.getUsageManager().removeUsageListener(listener);
-        
-        app.stop();
-        Asserts.succeedsContinually(new Runnable() {
-            @Override public void run() {
-                List<List<?>> events = listener.getLocationEvents();
-                assertEquals(events.size(), 0, "events="+events);
-            }});
-    }
-
-    @Test
-    public void testUsageIncludesStartAndStopEvents() {
-        SoftwareProcessEntityTest.MyService entity = app.createAndManageChild(EntitySpec.create(SoftwareProcessEntityTest.MyService.class));
-
-        // Start the app; expect record of location in use
-        long preStart = System.currentTimeMillis();
-        app.start(ImmutableList.of(loc));
-        long postStart = System.currentTimeMillis();
-        SshMachineLocation machine = Iterables.getOnlyElement(loc.getAllMachines());
-
-        Set<LocationUsage> usages1 = mgmt.getUsageManager().getLocationUsage(Predicates.alwaysTrue());
-        LocationUsage usage1 = Iterables.getOnlyElement(usages1);
-        assertLocationUsage(usage1, machine);
-        assertLocationEvent(usage1.getEvents().get(0), entity, Lifecycle.CREATED, preStart, postStart);
-
-        // Stop the app; expect record of location no longer in use
-        long preStop = System.currentTimeMillis();
-        app.stop();
-        long postStop = System.currentTimeMillis();
-
-        Set<LocationUsage> usages2 = mgmt.getUsageManager().getLocationUsage(Predicates.alwaysTrue());
-        LocationUsage usage2 = Iterables.getOnlyElement(usages2);
-        assertLocationUsage(usage2, machine);
-        assertLocationEvent(usage2.getEvents().get(1), app.getApplicationId(), entity.getId(), entity.getEntityType().getName(), Lifecycle.DESTROYED, preStop, postStop);
-        
-        assertEquals(usage2.getEvents().size(), 2, "usage="+usage2);
-    }
-
-    public static class DynamicLocalhostMachineProvisioningLocation extends LocalhostMachineProvisioningLocation {
-        private static final long serialVersionUID = 4822009936654077946L;
-
-        @Override
-        public SshMachineLocation obtain(Map<?, ?> flags) throws NoMachinesAvailableException {
-            System.out.println("called DynamicLocalhostMachineProvisioningLocation.obtain");
-            return super.obtain(flags);
-        }
-
-        @Override
-        public void release(SshMachineLocation machine) {
-            System.out.println("called DynamicLocalhostMachineProvisioningLocation.release");
-            super.release(machine);
-            super.machines.remove(machine);
-            super.removeChild(machine);
-        }
-    }
-    
-    private void assertLocationUsage(LocationUsage usage, Location expectedLoc) {
-        assertEquals(usage.getLocationId(), expectedLoc.getId(), "usage="+usage);
-        assertNotNull(usage.getMetadata(), "usage="+usage);
-    }
-
-    private void assertLocationEvent(LocationEvent event, Entity expectedEntity, Lifecycle expectedState, long preEvent, long postEvent) {
-        assertLocationEvent(event, expectedEntity.getApplicationId(), expectedEntity.getId(), expectedEntity.getEntityType().getName(), expectedState, preEvent, postEvent);
-    }
-    
-    private void assertLocationEvent(LocationEvent event, String expectedAppId, String expectedEntityId, String expectedEntityType, Lifecycle expectedState, long preEvent, long postEvent) {
-        // Saw times differ by 1ms - perhaps different threads calling currentTimeMillis() can get out-of-order times?!
-        final int TIMING_GRACE = 5;
-        
-        assertEquals(event.getApplicationId(), expectedAppId);
-        assertEquals(event.getEntityId(), expectedEntityId);
-        assertEquals(event.getEntityType(), expectedEntityType);
-        assertEquals(event.getState(), expectedState);
-        long eventTime = event.getDate().getTime();
-        if (eventTime < (preEvent - TIMING_GRACE) || eventTime > (postEvent + TIMING_GRACE)) {
-            fail("for "+expectedState+": event=" + Time.makeDateString(eventTime) + "("+eventTime + "); "
-                    + "pre=" + Time.makeDateString(preEvent) + " ("+preEvent+ "); "
-                    + "post=" + Time.makeDateString(postEvent) + " ("+postEvent + ")");
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/management/usage/RecordingLegacyUsageListener.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/management/usage/RecordingLegacyUsageListener.java b/software/base/src/test/java/brooklyn/management/usage/RecordingLegacyUsageListener.java
deleted file mode 100644
index 918e890..0000000
--- a/software/base/src/test/java/brooklyn/management/usage/RecordingLegacyUsageListener.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.management.usage;
-
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.core.mgmt.usage.ApplicationUsage.ApplicationEvent;
-import org.apache.brooklyn.core.mgmt.usage.LocationUsage.LocationEvent;
-import org.apache.brooklyn.util.collections.MutableList;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-
-@Deprecated
-public class RecordingLegacyUsageListener implements org.apache.brooklyn.core.mgmt.internal.UsageManager.UsageListener {
-
-    private final List<List<?>> events = Lists.newCopyOnWriteArrayList();
-    
-    @Override
-    public void onApplicationEvent(String applicationId, String applicationName, String entityType, 
-            String catalogItemId, Map<String, String> metadata, ApplicationEvent event) {
-        events.add(MutableList.of("application", applicationId, applicationName, entityType, catalogItemId, metadata, event));
-    }
-
-    @Override
-    public void onLocationEvent(String locationId, Map<String, String> metadata, LocationEvent event) {
-        events.add(MutableList.of("location", locationId, metadata, event));
-    }
-    
-    public void clearEvents() {
-        events.clear();
-    }
-    
-    public List<List<?>> getEvents() {
-        return ImmutableList.copyOf(events);
-    }
-    
-    public List<List<?>> getLocationEvents() {
-        List<List<?>> result = Lists.newArrayList();
-        for (List<?> event : events) {
-            if (event.get(0).equals("location")) result.add(event);
-        }
-        return ImmutableList.copyOf(result);
-    }
-    
-    public List<List<?>> getApplicationEvents() {
-        List<List<?>> result = Lists.newArrayList();
-        for (List<?> event : events) {
-            if (event.get(0).equals("application")) result.add(event);
-        }
-        return ImmutableList.copyOf(result);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/management/usage/RecordingUsageListener.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/management/usage/RecordingUsageListener.java b/software/base/src/test/java/brooklyn/management/usage/RecordingUsageListener.java
deleted file mode 100644
index b3fe39f..0000000
--- a/software/base/src/test/java/brooklyn/management/usage/RecordingUsageListener.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.management.usage;
-
-import java.util.List;
-
-import org.apache.brooklyn.core.mgmt.usage.ApplicationUsage.ApplicationEvent;
-import org.apache.brooklyn.core.mgmt.usage.LocationUsage.LocationEvent;
-import org.apache.brooklyn.util.collections.MutableList;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-
-public class RecordingUsageListener implements org.apache.brooklyn.core.mgmt.internal.UsageListener {
-
-    private final List<List<?>> events = Lists.newCopyOnWriteArrayList();
-    
-    @Override
-    public void onApplicationEvent(ApplicationMetadata app, ApplicationEvent event) {
-        events.add(MutableList.of("application", app, event));
-    }
-
-    @Override
-    public void onLocationEvent(LocationMetadata loc, LocationEvent event) {
-        events.add(MutableList.of("location", loc, event));
-    }
-    
-    public void clearEvents() {
-        events.clear();
-    }
-    
-    public List<List<?>> getEvents() {
-        return ImmutableList.copyOf(events);
-    }
-    
-    public List<List<?>> getLocationEvents() {
-        List<List<?>> result = Lists.newArrayList();
-        for (List<?> event : events) {
-            if (event.get(0).equals("location")) result.add(event);
-        }
-        return ImmutableList.copyOf(result);
-    }
-    
-    public List<List<?>> getApplicationEvents() {
-        List<List<?>> result = Lists.newArrayList();
-        for (List<?> event : events) {
-            if (event.get(0).equals("application")) result.add(event);
-        }
-        return ImmutableList.copyOf(result);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/management/usage/UsageListenerTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/management/usage/UsageListenerTest.java b/software/base/src/test/java/brooklyn/management/usage/UsageListenerTest.java
deleted file mode 100644
index 64d6723..0000000
--- a/software/base/src/test/java/brooklyn/management/usage/UsageListenerTest.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.management.usage;
-
-import static org.testng.Assert.assertTrue;
-
-import java.util.List;
-
-import org.apache.brooklyn.test.Asserts;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.core.mgmt.internal.UsageManager;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
-public class UsageListenerTest {
-
-    // Also see {Application|Location}UsageTrackingTest for listener functionality
-    
-    private static final Logger LOG = LoggerFactory.getLogger(ApplicationUsageTrackingTest.class);
-
-    protected TestApplication app;
-    protected ManagementContextInternal mgmt;
-
-    protected boolean shouldSkipOnBoxBaseDirResolution() {
-        return true;
-    }
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        RecordingStaticLegacyUsageListener.clearInstances();
-        RecordingStaticUsageListener.clearInstances();
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        try {
-            if (mgmt != null) Entities.destroyAll(mgmt);
-        } catch (Throwable t) {
-            LOG.error("Caught exception in tearDown method", t);
-        } finally {
-            mgmt = null;
-            RecordingStaticLegacyUsageListener.clearInstances();
-            RecordingStaticUsageListener.clearInstances();
-        }
-    }
-
-    @Test
-    public void testAddLegacyUsageListenerViaProperties() throws Exception {
-        BrooklynProperties brooklynProperties = BrooklynProperties.Factory.newEmpty();
-        brooklynProperties.put(UsageManager.USAGE_LISTENERS, RecordingStaticLegacyUsageListener.class.getName());
-        mgmt = LocalManagementContextForTests.newInstance(brooklynProperties);
-        
-        app = TestApplication.Factory.newManagedInstanceForTests(mgmt);
-        app.start(ImmutableList.<Location>of());
-
-        Asserts.succeedsEventually(new Runnable() {
-            @Override public void run() {
-                List<List<?>> events = RecordingStaticLegacyUsageListener.getInstance().getApplicationEvents();
-                assertTrue(events.size() > 0, "events="+events); // expect some events
-            }});
-    }
-    
-    @Test
-    public void testAddUsageListenerViaProperties() throws Exception {
-        BrooklynProperties brooklynProperties = BrooklynProperties.Factory.newEmpty();
-        brooklynProperties.put(UsageManager.USAGE_LISTENERS, RecordingStaticUsageListener.class.getName());
-        mgmt = LocalManagementContextForTests.newInstance(brooklynProperties);
-        
-        app = TestApplication.Factory.newManagedInstanceForTests(mgmt);
-        app.start(ImmutableList.<Location>of());
-
-        Asserts.succeedsEventually(new Runnable() {
-            @Override public void run() {
-                List<List<?>> events = RecordingStaticUsageListener.getInstance().getApplicationEvents();
-                assertTrue(events.size() > 0, "events="+events); // expect some events
-            }});
-    }
-    
-    public static class RecordingStaticLegacyUsageListener extends RecordingLegacyUsageListener implements org.apache.brooklyn.core.mgmt.internal.UsageManager.UsageListener {
-        private static final List<RecordingStaticLegacyUsageListener> STATIC_INSTANCES = Lists.newCopyOnWriteArrayList();
-        
-        public static RecordingStaticLegacyUsageListener getInstance() {
-            return Iterables.getOnlyElement(STATIC_INSTANCES);
-        }
-
-        public static void clearInstances() {
-            STATIC_INSTANCES.clear();
-        }
-        
-        public RecordingStaticLegacyUsageListener() {
-            // Bad to leak a ref to this before constructor finished, but we'll live with it because
-            // it's just test code!
-            STATIC_INSTANCES.add(this);
-        }
-    }
-    
-    public static class RecordingStaticUsageListener extends RecordingUsageListener implements org.apache.brooklyn.core.mgmt.internal.UsageListener {
-        private static final List<RecordingStaticUsageListener> STATIC_INSTANCES = Lists.newCopyOnWriteArrayList();
-        
-        public static RecordingStaticUsageListener getInstance() {
-            return Iterables.getOnlyElement(STATIC_INSTANCES);
-        }
-
-        public static void clearInstances() {
-            STATIC_INSTANCES.clear();
-        }
-        
-        public RecordingStaticUsageListener() {
-            // Bad to leak a ref to this before constructor finished, but we'll live with it because
-            // it's just test code!
-            STATIC_INSTANCES.add(this);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/test/GeneralisedDynamicMBean.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/test/GeneralisedDynamicMBean.java b/software/base/src/test/java/brooklyn/test/GeneralisedDynamicMBean.java
deleted file mode 100644
index 11c8fbb..0000000
--- a/software/base/src/test/java/brooklyn/test/GeneralisedDynamicMBean.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.test;
-
-import static com.google.common.base.Preconditions.checkArgument;
-
-import java.util.Map;
-import java.util.Map.Entry;
-
-import javax.management.Attribute;
-import javax.management.AttributeList;
-import javax.management.DynamicMBean;
-import javax.management.MBeanAttributeInfo;
-import javax.management.MBeanConstructorInfo;
-import javax.management.MBeanInfo;
-import javax.management.MBeanNotificationInfo;
-import javax.management.MBeanOperationInfo;
-import javax.management.MBeanParameterInfo;
-
-import com.google.common.base.Function;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Maps;
-
-/**
- * A quick-and-simple general-purpose implementation of DynamicMBean.
- *
- * This class provides an implementation of {@link DynamicMBean}. Its initial set of attribute names and values are
- * provided to the constructor; from this it figures an {@link MBeanInfo}.
- * <p>
- * It presently assumes that all attributes are read-only; operations and notifications are not currently supported.
- * Choosing the descriptions is not supported - they are set to be the same as the name.
- * <p>
- * Getting a valid dynamic MBean (in Groovy) is as simple as:
- * <pre>
- * new GeneralisedDynamicMBean(meaning: 42, advice: "Don't panic")
- * </pre>
- */
-public class GeneralisedDynamicMBean implements DynamicMBean {
-    private final MBeanInfo mBeanInfo;
-    private final Map<String,Object> attributes = Maps.newLinkedHashMap();
-    private final Map<String,Function> operations = Maps.newLinkedHashMap();
-    
-    public GeneralisedDynamicMBean(Map<String,?> initialAttributes, Map<?,?> initialOperations) {
-        attributes.putAll(initialAttributes);
-
-        for (Entry<?,?> entry : initialOperations.entrySet()) {
-            checkArgument(entry.getKey() instanceof String || entry.getKey() instanceof MBeanOperationInfo, "entry.key=%s", entry.getKey());
-            String opName = (entry.getKey() instanceof String) ? (String)entry.getKey() : ((MBeanOperationInfo)entry.getKey()).getName();
-            operations.put(opName, (Function) entry.getValue());
-        }
-        
-        Iterable<MBeanAttributeInfo> attrInfo = Iterables.transform(initialAttributes.entrySet(), new Function<Map.Entry<String,?>, MBeanAttributeInfo>() {
-            @Override public MBeanAttributeInfo apply(Map.Entry<String,?> entry) {
-                return new MBeanAttributeInfo(entry.getKey(), entry.getValue().getClass().getName(), entry.getKey(), true, false, false);
-            }
-        });
-        
-        Iterable<MBeanOperationInfo> opInfo = Iterables.transform(initialOperations.keySet(), new Function<Object, MBeanOperationInfo>() {
-            public MBeanOperationInfo apply(Object it) {
-                if (it instanceof MBeanOperationInfo) {
-                    return (MBeanOperationInfo) it;
-                } else if (it instanceof CharSequence) {
-                    return new MBeanOperationInfo(
-                            it.toString(),
-                            "my descr", 
-                            new MBeanParameterInfo[0], 
-                            "void", 
-                            MBeanOperationInfo.ACTION_INFO);
-                } else {
-                    throw new IllegalArgumentException("Cannot convert "+it+" to MBeanOperationInfo");
-                }
-            }});
-        
-        mBeanInfo = new MBeanInfo(
-                GeneralisedDynamicMBean.class.getName(), 
-                GeneralisedDynamicMBean.class.getName(), 
-                Iterables.toArray(attrInfo, MBeanAttributeInfo.class),
-                new MBeanConstructorInfo[0], 
-                Iterables.toArray(opInfo, MBeanOperationInfo.class),
-                new MBeanNotificationInfo[0]);
-    }
-
-    public void updateAttributeValue(String name, Object value) {
-        attributes.put(name, value);
-    }
-
-    @Override
-    public Object getAttribute(String s) {
-        return attributes.get(s);
-    }
-
-    @Override
-    public void setAttribute(Attribute attribute) {
-        attributes.put(attribute.getName(), attribute.getValue());
-    }
-
-    @Override
-    public AttributeList getAttributes(String[] strings) {
-        AttributeList result = new AttributeList();
-        for (Object obj : mBeanInfo.getAttributes()) {
-            Attribute attrib = (Attribute) obj;
-            result.add(new Attribute(attrib.getName(), attributes.get(attrib.getName())));
-        }
-        return result;
-    }
-
-    @Override
-    public AttributeList setAttributes(AttributeList attributeList) {
-        for (Object element : attributeList) {
-            Attribute attrib = (Attribute) element;
-            attributes.put(attrib.getName(), attrib.getValue());
-        }
-        return attributeList;
-    }
-
-    @Override
-    public Object invoke(String s, Object[] objects, String[] strings) {
-        Function op = operations.get(s);
-        if (op != null) {
-            return op.apply(objects);
-        } else {
-            throw new RuntimeException("Unknown operation "+s);
-        }
-    }
-
-    @Override
-    public MBeanInfo getMBeanInfo() {
-        return mBeanInfo;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/test/JmxService.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/test/JmxService.java b/software/base/src/test/java/brooklyn/test/JmxService.java
deleted file mode 100644
index 197f4d4..0000000
--- a/software/base/src/test/java/brooklyn/test/JmxService.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.test;
-
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.MBeanNotificationInfo;
-import javax.management.MBeanRegistrationException;
-import javax.management.MBeanServer;
-import javax.management.MBeanServerFactory;
-import javax.management.MBeanServerInvocationHandler;
-import javax.management.MalformedObjectNameException;
-import javax.management.NotCompliantMBeanException;
-import javax.management.Notification;
-import javax.management.NotificationBroadcasterSupport;
-import javax.management.NotificationEmitter;
-import javax.management.ObjectName;
-import javax.management.StandardEmitterMBean;
-import javax.management.remote.JMXConnectorServer;
-import javax.management.remote.JMXConnectorServerFactory;
-import javax.management.remote.JMXServiceURL;
-
-import mx4j.tools.naming.NamingService;
-import mx4j.tools.naming.NamingServiceMBean;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.java.UsesJmx;
-import brooklyn.event.feed.jmx.JmxHelper;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableMap;
-
-/**
- * Set up a JMX service ready for clients to connect. This consists of an MBean server, a connector server and a naming
- * service.
- */
-public class JmxService {
-    private static final Logger logger = LoggerFactory.getLogger(JmxService.class);
-
-    private MBeanServer server;
-    private NamingServiceMBean namingServiceMBean;
-    private JMXConnectorServer connectorServer;
-    private String jmxHost;
-    private int jmxPort;
-    private String url;
-
-    public JmxService() throws Exception {
-        this("localhost", 28000 + (int)Math.floor(new Random().nextDouble() * 1000));
-        logger.warn("use of deprecated default host and port in JmxService");
-    }
-    
-    /**
-     * @deprecated since 0.6.0; either needs abandoning, or updating to support JmxSupport (and JmxmpAgent, etc) */
-    public JmxService(Entity e) throws Exception {
-        this(e.getAttribute(Attributes.HOSTNAME) != null ? e.getAttribute(Attributes.HOSTNAME) : "localhost", 
-                 e.getAttribute(UsesJmx.JMX_PORT) != null ? e.getAttribute(UsesJmx.JMX_PORT) : null);
-    }
-    
-    public JmxService(String jmxHost, Integer jmxPort) throws Exception {
-        this.jmxHost = jmxHost;
-        Preconditions.checkNotNull(jmxPort, "JMX_PORT must be set when starting JmxService"); 
-        this.jmxPort = jmxPort;
-        url = JmxHelper.toRmiJmxUrl(jmxHost, jmxPort, jmxPort, "jmxrmi");
-
-        try {
-            JMXServiceURL address = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + jmxHost + ":" + jmxPort + "/jmxrmi");
-            connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(address, null, null);
-            server = MBeanServerFactory.createMBeanServer();
-            ObjectName cntorServerName = ObjectName.getInstance("connectors:protocol=rmi");
-            server.registerMBean(connectorServer, cntorServerName);
-    
-            ObjectName naming = new ObjectName("Naming:type=registry");
-            server.registerMBean(new NamingService(jmxPort), naming);
-            Object proxy = MBeanServerInvocationHandler.newProxyInstance(server, naming, NamingServiceMBean.class, false);
-            namingServiceMBean = (NamingServiceMBean) proxy;
-            try {
-                namingServiceMBean.start();
-            } catch (Exception e) {
-                // may take a bit of time for port to be available, if it had just been used
-                logger.warn("JmxService couldn't start test mbean ("+e+"); will delay then retry once");
-                Thread.sleep(1000);
-                namingServiceMBean.start();
-            }
-    
-            connectorServer.start();
-            logger.info("JMX tester service started at URL {}", address);
-        } catch (Exception e) {
-            try {
-                shutdown();
-            } catch (Exception e2) {
-                logger.warn("Error shutting down JmxService, after error during startup; rethrowing original error", e2);
-            }
-            throw e;
-        }
-    }
-
-    public int getJmxPort() {
-        return jmxPort;
-    }
-    
-    public void shutdown() throws IOException {
-        if (connectorServer != null) connectorServer.stop();
-        if (namingServiceMBean != null) namingServiceMBean.stop();
-        if (server != null) MBeanServerFactory.releaseMBeanServer(server);
-        connectorServer = null;
-        namingServiceMBean = null;
-        server = null;
-        logger.info("JMX tester service stopped ({}:{})", jmxHost, jmxPort);
-    }
-
-    public String getUrl() {
-        return url;
-    }
-    
-    public GeneralisedDynamicMBean registerMBean(String name) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, MalformedObjectNameException, NullPointerException {
-        return registerMBean(ImmutableMap.of(), ImmutableMap.of(), name);
-    }
-
-    /**
-     * Construct a {@link GeneralisedDynamicMBean} and register it with this MBean server.
-     *
-     * @param initialAttributes a {@link Map} of attributes that make up the MBean's initial set of attributes and their * values
-     * @param name the name of the MBean
-     * @return the newly created and registered MBean
-     * @throws NullPointerException 
-     * @throws MalformedObjectNameException 
-     * @throws NotCompliantMBeanException 
-     * @throws MBeanRegistrationException 
-     * @throws InstanceAlreadyExistsException 
-     */
-    public GeneralisedDynamicMBean registerMBean(Map initialAttributes, String name) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, MalformedObjectNameException, NullPointerException {
-        return registerMBean(initialAttributes, ImmutableMap.of(), name);
-    }
-    
-    public GeneralisedDynamicMBean registerMBean(Map initialAttributes, Map operations, String name) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, MalformedObjectNameException, NullPointerException {
-        GeneralisedDynamicMBean mbean = new GeneralisedDynamicMBean(initialAttributes, operations);
-        server.registerMBean(mbean, new ObjectName(name));
-        return mbean;
-    }
-    
-    public StandardEmitterMBean registerMBean(List<String> notifications, String name) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, MalformedObjectNameException, NullPointerException {
-        String[] types = (String[]) notifications.toArray(new String[0]);
-        MBeanNotificationInfo info = new MBeanNotificationInfo(types, Notification.class.getName(), "Notification");
-        NotificationEmitter emitter = new NotificationBroadcasterSupport(info);
-        StandardEmitterMBean mbean = new StandardEmitterMBean(emitter, NotificationEmitter.class, emitter);
-        server.registerMBean(mbean, new ObjectName(name));
-        return mbean;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/AbstractEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/AbstractEc2LiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/AbstractEc2LiveTest.java
new file mode 100644
index 0000000..0a1e9d7
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/AbstractEc2LiveTest.java
@@ -0,0 +1,139 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity;
+
+import java.util.Map;
+
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.location.jclouds.JcloudsLocation;
+import org.apache.brooklyn.location.jclouds.JcloudsLocationConfig;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+/**
+ * Runs a test with many different distros and versions.
+ */
+public abstract class AbstractEc2LiveTest extends BrooklynAppLiveTestSupport {
+    
+    // FIXME Currently have just focused on test_Debian_6; need to test the others as well!
+
+    // TODO No nice fedora VMs
+    
+    // TODO Instead of this sub-classing approach, we could use testng's "provides" mechanism
+    // to say what combo of provider/region/flags should be used. The problem with that is the
+    // IDE integration: one can't just select a single test to run.
+    
+    public static final String PROVIDER = "aws-ec2";
+    public static final String REGION_NAME = "us-east-1";
+    public static final String LOCATION_SPEC = PROVIDER + (REGION_NAME == null ? "" : ":" + REGION_NAME);
+    public static final String TINY_HARDWARE_ID = "t1.micro";
+    public static final String SMALL_HARDWARE_ID = "m1.small";
+    
+    protected BrooklynProperties brooklynProperties;
+    
+    protected Location jcloudsLocation;
+    
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        // Don't let any defaults from brooklyn.properties (except credentials) interfere with test
+        brooklynProperties = BrooklynProperties.Factory.newDefault();
+        brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-description-regex");
+        brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-name-regex");
+        brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-id");
+        brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".inboundPorts");
+        brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".hardware-id");
+
+        // Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can cause "stdin: is not a tty")
+        brooklynProperties.remove("brooklyn.ssh.config.scriptHeader");
+        
+        mgmt = new LocalManagementContextForTests(brooklynProperties);
+        
+        super.setUp();
+    }
+
+    // Image ids for Debian: https://wiki.debian.org/Cloud/AmazonEC2Image/Squeeze
+    @Test(groups = {"Live"})
+    public void test_Debian_6() throws Exception {
+        // release codename "squeeze"
+        runTest(ImmutableMap.of("imageId", "us-east-1/ami-5e12dc36", "loginUser", "admin", "hardwareId", SMALL_HARDWARE_ID));
+    }
+
+    @Test(groups = {"Live"})
+    public void test_Debian_7_2() throws Exception {
+        // release codename "wheezy"
+        runTest(ImmutableMap.of("imageId", "us-east-1/ami-5586a43c", "loginUser", "admin", "hardwareId", SMALL_HARDWARE_ID));
+    }
+
+    @Test(groups = {"Live"})
+    public void test_Ubuntu_10_0() throws Exception {
+        // Image: {id=us-east-1/ami-5e008437, providerId=ami-5e008437, name=RightImage_Ubuntu_10.04_x64_v5.8.8.3, location={scope=REGION, id=us-east-1, description=us-east-1, parent=aws-ec2, iso3166Codes=[US-VA]}, os={family=ubuntu, arch=paravirtual, version=10.04, description=rightscale-us-east/RightImage_Ubuntu_10.04_x64_v5.8.8.3.manifest.xml, is64Bit=true}, description=rightscale-us-east/RightImage_Ubuntu_10.04_x64_v5.8.8.3.manifest.xml, version=5.8.8.3, status=AVAILABLE[available], loginUser=root, userMetadata={owner=411009282317, rootDeviceType=instance-store, virtualizationType=paravirtual, hypervisor=xen}}
+        runTest(ImmutableMap.of("imageId", "us-east-1/ami-5e008437", "loginUser", "root", "hardwareId", SMALL_HARDWARE_ID));
+    }
+
+    @Test(groups = {"Live"})
+    public void test_Ubuntu_12_0() throws Exception {
+        // Image: {id=us-east-1/ami-d0f89fb9, providerId=ami-d0f89fb9, name=ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1, location={scope=REGION, id=us-east-1, description=us-east-1, parent=aws-ec2, iso3166Codes=[US-VA]}, os={family=ubuntu, arch=paravirtual, version=12.04, description=099720109477/ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1, is64Bit=true}, description=099720109477/ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1, version=20130411.1, status=AVAILABLE[available], loginUser=ubuntu, userMetadata={owner=099720109477, rootDeviceType=ebs, virtualizationType=paravirtual, hypervisor=xen}}
+        runTest(ImmutableMap.of("imageId", "us-east-1/ami-d0f89fb9", "loginUser", "ubuntu", "hardwareId", SMALL_HARDWARE_ID));
+    }
+
+    @Test(groups = {"Live"})
+    public void test_CentOS_6_3() throws Exception {
+        // TODO Should openIptables=true be the default?!
+        // Image: {id=us-east-1/ami-a96b01c0, providerId=ami-a96b01c0, name=CentOS-6.3-x86_64-GA-EBS-02-85586466-5b6c-4495-b580-14f72b4bcf51-ami-bb9af1d2.1, location={scope=REGION, id=us-east-1, description=us-east-1, parent=aws-ec2, iso3166Codes=[US-VA]}, os={family=centos, arch=paravirtual, version=6.3, description=aws-marketplace/CentOS-6.3-x86_64-GA-EBS-02-85586466-5b6c-4495-b580-14f72b4bcf51-ami-bb9af1d2.1, is64Bit=true}, description=CentOS-6.3-x86_64-GA-EBS-02 on EBS x86_64 20130527:1219, version=bb9af1d2.1, status=AVAILABLE[available], loginUser=root, userMetadata={owner=679593333241, rootDeviceType=ebs, virtualizationType=paravirtual, hypervisor=xen}})
+        runTest(ImmutableMap.of("imageId", "us-east-1/ami-a96b01c0", "hardwareId", SMALL_HARDWARE_ID, JcloudsLocation.OPEN_IPTABLES.getName(), true));
+    }
+
+    @Test(groups = {"Live"})
+    public void test_CentOS_5() throws Exception {
+        // Image: {id=us-east-1/ami-e4bffe8d, providerId=ami-e4bffe8d, name=RightImage_CentOS_5.9_x64_v12.11.4_EBS, location={scope=REGION, id=us-east-1, description=us-east-1, parent=aws-ec2, iso3166Codes=[US-VA]}, os={family=centos, arch=paravirtual, version=5.0, description=411009282317/RightImage_CentOS_5.9_x64_v12.11.4_EBS, is64Bit=true}, description=RightImage_CentOS_5.9_x64_v12.11.4_EBS, version=12.11.4_EBS, status=AVAILABLE[available], loginUser=root, userMetadata={owner=411009282317, rootDeviceType=ebs, virtualizationType=paravirtual, hypervisor=xen}}
+        runTest(ImmutableMap.of("imageId", "us-east-1/ami-e4bffe8d", "hardwareId", SMALL_HARDWARE_ID));
+    }
+
+    @Test(groups = {"Live"})
+    public void test_Red_Hat_Enterprise_Linux_6() throws Exception {
+        // Image: {id=us-east-1/ami-a35a33ca, providerId=ami-a35a33ca, name=RHEL-6.3_GA-x86_64-5-Hourly2, location={scope=REGION, id=us-east-1, description=us-east-1, parent=aws-ec2, iso3166Codes=[US-VA]}, os={family=rhel, arch=paravirtual, version=6.0, description=309956199498/RHEL-6.3_GA-x86_64-5-Hourly2, is64Bit=true}, description=309956199498/RHEL-6.3_GA-x86_64-5-Hourly2, version=Hourly2, status=AVAILABLE[available], loginUser=root, userMetadata={owner=309956199498, rootDeviceType=ebs, virtualizationType=paravirtual, hypervisor=xen}}
+        runTest(ImmutableMap.of("imageId", "us-east-1/ami-a35a33ca", "hardwareId", SMALL_HARDWARE_ID, JcloudsLocationConfig.OPEN_IPTABLES.getName(), "true"));
+    }
+    
+    @Test(groups = {"Live"})
+    public void test_Suse_11sp3() throws Exception {
+        // Image: {id=us-east-1/ami-c08fcba8, providerId=ami-c08fcba8, name=suse-sles-11-sp3-v20150127-pv-ssd-x86_64, location={scope=REGION, id=us-east-1, description=us-east-1, parent=aws-ec2, iso3166Codes=[US-VA]}, os={family=suse, arch=paravirtual, version=, description=amazon/suse-sles-11-sp3-v20150127-pv-ssd-x86_64, is64Bit=true}, description=SUSE Linux Enterprise Server 11 Service Pack 3 (PV, 64-bit, SSD-Backed), version=x86_64, status=AVAILABLE[available], loginUser=root, userMetadata={owner=013907871322, rootDeviceType=ebs, virtualizationType=paravirtual, hypervisor=xen}}
+        runTest(ImmutableMap.of("imageId", "us-east-1/ami-c08fcba8", "hardwareId", SMALL_HARDWARE_ID, "loginUser", "ec2-user"));//, JcloudsLocationConfig.OPEN_IPTABLES.getName(), "true"));
+    }
+    
+    protected void runTest(Map<String,?> flags) throws Exception {
+        Map<String,?> allFlags = MutableMap.<String,Object>builder()
+                .put("tags", ImmutableList.of(getClass().getName()))
+                .putAll(flags)
+                .build();
+        jcloudsLocation = mgmt.getLocationRegistry().resolve(LOCATION_SPEC, allFlags);
+
+        doTest(jcloudsLocation);
+    }
+    
+    protected abstract void doTest(Location loc) throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/AbstractGoogleComputeLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/AbstractGoogleComputeLiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/AbstractGoogleComputeLiveTest.java
new file mode 100644
index 0000000..54911fd
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/AbstractGoogleComputeLiveTest.java
@@ -0,0 +1,137 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.base.CaseFormat;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+/**
+ * Runs a test with many different distros and versions.
+ */
+public abstract class AbstractGoogleComputeLiveTest {
+    
+    // TODO See todos in AbstractEc2LiveTest
+    
+    public static final String PROVIDER = "google-compute-engine";
+    public static final String REGION_NAME = null;//"us-central1";
+    public static final String LOCATION_SPEC = PROVIDER + (REGION_NAME == null ? "" : ":" + REGION_NAME);
+    public static final String STANDARD_HARDWARE_ID = "us-central1-b/n1-standard-1-d";
+    private static final int MAX_TAG_LENGTH = 63;
+
+    protected BrooklynProperties brooklynProperties;
+    protected ManagementContext ctx;
+    
+    protected TestApplication app;
+    protected Location jcloudsLocation;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        List<String> propsToRemove = ImmutableList.of("imageId", "imageDescriptionRegex", "imageNameRegex", "inboundPorts", "hardwareId", "minRam");
+        
+     // Don't let any defaults from brooklyn.properties (except credentials) interfere with test
+        brooklynProperties = BrooklynProperties.Factory.newDefault();
+        for (String propToRemove : propsToRemove) {
+            for (String propVariant : ImmutableList.of(propToRemove, CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propToRemove))) {
+                brooklynProperties.remove("brooklyn.locations.jclouds."+PROVIDER+"."+propVariant);
+                brooklynProperties.remove("brooklyn.locations."+propVariant);
+                brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+"."+propVariant);
+                brooklynProperties.remove("brooklyn.jclouds."+propVariant);
+            }
+        }
+
+        // Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can cause "stdin: is not a tty")
+        brooklynProperties.remove("brooklyn.ssh.config.scriptHeader");
+        
+        ctx = new LocalManagementContext(brooklynProperties);
+        app = ApplicationBuilder.newManagedApp(TestApplication.class, ctx);
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (app != null) Entities.destroyAllCatching(app.getManagementContext());
+    }
+
+    @Test(groups = {"Live"})
+    public void test_DefaultImage() throws Exception {
+        runTest(ImmutableMap.<String,String>of());
+    }
+
+    // most of these not available
+    
+//    @Test(groups = {"Live"})
+//    public void test_GCEL_10_04() throws Exception {
+//        // release codename "squeeze"
+//        runTest(ImmutableMap.of("imageId", "gcel-10-04-v20130325", "loginUser", "admin", "hardwareId", STANDARD_HARDWARE_ID));
+//    }
+//
+//    @Test(groups = {"Live"})
+//    public void test_GCEL_12_04() throws Exception {
+//        // release codename "squeeze"
+//        runTest(ImmutableMap.of("imageId", "gcel-12-04-v20130325", "loginUser", "admin", "hardwareId", STANDARD_HARDWARE_ID));
+//    }
+//
+//    @Test(groups = {"Live"})
+//    public void test_Ubuntu_10_04() throws Exception {
+//        // release codename "squeeze"
+//        runTest(ImmutableMap.of("imageId", "ubuntu-10-04-v20120912", "loginUser", "admin", "hardwareId", STANDARD_HARDWARE_ID));
+//    }
+//
+//    @Test(groups = {"Live"})
+//    public void test_Ubuntu_12_04() throws Exception {
+//        // release codename "squeeze"
+//        runTest(ImmutableMap.of("imageId", "ubuntu-10-04-v20120912", "loginUser", "admin", "hardwareId", STANDARD_HARDWARE_ID));
+//    }
+//
+//    @Test(groups = {"Live"})
+//    public void test_CentOS_6() throws Exception {
+//        runTest(ImmutableMap.of("imageId", "centos-6-v20130325", "hardwareId", STANDARD_HARDWARE_ID));
+//    }
+
+    protected void runTest(Map<String,?> flags) throws Exception {
+        String tag = getClass().getSimpleName().toLowerCase();
+        int length = tag.length();
+        if (length > MAX_TAG_LENGTH)
+            tag = tag.substring(length - MAX_TAG_LENGTH, length);
+        Map<String,?> allFlags = MutableMap.<String,Object>builder()
+                .put("tags", ImmutableList.of(tag))
+                .putAll(flags)
+                .build();
+        jcloudsLocation = ctx.getLocationRegistry().resolve(LOCATION_SPEC, allFlags);
+
+        doTest(jcloudsLocation);
+    }
+
+    protected abstract void doTest(Location loc) throws Exception;
+}


[17/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessEntityLatchTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessEntityLatchTest.java b/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessEntityLatchTest.java
deleted file mode 100644
index 1421f45..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessEntityLatchTest.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
-import java.util.List;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.stock.BasicEntity;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcessEntityTest.MyService;
-import brooklyn.entity.basic.SoftwareProcessEntityTest.SimulatedDriver;
-
-import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.sensor.core.DependentConfiguration;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.core.task.TaskInternal;
-import org.apache.brooklyn.util.time.Duration;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
-
-public class SoftwareProcessEntityLatchTest extends BrooklynAppUnitTestSupport {
-
-    // NB: These tests don't actually require ssh to localhost -- only that 'localhost' resolves.
-
-    @SuppressWarnings("unused")
-    private static final Logger LOG = LoggerFactory.getLogger(SoftwareProcessEntityLatchTest.class);
-
-    private SshMachineLocation machine;
-    private FixedListMachineProvisioningLocation<SshMachineLocation> loc;
-    
-    @BeforeMethod(alwaysRun=true)
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-        loc = getLocation();
-    }
-
-    @SuppressWarnings("unchecked")
-    private FixedListMachineProvisioningLocation<SshMachineLocation> getLocation() {
-        FixedListMachineProvisioningLocation<SshMachineLocation> loc = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class));
-        machine = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                .configure("address", "localhost"));
-        loc.addMachine(machine);
-        return loc;
-    }
-
-    @Test
-    public void testStartLatchBlocks() throws Exception {
-        runTestLatchBlocks(SoftwareProcess.START_LATCH, ImmutableList.<String>of());
-    }
-
-    @Test
-    public void testSetupLatchBlocks() throws Exception {
-        runTestLatchBlocks(SoftwareProcess.SETUP_LATCH, ImmutableList.<String>of());
-    }
-
-    @Test
-    public void testIntallResourcesLatchBlocks() throws Exception {
-        runTestLatchBlocks(SoftwareProcess.INSTALL_RESOURCES_LATCH, ImmutableList.of("setup"));
-    }
-
-    @Test
-    public void testInstallLatchBlocks() throws Exception {
-        runTestLatchBlocks(SoftwareProcess.INSTALL_LATCH, ImmutableList.of("setup", "copyInstallResources"));
-    }
-
-    @Test
-    public void testCustomizeLatchBlocks() throws Exception {
-        runTestLatchBlocks(SoftwareProcess.CUSTOMIZE_LATCH, ImmutableList.of("setup", "copyInstallResources", "install"));
-    }
-
-    @Test
-    public void testRuntimeResourcesLatchBlocks() throws Exception {
-        runTestLatchBlocks(SoftwareProcess.RUNTIME_RESOURCES_LATCH, ImmutableList.of("setup", "copyInstallResources", "install", "customize"));
-    }
-
-    @Test
-    public void testLaunchLatchBlocks() throws Exception {
-        runTestLatchBlocks(SoftwareProcess.LAUNCH_LATCH, ImmutableList.of("setup", "copyInstallResources", "install", "customize", "copyRuntimeResources"));
-    }
-
-    protected void runTestLatchBlocks(final ConfigKey<Boolean> latch, List<String> preLatchEvents) throws Exception {
-        final BasicEntity triggerEntity = app.createAndManageChild(EntitySpec.create(BasicEntity.class));
-        final MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)
-                .configure(latch, DependentConfiguration.attributeWhenReady(triggerEntity, Attributes.SERVICE_UP)));
-        
-        final Task<Void> task = Entities.invokeEffector(app, app, MyService.START, ImmutableMap.of("locations", ImmutableList.of(loc)));
-        
-        assertEffectorBlockingDetailsEventually(entity, "Waiting for config "+latch.getName());
-        assertDriverEventsEquals(entity, preLatchEvents);
-
-        assertFalse(task.isDone());
-        ((EntityLocal)triggerEntity).setAttribute(Attributes.SERVICE_UP, true);
-        task.get(Duration.THIRTY_SECONDS);
-        assertDriverEventsEquals(entity, ImmutableList.of("setup", "copyInstallResources", "install", "customize", "copyRuntimeResources", "launch"));
-    }
-
-    private void assertDriverEventsEquals(MyService entity, List<String> expectedEvents) {
-        List<String> events = ((SimulatedDriver)entity.getDriver()).events;
-        assertEquals(events, expectedEvents, "events="+events);
-    }
-
-    private void assertEffectorBlockingDetailsEventually(final Entity entity, final String blockingDetailsSnippet) {
-        Asserts.succeedsEventually(new Runnable() {
-            @Override public void run() {
-                Task<?> entityTask = Iterables.getOnlyElement(mgmt.getExecutionManager().getTasksWithAllTags(ImmutableList.of(BrooklynTaskTags.EFFECTOR_TAG, BrooklynTaskTags.tagForContextEntity(entity))));
-                String blockingDetails = getBlockingDetails(entityTask);
-                assertTrue(blockingDetails.contains(blockingDetailsSnippet));
-            }});
-    }
-    
-    private String getBlockingDetails(Task<?> task) {
-        List<TaskInternal<?>> taskChain = Lists.newArrayList();
-        TaskInternal<?> taskI = (TaskInternal<?>) task;
-        while (taskI != null) {
-            taskChain.add(taskI);
-            if (taskI.getBlockingDetails() != null) {
-                return taskI.getBlockingDetails();
-            }
-            taskI = (TaskInternal<?>) taskI.getBlockingTask();
-        }
-        throw new IllegalStateException("No blocking details for "+task+" (walked task chain "+taskChain+")");
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessEntityRebindTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessEntityRebindTest.java b/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessEntityRebindTest.java
deleted file mode 100644
index 5723507..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessEntityRebindTest.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNull;
-import static org.testng.Assert.assertTrue;
-
-import java.io.File;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic.ServiceProblemsLogic;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcessEntityTest.MyService;
-
-import org.apache.brooklyn.location.basic.AbstractLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.io.Files;
-
-public class SoftwareProcessEntityRebindTest extends BrooklynAppUnitTestSupport {
-
-    private ClassLoader classLoader = getClass().getClassLoader();
-    private TestApplication newApp;
-    private ManagementContext newManagementContext;
-    private MyService origE;
-    private File mementoDir;
-    
-    @BeforeMethod(alwaysRun=true)
-    @Override
-    public void setUp() throws Exception {
-        mementoDir = Files.createTempDir();
-        mgmt = RebindTestUtils.newPersistingManagementContext(mementoDir, classLoader);
-        super.setUp();
-    }
-
-    @AfterMethod(alwaysRun=true)
-    @Override
-    public void tearDown() throws Exception {
-        super.tearDown();
-        if (newApp != null) Entities.destroyAll(newApp.getManagementContext());
-        if (newManagementContext != null) Entities.destroyAll(newManagementContext);
-        if (mementoDir != null) RebindTestUtils.deleteMementoDir(mementoDir);
-    }
-    
-    @Test
-    public void testReleasesLocationOnStopAfterRebinding() throws Exception {
-        origE = app.createAndManageChild(EntitySpec.create(MyService.class));
-        
-        MyProvisioningLocation origLoc = mgmt.getLocationManager().createLocation(LocationSpec.create(MyProvisioningLocation.class)
-                .displayName("mylocname"));
-        app.start(ImmutableList.of(origLoc));
-        assertEquals(origLoc.inUseCount.get(), 1);
-        
-        newApp = (TestApplication) rebind();
-        MyProvisioningLocation newLoc = (MyProvisioningLocation) Iterables.getOnlyElement(newApp.getLocations());
-        assertEquals(newLoc.inUseCount.get(), 1);
-        
-        newApp.stop();
-        assertEquals(newLoc.inUseCount.get(), 0);
-    }
-
-    @Test
-    public void testCreatesDriverAfterRebind() throws Exception {
-        origE = app.createAndManageChild(EntitySpec.create(MyService.class));
-        //the entity skips enricher initialization, do it explicitly
-        origE.addEnricher(ServiceStateLogic.newEnricherForServiceStateFromProblemsAndUp());
-
-        MyProvisioningLocation origLoc = mgmt.getLocationManager().createLocation(LocationSpec.create(MyProvisioningLocation.class)
-                .displayName("mylocname"));
-        app.start(ImmutableList.of(origLoc));
-        assertEquals(origE.getAttribute(Attributes.SERVICE_STATE_EXPECTED).getState(), Lifecycle.RUNNING);
-        EntityTestUtils.assertAttributeEqualsEventually(origE, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
-
-        ServiceProblemsLogic.updateProblemsIndicator((EntityLocal)origE, "test", "fire");
-        EntityTestUtils.assertAttributeEqualsEventually(origE, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);
-
-        newApp = (TestApplication) rebind();
-        MyService newE = (MyService) Iterables.getOnlyElement(newApp.getChildren());
-        assertTrue(newE.getDriver() != null, "driver should be initialized");
-    }
-
-    @Test
-    public void testDoesNotCreateDriverAfterRebind() throws Exception {
-        origE = app.createAndManageChild(EntitySpec.create(MyService.class));
-        //the entity skips enricher initialization, do it explicitly
-        origE.addEnricher(ServiceStateLogic.newEnricherForServiceStateFromProblemsAndUp());
-        
-        MyProvisioningLocation origLoc = mgmt.getLocationManager().createLocation(LocationSpec.create(MyProvisioningLocation.class)
-                .displayName("mylocname"));
-        app.start(ImmutableList.of(origLoc));
-        assertEquals(origE.getAttribute(Attributes.SERVICE_STATE_EXPECTED).getState(), Lifecycle.RUNNING);
-        EntityTestUtils.assertAttributeEqualsEventually(origE, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
-
-        ServiceStateLogic.setExpectedState(origE, Lifecycle.ON_FIRE);
-        EntityTestUtils.assertAttributeEqualsEventually(origE, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);
-
-        newApp = (TestApplication) rebind();
-        MyService newE = (MyService) Iterables.getOnlyElement(newApp.getChildren());
-        assertNull(newE.getDriver(), "driver should not be initialized because entity is in a permanent failure");
-    }
-
-    private TestApplication rebind() throws Exception {
-        RebindTestUtils.waitForPersisted(app);
-        TestApplication result = (TestApplication) RebindTestUtils.rebind(mementoDir, getClass().getClassLoader());
-        newManagementContext = result.getManagementContext();
-        return result;
-    }
-    
-    public static class MyProvisioningLocation extends AbstractLocation implements MachineProvisioningLocation<SshMachineLocation> {
-        private static final long serialVersionUID = 1L;
-        
-        @SetFromFlag(defaultVal="0")
-        AtomicInteger inUseCount;
-
-        public MyProvisioningLocation() {
-        }
-        
-        @Override
-        public MachineProvisioningLocation<SshMachineLocation> newSubLocation(Map<?, ?> newFlags) {
-            throw new UnsupportedOperationException();
-        }
-        
-        @Override
-        public SshMachineLocation obtain(Map flags) throws NoMachinesAvailableException {
-            inUseCount.incrementAndGet();
-            return getManagementContext().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                    .parent(this)
-                    .configure("address","localhost"));
-        }
-
-        @Override
-        public void release(SshMachineLocation machine) {
-            inUseCount.decrementAndGet();
-        }
-
-        @Override
-        public Map getProvisioningFlags(Collection tags) {
-            return Collections.emptyMap();
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessEntityTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessEntityTest.java b/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessEntityTest.java
deleted file mode 100644
index ecd50e6..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessEntityTest.java
+++ /dev/null
@@ -1,793 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.mgmt.EntityManager;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.api.mgmt.TaskAdaptable;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.apache.brooklyn.entity.drivers.BasicEntityDriverManager;
-import org.apache.brooklyn.entity.drivers.ReflectiveEntityDriverFactory;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
-import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.exceptions.PropagatedRuntimeException;
-import org.apache.brooklyn.util.net.UserAndHostAndPort;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.time.Duration;
-import org.jclouds.util.Throwables2;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-
-import brooklyn.entity.basic.SoftwareProcess.RestartSoftwareParameters;
-import brooklyn.entity.basic.SoftwareProcess.RestartSoftwareParameters.RestartMachineMode;
-import brooklyn.entity.basic.SoftwareProcess.StopSoftwareParameters;
-import brooklyn.entity.basic.SoftwareProcess.StopSoftwareParameters.StopMode;
-import brooklyn.entity.software.MachineLifecycleEffectorTasksTest;
-
-import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-
-public class SoftwareProcessEntityTest extends BrooklynAppUnitTestSupport {
-
-    // NB: These tests don't actually require ssh to localhost -- only that 'localhost' resolves.
-
-    private static final Logger LOG = LoggerFactory.getLogger(SoftwareProcessEntityTest.class);
-
-    private SshMachineLocation machine;
-    private FixedListMachineProvisioningLocation<SshMachineLocation> loc;
-    
-    @BeforeMethod(alwaysRun=true)
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-        loc = getLocation();
-    }
-
-    @SuppressWarnings("unchecked")
-    private FixedListMachineProvisioningLocation<SshMachineLocation> getLocation() {
-        FixedListMachineProvisioningLocation<SshMachineLocation> loc = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class));
-        machine = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                .configure("address", "localhost"));
-        loc.addMachine(machine);
-        return loc;
-    }
-
-    @Test
-    public void testSetsMachineAttributes() throws Exception {
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
-        entity.start(ImmutableList.of(loc));
-        
-        assertEquals(entity.getAttribute(SoftwareProcess.HOSTNAME), machine.getAddress().getHostName());
-        assertEquals(entity.getAttribute(SoftwareProcess.ADDRESS), machine.getAddress().getHostAddress());
-        assertEquals(entity.getAttribute(Attributes.SSH_ADDRESS), UserAndHostAndPort.fromParts(machine.getUser(), machine.getAddress().getHostName(), machine.getPort()));
-        assertEquals(entity.getAttribute(SoftwareProcess.PROVISIONING_LOCATION), loc);
-    }
-
-    @Test
-    public void testProcessTemplateWithExtraSubstitutions() throws Exception {
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
-        entity.start(ImmutableList.of(loc));
-        SimulatedDriver driver = (SimulatedDriver) entity.getDriver();
-        Map<String,String> substitutions = MutableMap.of("myname","peter");
-        String result = driver.processTemplate("/brooklyn/entity/basic/template_with_extra_substitutions.txt",substitutions);
-        Assert.assertTrue(result.contains("peter"));
-    }
-
-    @Test
-    public void testInstallDirAndRunDir() throws Exception {
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)
-            .configure(BrooklynConfigKeys.ONBOX_BASE_DIR, "/tmp/brooklyn-foo"));
-
-        entity.start(ImmutableList.of(loc));
-
-        Assert.assertEquals(entity.getAttribute(SoftwareProcess.INSTALL_DIR), "/tmp/brooklyn-foo/installs/MyService");
-        Assert.assertEquals(entity.getAttribute(SoftwareProcess.RUN_DIR), "/tmp/brooklyn-foo/apps/"+entity.getApplicationId()+"/entities/MyService_"+entity.getId());
-    }
-
-    @Test
-    public void testInstallDirAndRunDirUsingTilde() throws Exception {
-        String dataDirName = ".brooklyn-foo"+Strings.makeRandomId(4);
-        String dataDir = "~/"+dataDirName;
-        String resolvedDataDir = Os.mergePaths(Os.home(), dataDirName);
-        
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)
-            .configure(BrooklynConfigKeys.ONBOX_BASE_DIR, dataDir));
-
-        entity.start(ImmutableList.of(loc));
-
-        Assert.assertEquals(Os.nativePath(entity.getAttribute(SoftwareProcess.INSTALL_DIR)),
-                            Os.nativePath(Os.mergePaths(resolvedDataDir, "installs/MyService")));
-        Assert.assertEquals(Os.nativePath(entity.getAttribute(SoftwareProcess.RUN_DIR)),
-                            Os.nativePath(Os.mergePaths(resolvedDataDir, "apps/"+entity.getApplicationId()+"/entities/MyService_"+entity.getId())));
-    }
-
-    protected <T extends MyService> void doStartAndCheckVersion(Class<T> type, String expectedLabel, ConfigBag config) {
-        MyService entity = app.createAndManageChild(EntitySpec.create(type)
-            .configure(BrooklynConfigKeys.ONBOX_BASE_DIR, "/tmp/brooklyn-foo")
-            .configure(config.getAllConfigAsConfigKeyMap()));
-        entity.start(ImmutableList.of(loc));
-        Assert.assertEquals(entity.getAttribute(SoftwareProcess.INSTALL_DIR), "/tmp/brooklyn-foo/installs/"
-            + expectedLabel);
-    }
-    
-    @Test
-    public void testCustomInstallDir0() throws Exception {
-        doStartAndCheckVersion(MyService.class, "MyService", ConfigBag.newInstance());
-    }
-    @Test
-    public void testCustomInstallDir1() throws Exception {
-        doStartAndCheckVersion(MyService.class, "MyService_9.9.8", ConfigBag.newInstance()
-            .configure(SoftwareProcess.SUGGESTED_VERSION, "9.9.8"));
-    }
-    @Test
-    public void testCustomInstallDir2() throws Exception {
-        doStartAndCheckVersion(MyService.class, "MySvc_998", ConfigBag.newInstance()
-            .configure(SoftwareProcess.INSTALL_UNIQUE_LABEL, "MySvc_998"));
-    }
-    @Test
-    public void testCustomInstallDir3() throws Exception {
-        doStartAndCheckVersion(MyServiceWithVersion.class, "MyServiceWithVersion_9.9.9", ConfigBag.newInstance());
-    }
-    @Test
-    public void testCustomInstallDir4() throws Exception {
-        doStartAndCheckVersion(MyServiceWithVersion.class, "MyServiceWithVersion_9.9.7", ConfigBag.newInstance()
-            .configure(SoftwareProcess.SUGGESTED_VERSION, "9.9.7"));
-    }
-    @Test
-    public void testCustomInstallDir5() throws Exception {
-        doStartAndCheckVersion(MyServiceWithVersion.class, "MyServiceWithVersion_9.9.9_NaCl", ConfigBag.newInstance()
-            .configure(ConfigKeys.newStringConfigKey("salt"), "NaCl"));
-    }
-
-    @Test
-    public void testBasicSoftwareProcessEntityLifecycle() throws Exception {
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
-        entity.start(ImmutableList.of(loc));
-        SimulatedDriver d = (SimulatedDriver) entity.getDriver();
-        Assert.assertTrue(d.isRunning());
-        entity.stop();
-        Assert.assertEquals(d.events, ImmutableList.of("setup", "copyInstallResources", "install", "customize", "copyRuntimeResources", "launch", "stop"));
-        assertFalse(d.isRunning());
-    }
-    
-    @Test
-    public void testBasicSoftwareProcessRestarts() throws Exception {
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
-        entity.start(ImmutableList.of(loc));
-        SimulatedDriver d = (SimulatedDriver) entity.getDriver();
-        Assert.assertTrue(d.isRunning());
-        
-        // this will cause restart to fail if it attempts to replace the machine
-        loc.removeMachine(Locations.findUniqueSshMachineLocation(entity.getLocations()).get());
-        
-        // with defaults, it won't reboot machine
-        d.events.clear();
-        entity.restart();
-        assertEquals(d.events, ImmutableList.of("stop", "launch"));
-
-        // but here, it will try to reboot, and fail because there is no machine available
-        TaskAdaptable<Void> t1 = Entities.submit(entity, Effectors.invocation(entity, Startable.RESTART, 
-                ConfigBag.newInstance().configure(RestartSoftwareParameters.RESTART_MACHINE_TYPED, RestartMachineMode.TRUE)));
-        t1.asTask().blockUntilEnded(Duration.TEN_SECONDS);
-        if (!t1.asTask().isError()) {
-            Assert.fail("Should have thrown error during "+t1+" because no more machines available at "+loc);
-        }
-
-        // now it has a machine, so reboot should succeed
-        SshMachineLocation machine2 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-            .configure("address", "localhost"));
-        loc.addMachine(machine2);
-        TaskAdaptable<Void> t2 = Entities.submit(entity, Effectors.invocation(entity, Startable.RESTART, 
-            ConfigBag.newInstance().configure(RestartSoftwareParameters.RESTART_MACHINE_TYPED, RestartMachineMode.TRUE)));
-        t2.asTask().get();
-        
-        assertFalse(d.isRunning());
-    }
-
-    @Test
-    public void testBasicSoftwareProcessStopsEverything() throws Exception {
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
-        entity.start(ImmutableList.of(loc));
-        SimulatedDriver d = (SimulatedDriver) entity.getDriver();
-        Location machine = Iterables.getOnlyElement(entity.getLocations());
-
-        d.events.clear();
-        entity.stop();
-        assertEquals(d.events, ImmutableList.of("stop"));
-        assertEquals(entity.getLocations().size(), 0);
-        assertTrue(loc.getAvailable().contains(machine));
-    }
-
-    @Test
-    public void testBasicSoftwareProcessStopEverythingExplicitly() throws Exception {
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
-        entity.start(ImmutableList.of(loc));
-        SimulatedDriver d = (SimulatedDriver) entity.getDriver();
-        Location machine = Iterables.getOnlyElement(entity.getLocations());
-        d.events.clear();
-
-        TaskAdaptable<Void> t1 = Entities.submit(entity, Effectors.invocation(entity, Startable.STOP,
-                ConfigBag.newInstance().configure(StopSoftwareParameters.STOP_MACHINE_MODE, StopSoftwareParameters.StopMode.IF_NOT_STOPPED)));
-        t1.asTask().get();
-
-        assertEquals(d.events, ImmutableList.of("stop"));
-        assertEquals(entity.getLocations().size(), 0);
-        assertTrue(loc.getAvailable().contains(machine));
-    }
-
-    @Test
-    public void testBasicSoftwareProcessStopsProcess() throws Exception {
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
-        entity.start(ImmutableList.of(loc));
-        SimulatedDriver d = (SimulatedDriver) entity.getDriver();
-        Location machine = Iterables.getOnlyElement(entity.getLocations());
-        d.events.clear();
-
-        TaskAdaptable<Void> t1 = Entities.submit(entity, Effectors.invocation(entity, Startable.STOP,
-                ConfigBag.newInstance().configure(StopSoftwareParameters.STOP_MACHINE_MODE, StopSoftwareParameters.StopMode.NEVER)));
-        t1.asTask().get(10, TimeUnit.SECONDS);
-
-        assertEquals(d.events, ImmutableList.of("stop"));
-        assertEquals(ImmutableList.copyOf(entity.getLocations()), ImmutableList.of(machine));
-        assertFalse(loc.getAvailable().contains(machine));
-    }
-    
-    @Test(groups = "Integration")
-    public void testBasicSoftwareProcessStopAllModes() throws Exception {
-        for (boolean isEntityStopped : new boolean[] {true, false}) {
-            for (StopMode stopProcessMode : StopMode.values()) {
-                for (StopMode stopMachineMode : StopMode.values()) {
-                    try {
-                        testBasicSoftwareProcessStopModes(stopProcessMode, stopMachineMode, isEntityStopped);
-                    } catch (Exception e) {
-                        String msg = "stopProcessMode: " + stopProcessMode + ", stopMachineMode: " + stopMachineMode + ", isEntityStopped: " + isEntityStopped;
-                        throw new PropagatedRuntimeException(msg, e);
-                    }
-                }
-            }
-        }
-    }
-    
-    @Test
-    public void testBasicSoftwareProcessStopSomeModes() throws Exception {
-        for (boolean isEntityStopped : new boolean[] {true, false}) {
-            StopMode stopProcessMode = StopMode.IF_NOT_STOPPED;
-            StopMode stopMachineMode = StopMode.IF_NOT_STOPPED;
-            try {
-                testBasicSoftwareProcessStopModes(stopProcessMode, stopMachineMode, isEntityStopped);
-            } catch (Exception e) {
-                String msg = "stopProcessMode: " + stopProcessMode + ", stopMachineMode: " + stopMachineMode + ", isEntityStopped: " + isEntityStopped;
-                throw new PropagatedRuntimeException(msg, e);
-            }
-        }
-    }
-    
-    private void testBasicSoftwareProcessStopModes(StopMode stopProcessMode, StopMode stopMachineMode, boolean isEntityStopped) throws Exception {
-        FixedListMachineProvisioningLocation<SshMachineLocation> l = getLocation();
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
-        entity.start(ImmutableList.of(l));
-        SimulatedDriver d = (SimulatedDriver) entity.getDriver();
-        Location machine = Iterables.getOnlyElement(entity.getLocations());
-        d.events.clear();
-
-        if (isEntityStopped) {
-            ((EntityInternal)entity).setAttribute(ServiceStateLogic.SERVICE_STATE_ACTUAL, Lifecycle.STOPPED);
-        }
-
-        TaskAdaptable<Void> t1 = Entities.submit(entity, Effectors.invocation(entity, Startable.STOP,
-                ConfigBag.newInstance()
-                    .configure(StopSoftwareParameters.STOP_PROCESS_MODE, stopProcessMode)
-                    .configure(StopSoftwareParameters.STOP_MACHINE_MODE, stopMachineMode)));
-        t1.asTask().get(10, TimeUnit.SECONDS);
-
-        if (MachineLifecycleEffectorTasksTest.canStop(stopProcessMode, isEntityStopped)) {
-            assertEquals(d.events, ImmutableList.of("stop"));
-        } else {
-            assertTrue(d.events.isEmpty());
-        }
-        if (MachineLifecycleEffectorTasksTest.canStop(stopMachineMode, machine == null)) {
-            assertTrue(entity.getLocations().isEmpty());
-            assertTrue(l.getAvailable().contains(machine));
-        } else {
-            assertEquals(ImmutableList.copyOf(entity.getLocations()), ImmutableList.of(machine));
-            assertFalse(l.getAvailable().contains(machine));
-        }
-    }
-
-    @Test
-    public void testShutdownIsIdempotent() throws Exception {
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
-        entity.start(ImmutableList.of(loc));
-        entity.stop();
-        
-        entity.stop();
-    }
-    
-    @Test
-    public void testReleaseEvenIfErrorDuringStart() throws Exception {
-        MyServiceImpl entity = new MyServiceImpl(app) {
-            @Override public Class<?> getDriverInterface() {
-                return SimulatedFailOnStartDriver.class;
-            }
-        };
-        Entities.manage(entity);
-        
-        try {
-            entity.start(ImmutableList.of(loc));
-            Assert.fail();
-        } catch (Exception e) {
-            IllegalStateException cause = Throwables2.getFirstThrowableOfType(e, IllegalStateException.class);
-            if (cause == null || !cause.toString().contains("Simulating start error")) throw e; 
-        }
-        
-        try {
-            entity.stop();
-        } catch (Exception e) {
-            // Keep going
-            LOG.info("Error during stop, after simulating error during start", e);
-        }
-        Assert.assertEquals(loc.getAvailable(), ImmutableSet.of(machine));
-        Entities.unmanage(entity);
-    }
-
-    @SuppressWarnings("rawtypes")
-    public void doTestReleaseEvenIfErrorDuringStop(final Class driver) throws Exception {
-        MyServiceImpl entity = new MyServiceImpl(app) {
-            @Override public Class<?> getDriverInterface() {
-                return driver;
-            }
-        };
-        Entities.manage(entity);
-        
-        entity.start(ImmutableList.of(loc));
-        Task<Void> t = entity.invoke(Startable.STOP);
-        t.blockUntilEnded();
-        
-        assertFalse(t.isError(), "Expected parent to succeed, not fail with " + Tasks.getError(t));
-        Iterator<Task<?>> failures;
-        failures = Tasks.failed(Tasks.descendants(t, true)).iterator();
-        Assert.assertTrue(failures.hasNext(), "Expected error in descendants");
-        failures = Tasks.failed(Tasks.children(t)).iterator();
-        Assert.assertTrue(failures.hasNext(), "Expected error in child");
-        Throwable e = Tasks.getError(failures.next());
-        if (e == null || !e.toString().contains("Simulating stop error")) 
-            Assert.fail("Wrong error", e);
-
-        Assert.assertEquals(loc.getAvailable(), ImmutableSet.of(machine), "Expected location to be available again");
-
-        Entities.unmanage(entity);
-    }
-
-    @Test
-    public void testReleaseEvenIfErrorDuringStop() throws Exception {
-        doTestReleaseEvenIfErrorDuringStop(SimulatedFailOnStopDriver.class);
-    }
-    
-    @Test
-    public void testReleaseEvenIfChildErrorDuringStop() throws Exception {
-        doTestReleaseEvenIfErrorDuringStop(SimulatedFailInChildOnStopDriver.class);
-    }
-
-    @Test
-    public void testDoubleStopEntity() {
-        ReflectiveEntityDriverFactory f = ((BasicEntityDriverManager)mgmt.getEntityDriverManager()).getReflectiveDriverFactory();
-        f.addClassFullNameMapping(EmptySoftwareProcessDriver.class.getName(), MinimalEmptySoftwareProcessTestDriver.class.getName());
-
-        // Second stop on SoftwareProcess will return early, while the first stop is still in progress
-        // This causes the app to shutdown prematurely, leaking machines.
-        EntityManager emgr = mgmt.getEntityManager();
-        EntitySpec<TestApplication> appSpec = EntitySpec.create(TestApplication.class);
-        TestApplication app = emgr.createEntity(appSpec);
-        emgr.manage(app);
-        EntitySpec<?> latchEntitySpec = EntitySpec.create(EmptySoftwareProcess.class);
-        Entity entity = app.createAndManageChild(latchEntitySpec);
-
-        final ReleaseLatchLocation loc = mgmt.getLocationManager().createLocation(LocationSpec.create(ReleaseLatchLocation.class));
-        try {
-            app.start(ImmutableSet.of(loc));
-            EntityTestUtils.assertAttributeEquals(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
-    
-            final Task<Void> firstStop = entity.invoke(Startable.STOP, ImmutableMap.<String, Object>of());
-            // Wait until first task tries to release the location, at this point the entity's reference 
-            // to the location is already cleared.
-            Asserts.succeedsEventually(new Runnable() {
-                @Override
-                public void run() {
-                    assertTrue(loc.isBlocked());
-                }
-            });
-    
-            // Subsequent stops will end quickly - no location to release,
-            // while the first one is still releasing the machine.
-            final Task<Void> secondStop = entity.invoke(Startable.STOP, ImmutableMap.<String, Object>of());;
-            Asserts.succeedsEventually(new Runnable() {
-                @Override
-                public void run() {
-                    assertTrue(secondStop.isDone());
-                }
-            });
-    
-            // Entity state is STOPPED even though first location is still releasing
-            EntityTestUtils.assertAttributeEquals(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.STOPPED);
-            Asserts.succeedsContinually(new Runnable() {
-                @Override
-                public void run() {
-                    assertFalse(firstStop.isDone());
-                }
-            });
-
-            loc.unblock();
-
-            // After the location is released, first task ends as well.
-            EntityTestUtils.assertAttributeEquals(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.STOPPED);
-            Asserts.succeedsEventually(new Runnable() {
-                @Override
-                public void run() {
-                    assertTrue(firstStop.isDone());
-                }
-            });
-
-        } finally {
-            loc.unblock();
-        }
-
-    }
-
-    @Test
-    public void testDoubleStopApp() {
-        ReflectiveEntityDriverFactory f = ((BasicEntityDriverManager)mgmt.getEntityDriverManager()).getReflectiveDriverFactory();
-        f.addClassFullNameMapping(EmptySoftwareProcessDriver.class.getName(), MinimalEmptySoftwareProcessTestDriver.class.getName());
-
-        // Second stop on SoftwareProcess will return early, while the first stop is still in progress
-        // This causes the app to shutdown prematurely, leaking machines.
-        EntityManager emgr = mgmt.getEntityManager();
-        EntitySpec<TestApplication> appSpec = EntitySpec.create(TestApplication.class);
-        final TestApplication app = emgr.createEntity(appSpec);
-        emgr.manage(app);
-        EntitySpec<?> latchEntitySpec = EntitySpec.create(EmptySoftwareProcess.class);
-        final Entity entity = app.createAndManageChild(latchEntitySpec);
-
-        final ReleaseLatchLocation loc = mgmt.getLocationManager().createLocation(LocationSpec.create(ReleaseLatchLocation.class));
-        try {
-            app.start(ImmutableSet.of(loc));
-            EntityTestUtils.assertAttributeEquals(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
-    
-            final Task<Void> firstStop = app.invoke(Startable.STOP, ImmutableMap.<String, Object>of());
-            // Wait until first task tries to release the location, at this point the entity's reference 
-            // to the location is already cleared.
-            Asserts.succeedsEventually(new Runnable() {
-                @Override
-                public void run() {
-                    assertTrue(loc.isBlocked());
-                }
-            });
-    
-            // Subsequent stops will end quickly - no location to release,
-            // while the first one is still releasing the machine.
-            final Task<Void> secondStop = app.invoke(Startable.STOP, ImmutableMap.<String, Object>of());;
-            Asserts.succeedsEventually(new Runnable() {
-                @Override
-                public void run() {
-                    assertTrue(secondStop.isDone());
-                }
-            });
-    
-            // Since second stop succeeded the app will get unmanaged.
-            Asserts.succeedsEventually(new Runnable() {
-                @Override
-                public void run() {
-                    assertTrue(!Entities.isManaged(entity));
-                    assertTrue(!Entities.isManaged(app));
-                }
-            });
-    
-            // Unmanage will cancel the first task
-            Asserts.succeedsEventually(new Runnable() {
-                @Override
-                public void run() {
-                    assertTrue(firstStop.isDone());
-                }
-            });
-        } finally {
-            // We still haven't unblocked the location release, but entity is already unmanaged.
-            // Double STOP on an application could leak locations!!!
-            loc.unblock();
-        }
-    }
-
-    @Test
-    public void testOpenPortsWithPortRangeConfig() throws Exception {
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)
-            .configure("http.port", "9999+"));
-        Assert.assertTrue(entity.getRequiredOpenPorts().contains(9999));
-    }
-
-    @ImplementedBy(MyServiceImpl.class)
-    public interface MyService extends SoftwareProcess {
-        PortAttributeSensorAndConfigKey HTTP_PORT = Attributes.HTTP_PORT;
-        public SoftwareProcessDriver getDriver();
-        public Collection<Integer> getRequiredOpenPorts();
-    }
-
-    public static class MyServiceImpl extends SoftwareProcessImpl implements MyService {
-        public MyServiceImpl() {}
-        public MyServiceImpl(Entity parent) { super(parent); }
-
-        @Override
-        protected void initEnrichers() {
-            // Don't add enrichers messing with the SERVICE_UP state - we are setting it manually
-        }
-
-        @Override
-        public Class<?> getDriverInterface() {
-            return SimulatedDriver.class;
-        }
-
-        @Override
-        public Collection<Integer> getRequiredOpenPorts() {
-            return super.getRequiredOpenPorts();
-        }
-    }
-
-    @ImplementedBy(MyServiceWithVersionImpl.class)
-    public interface MyServiceWithVersion extends MyService {
-        public static ConfigKey<String> SUGGESTED_VERSION = ConfigKeys.newConfigKeyWithDefault(SoftwareProcess.SUGGESTED_VERSION, "9.9.9");
-    }
-
-    public static class MyServiceWithVersionImpl extends MyServiceImpl implements MyServiceWithVersion {
-        public MyServiceWithVersionImpl() {}
-        public MyServiceWithVersionImpl(Entity parent) { super(parent); }
-    }
-
-    public static class SimulatedFailOnStartDriver extends SimulatedDriver {
-        public SimulatedFailOnStartDriver(EntityLocal entity, SshMachineLocation machine) {
-            super(entity, machine);
-        }
-        
-        @Override
-        public void install() {
-            throw new IllegalStateException("Simulating start error");
-        }
-    }
-    
-    public static class SimulatedFailOnStopDriver extends SimulatedDriver {
-        public SimulatedFailOnStopDriver(EntityLocal entity, SshMachineLocation machine) {
-            super(entity, machine);
-        }
-        
-        @Override
-        public void stop() {
-            throw new IllegalStateException("Simulating stop error");
-        }
-    }
-    
-    public static class SimulatedFailInChildOnStopDriver extends SimulatedDriver {
-        public SimulatedFailInChildOnStopDriver(EntityLocal entity, SshMachineLocation machine) {
-            super(entity, machine);
-        }
-        
-        @Override
-        public void stop() {
-            DynamicTasks.queue(Tasks.fail("Simulating stop error in child", null));
-        }
-    }
-    
-    public static class SimulatedDriver extends AbstractSoftwareProcessSshDriver {
-        public List<String> events = new ArrayList<String>();
-        private volatile boolean launched = false;
-        
-        public SimulatedDriver(EntityLocal entity, SshMachineLocation machine) {
-            super(entity, machine);
-        }
-
-        @Override
-        public boolean isRunning() {
-            return launched;
-        }
-    
-        @Override
-        public void stop() {
-            events.add("stop");
-            launched = false;
-            entity.setAttribute(Startable.SERVICE_UP, false);
-            entity.setAttribute(SoftwareProcess.SERVICE_STATE_ACTUAL, Lifecycle.STOPPED);
-        }
-    
-        @Override
-        public void kill() {
-            events.add("kill");
-            launched = false;
-            entity.setAttribute(Startable.SERVICE_UP, false);
-        }
-    
-        @Override
-        public void install() {
-            events.add("install");
-            entity.setAttribute(SoftwareProcess.SERVICE_STATE_ACTUAL, Lifecycle.STARTING);
-        }
-    
-        @Override
-        public void customize() {
-            events.add("customize");
-        }
-    
-        @Override
-        public void launch() {
-            events.add("launch");
-            launched = true;
-            entity.setAttribute(Startable.SERVICE_UP, true);
-            entity.setAttribute(SoftwareProcess.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
-        }
-
-        @Override
-        public void setup() {
-            events.add("setup");
-        }
-
-        @Override
-        public void copyInstallResources() {
-            events.add("copyInstallResources");
-        }
-
-        @Override
-        public void copyRuntimeResources() {
-            events.add("copyRuntimeResources");
-        }
-
-        @Override
-        public void runPreInstallCommand(String command) { }
-
-        @Override
-        public void runPostInstallCommand(String command) { }
-
-        @Override
-        public void runPreLaunchCommand(String command) { }
-
-        @Override
-        public void runPostLaunchCommand(String command) { }
-
-        @Override
-        protected String getInstallLabelExtraSalt() {
-            return (String)getEntity().getConfigRaw(ConfigKeys.newStringConfigKey("salt"), true).or((String)null);
-        }
-    }
-
-    public static class ReleaseLatchLocation extends SimulatedLocation {
-        private static final long serialVersionUID = 1L;
-        
-        private CountDownLatch lock = new CountDownLatch(1);
-        private volatile boolean isBlocked;
-
-        public void unblock() {
-            lock.countDown();
-        }
-        @Override
-        public void release(MachineLocation machine) {
-            super.release(machine);
-            try {
-                isBlocked = true;
-                lock.await();
-                isBlocked = false;
-            } catch (InterruptedException e) {
-                throw Exceptions.propagate(e);
-            }
-        }
-
-        public boolean isBlocked() {
-            return isBlocked;
-        }
-
-    }
-
-    public static class MinimalEmptySoftwareProcessTestDriver implements EmptySoftwareProcessDriver {
-
-        private EmptySoftwareProcessImpl entity;
-        private Location location;
-
-        public MinimalEmptySoftwareProcessTestDriver(EmptySoftwareProcessImpl entity, Location location) {
-            this.entity = entity;
-            this.location = location;
-        }
-
-        @Override
-        public Location getLocation() {
-            return location;
-        }
-
-        @Override
-        public EntityLocal getEntity() {
-            return entity;
-        }
-
-        @Override
-        public boolean isRunning() {
-            return true;
-        }
-
-        @Override
-        public void rebind() {
-        }
-
-        @Override
-        public void start() {
-        }
-
-        @Override
-        public void restart() {
-        }
-
-        @Override
-        public void stop() {
-        }
-
-        @Override
-        public void kill() {
-        }
-
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessSshDriverIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessSshDriverIntegrationTest.java b/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessSshDriverIntegrationTest.java
deleted file mode 100644
index c4ce2fe..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessSshDriverIntegrationTest.java
+++ /dev/null
@@ -1,385 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotEquals;
-import static org.testng.Assert.assertTrue;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.BrooklynNetworkUtils;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.stream.KnownSizeInputStream;
-import org.apache.brooklyn.util.stream.Streams;
-import org.apache.brooklyn.util.yaml.Yamls;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-import com.google.common.base.Charsets;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.io.ByteSource;
-import com.google.common.io.Files;
-
-
-public class SoftwareProcessSshDriverIntegrationTest {
-
-    private LocalManagementContext managementContext;
-    private LocalhostMachineProvisioningLocation localhost;
-    private SshMachineLocation machine127;
-    private TestApplication app;
-    private File tempDataDir;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        tempDataDir = Files.createTempDir();
-        managementContext = new LocalManagementContext();
-        
-        localhost = managementContext.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class));
-        machine127 = managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                .configure("address", "localhost"));
-        app = ApplicationBuilder.newManagedApp(TestApplication.class, managementContext);
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-        if (tempDataDir != null) Os.deleteRecursively(tempDataDir);
-    }
-
-    // Integration test because requires ssh'ing (and takes about 5 seconds)
-    // See also SoftwareProcessEntityTest.testCustomInstallDirX for a lot more mocked variants
-    @Test(groups="Integration")
-    public void testCanInstallMultipleVersionsOnSameMachine() throws Exception {
-        managementContext.getBrooklynProperties().put(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath());
-
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)
-                .configure(SoftwareProcess.SUGGESTED_VERSION, "0.1.0"));
-        MyService entity2 = app.createAndManageChild(EntitySpec.create(MyService.class)
-                .configure(SoftwareProcess.SUGGESTED_VERSION, "0.2.0"));
-        app.start(ImmutableList.of(machine127));
-        
-        String installDir1 = entity.getAttribute(SoftwareProcess.INSTALL_DIR);
-        String installDir2 = entity2.getAttribute(SoftwareProcess.INSTALL_DIR);
-        
-        assertNotEquals(installDir1, installDir2);
-        assertTrue(installDir1.contains("0.1.0"), "installDir1="+installDir1);
-        assertTrue(installDir2.contains("0.2.0"), "installDir2="+installDir2);
-        assertTrue(new File(new File(installDir1), "myfile").isFile());
-        assertTrue(new File(new File(installDir2), "myfile").isFile());
-    }
-
-    @Test(groups="Integration")
-    public void testLocalhostInTmp() throws Exception {
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
-        app.start(ImmutableList.of(localhost));
-
-        String installDir = entity.getAttribute(SoftwareProcess.INSTALL_DIR);
-        assertTrue(installDir.startsWith("/tmp/brooklyn-"+Os.user()+"/installs/"), "installed in "+installDir);
-    }
-
-    @Test(groups="Integration")
-    public void testMachine127InHome() throws Exception {
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
-        app.start(ImmutableList.of(machine127));
-
-        String installDir = entity.getAttribute(SoftwareProcess.INSTALL_DIR);
-        assertTrue(installDir.startsWith(Os.home()+"/brooklyn-managed-processes/installs/"), "installed in "+installDir);
-    }
-
-    @Test(groups="Integration")
-    public void testLocalhostInCustom() throws Exception {
-        localhost.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath());
-
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
-        app.start(ImmutableList.of(localhost));
-
-        String installDir = entity.getAttribute(SoftwareProcess.INSTALL_DIR);
-        assertTrue(installDir.startsWith(tempDataDir.getAbsolutePath()+"/installs/"), "installed in "+installDir);
-    }
-
-    @Test(groups="Integration")
-    @Deprecated
-    public void testMachineInCustomFromDataDir() throws Exception {
-        managementContext.getBrooklynProperties().put(BrooklynConfigKeys.BROOKLYN_DATA_DIR, tempDataDir.getAbsolutePath());
-
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
-        app.start(ImmutableList.of(machine127));
-
-        String installDir = entity.getAttribute(SoftwareProcess.INSTALL_DIR);
-        assertTrue(installDir.startsWith(tempDataDir.getAbsolutePath()+"/installs/"), "installed in "+installDir);
-    }
-
-    @Test(groups="Integration")
-    public void testCopyResource() throws Exception {
-        File tempDest = new File(tempDataDir, "tempDest.txt");
-        String tempLocalContent = "abc";
-        File tempLocal = new File(tempDataDir, "tempLocal.txt");
-        Files.write(tempLocalContent, tempLocal, Charsets.UTF_8);
-        
-        localhost.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath());
-
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
-        app.start(ImmutableList.of(localhost));
-
-        // Copy local file
-        entity.getDriver().copyResource(tempLocal, tempDest.getAbsolutePath());
-        assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent));
-        tempDest.delete();
-        
-        // Copy local file using url
-        entity.getDriver().copyResource(tempLocal.toURI().toString(), tempDest.getAbsolutePath());
-        assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent));
-        tempDest.delete();
-        
-        // Copy reader
-        entity.getDriver().copyResource(new StringReader(tempLocalContent), tempDest.getAbsolutePath());
-        assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent));
-        tempDest.delete();
-        
-        // Copy stream
-        entity.getDriver().copyResource(ByteSource.wrap(tempLocalContent.getBytes()).openStream(), tempDest.getAbsolutePath());
-        assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent));
-        tempDest.delete();
-        
-        // Copy known-size stream
-        entity.getDriver().copyResource(new KnownSizeInputStream(Streams.newInputStreamWithContents(tempLocalContent), tempLocalContent.length()), tempDest.getAbsolutePath());
-        assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent));
-        tempDest.delete();
-    }
-
-    @Test(groups="Integration")
-    public void testCopyResourceCreatingParentDir() throws Exception {
-        /*
-         * TODO copyResource will now always create the parent dir, irrespective of the createParentDir value!
-         * In SshMachineLocation on 2014-05-29, Alex added: mkdir -p `dirname '$DEST'`
-         * 
-         * Changing this test to assert that parent dir always created; should we delete boolean createParentDir
-         * from the copyResource method?
-         * 
-         * TODO Have also deleted test that if relative path is given it will write that relative to $RUN_DIR.
-         * That is not the case: it is relative to $HOME, which seems fine. For example, if copyResource
-         * is used during install phase then $RUN_DIR would be the wrong default. 
-         * Is there any code that relies on this behaviour?
-         */
-        File tempDataDirSub = new File(tempDataDir, "subdir");
-        File tempDest = new File(tempDataDirSub, "tempDest.txt");
-        String tempLocalContent = "abc";
-        File tempLocal = new File(tempDataDir, "tempLocal.txt");
-        Files.write(tempLocalContent, tempLocal, Charsets.UTF_8);
-        
-        localhost.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath());
-
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
-        app.start(ImmutableList.of(localhost));
-
-        // First confirm that even if createParentDir==false that it still gets created!
-        try {
-            entity.getDriver().copyResource(tempLocal.toURI().toString(), tempDest.getAbsolutePath(), false);
-            assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent));
-        } finally {
-            Os.deleteRecursively(tempDataDirSub);
-        }
-
-        // Copy to absolute path
-        try {
-            entity.getDriver().copyResource(tempLocal.toURI().toString(), tempDest.getAbsolutePath(), true);
-            assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent));
-        } finally {
-            Os.deleteRecursively(tempDataDirSub);
-        }
-    }
-
-    @Test(groups="Integration")
-    public void testPreAndPostLaunchCommands() throws IOException {
-        File tempFile = new File(tempDataDir, "tempFile.txt");
-        localhost.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath());
-        app.createAndManageChild(EntitySpec.create(VanillaSoftwareProcess.class)
-                .configure(VanillaSoftwareProcess.CHECK_RUNNING_COMMAND, "")
-                .configure(SoftwareProcess.PRE_LAUNCH_COMMAND, String.format("echo inPreLaunch >> %s", tempFile.getAbsoluteFile()))
-                .configure(VanillaSoftwareProcess.LAUNCH_COMMAND, String.format("echo inLaunch >> %s", tempFile.getAbsoluteFile()))
-                .configure(SoftwareProcess.POST_LAUNCH_COMMAND, String.format("echo inPostLaunch >> %s", tempFile.getAbsoluteFile())));
-        app.start(ImmutableList.of(localhost));
-
-        List<String> output = Files.readLines(tempFile, Charsets.UTF_8);
-        assertEquals(output.size(), 3);
-        assertEquals(output.get(0), "inPreLaunch");
-        assertEquals(output.get(1), "inLaunch");
-        assertEquals(output.get(2), "inPostLaunch");
-        tempFile.delete();
-    }
-
-    @Test(groups="Integration")
-    public void testInstallResourcesCopy() throws IOException {
-        localhost.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath());
-        File template = new File(Os.tmp(), "template.yaml");
-        VanillaSoftwareProcess entity = app.createAndManageChild(EntitySpec.create(VanillaSoftwareProcess.class)
-                .configure(VanillaSoftwareProcess.CHECK_RUNNING_COMMAND, "")
-                .configure(SoftwareProcess.INSTALL_FILES, MutableMap.of("classpath://brooklyn/entity/basic/frogs.txt", "frogs.txt"))
-                .configure(SoftwareProcess.INSTALL_TEMPLATES, MutableMap.of("classpath://brooklyn/entity/basic/template.yaml", template.getAbsolutePath()))
-                .configure(VanillaSoftwareProcess.LAUNCH_COMMAND, "date"));
-        app.start(ImmutableList.of(localhost));
-
-        File frogs = new File(entity.getAttribute(SoftwareProcess.INSTALL_DIR), "frogs.txt");
-        try {
-            Assert.assertTrue(frogs.canRead(), "File not readable: " + frogs);
-            String output = Files.toString(frogs, Charsets.UTF_8);
-            Assert.assertTrue(output.contains("Brekekekex"), "File content not found: " + output);
-        } finally {
-            frogs.delete();
-        }
-
-        try {
-            String expectedHostname = BrooklynNetworkUtils.getLocalhostInetAddress().getHostName();
-            String expectedIp = BrooklynNetworkUtils.getLocalhostInetAddress().getHostAddress();
-            
-            Map<?,?> data = (Map) Iterables.getOnlyElement(Yamls.parseAll(Files.toString(template, Charsets.UTF_8)));
-            Assert.assertEquals(data.size(), 3);
-            Assert.assertEquals(data.get("entity.hostname"), expectedHostname);
-            Assert.assertEquals(data.get("entity.address"), expectedIp);
-            Assert.assertEquals(data.get("frogs"), Integer.valueOf(12));
-        } finally {
-            template.delete();
-        }
-    }
-
-    @Test(groups="Integration")
-    public void testRuntimeResourcesCopy() throws IOException {
-        localhost.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath());
-        File template = new File(Os.tmp(), "template.yaml");
-        VanillaSoftwareProcess entity = app.createAndManageChild(EntitySpec.create(VanillaSoftwareProcess.class)
-                .configure(VanillaSoftwareProcess.CHECK_RUNNING_COMMAND, "")
-                .configure(SoftwareProcess.RUNTIME_FILES, MutableMap.of("classpath://brooklyn/entity/basic/frogs.txt", "frogs.txt"))
-                .configure(SoftwareProcess.RUNTIME_TEMPLATES, MutableMap.of("classpath://brooklyn/entity/basic/template.yaml", template.getAbsolutePath()))
-                .configure(VanillaSoftwareProcess.LAUNCH_COMMAND, "date"));
-        app.start(ImmutableList.of(localhost));
-
-        File frogs = new File(entity.getAttribute(SoftwareProcess.RUN_DIR), "frogs.txt");
-        try {
-            Assert.assertTrue(frogs.canRead(), "File not readable: " + frogs);
-            String output = Files.toString(frogs, Charsets.UTF_8);
-            Assert.assertTrue(output.contains("Brekekekex"), "File content not found: " + output);
-        } finally {
-            frogs.delete();
-        }
-
-        try {
-            String expectedHostname = BrooklynNetworkUtils.getLocalhostInetAddress().getHostName();
-            String expectedIp = BrooklynNetworkUtils.getLocalhostInetAddress().getHostAddress();
-            
-            Map<?,?> data = (Map) Iterables.getOnlyElement(Yamls.parseAll(Files.toString(template, Charsets.UTF_8)));
-            Assert.assertEquals(data.size(), 3);
-            Assert.assertEquals(data.get("entity.hostname"), expectedHostname);
-            Assert.assertEquals(data.get("entity.address"), expectedIp);
-            Assert.assertEquals(data.get("frogs"), Integer.valueOf(12));
-        } finally {
-            template.delete();
-        }
-    }
-
-    @ImplementedBy(MyServiceImpl.class)
-    public interface MyService extends SoftwareProcess {
-        public SimulatedDriver getDriver();
-    }
-    
-    public static class MyServiceImpl extends SoftwareProcessImpl implements MyService {
-        public MyServiceImpl() {
-        }
-
-        @Override
-        public Class<?> getDriverInterface() {
-            return SimulatedDriver.class;
-        }
-        
-        @Override
-        public SimulatedDriver getDriver() {
-            return (SimulatedDriver) super.getDriver();
-        }
-    }
-
-    public static class SimulatedDriver extends AbstractSoftwareProcessSshDriver {
-        public List<String> events = new ArrayList<String>();
-        private volatile boolean launched = false;
-        
-        public SimulatedDriver(EntityLocal entity, SshMachineLocation machine) {
-            super(entity, machine);
-        }
-
-        @Override
-        public void install() {
-            events.add("install");
-            newScript(INSTALLING)
-                    .failOnNonZeroResultCode()
-                    .body.append("touch myfile")
-                    .execute();
-        }
-        
-        @Override
-        public void customize() {
-            events.add("customize");
-        }
-    
-        @Override
-        public void launch() {
-            events.add("launch");
-            launched = true;
-            entity.setAttribute(Startable.SERVICE_UP, true);
-        }
-        
-        @Override
-        public boolean isRunning() {
-            return launched;
-        }
-    
-        @Override
-        public void stop() {
-            events.add("stop");
-            launched = false;
-            entity.setAttribute(Startable.SERVICE_UP, false);
-        }
-    
-        @Override
-        public void kill() {
-            events.add("kill");
-            launched = false;
-            entity.setAttribute(Startable.SERVICE_UP, false);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessSubclassTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessSubclassTest.java b/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessSubclassTest.java
deleted file mode 100644
index fc006fe..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/SoftwareProcessSubclassTest.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import static org.testng.Assert.assertEquals;
-
-import java.util.Collections;
-import java.util.List;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.effector.core.EffectorAndBody;
-import org.apache.brooklyn.effector.core.MethodEffector;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
-
-
-public class SoftwareProcessSubclassTest extends BrooklynAppUnitTestSupport {
-
-//  NB: These tests don't actually require ssh to localhost -- only that 'localhost' resolves.
-
-    @SuppressWarnings("unused")
-    private static final Logger LOG = LoggerFactory.getLogger(SoftwareProcessSubclassTest.class);
-
-    @ImplementedBy(SubSoftwareProcessImpl.class)
-    public static interface SubSoftwareProcess extends EmptySoftwareProcess {
-        public List<String> getCallHistory();
-        public void triggerStopOutsideOfEffector();
-        public void customRestart();
-    }
-    
-    public static class SubSoftwareProcessImpl extends EmptySoftwareProcessImpl implements SubSoftwareProcess {
-        
-        protected List<String> callHistory = Collections.synchronizedList(Lists.<String>newArrayList());
-
-        @Override
-        public void init() {
-            super.init();
-            getMutableEntityType().addEffector(new EffectorAndBody<Void>(SoftwareProcess.RESTART, new MethodEffector<Void>(SubSoftwareProcess.class, "customRestart").getBody()));
-        }
-        
-        @Override
-        public List<String> getCallHistory() {
-            return callHistory;
-        }
-
-        @Override
-        public void preStart() {
-            callHistory.add("doStart");
-            super.preStart();
-        }
-        
-        @Override
-        public void preStop() {
-            callHistory.add("doStop");
-            super.preStop();
-        }
-        
-        @Override
-        public void customRestart() {
-            callHistory.add("doRestart");
-        }
-        
-        @Override
-        public void triggerStopOutsideOfEffector() {
-            stop();
-        }
-        
-    }
-    
-    private Location loc;
-    private List<Location> locs;
-    private SubSoftwareProcess entity;
-    
-    @BeforeMethod(alwaysRun=true)
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-        loc = mgmt.getLocationRegistry().resolve("localhost");
-        locs = ImmutableList.of(loc);
-        entity = app.createAndManageChild(EntitySpec.create(SubSoftwareProcess.class));
-    }
-
-    @Test
-    public void testStartCalledViaMethod() throws Exception {
-        entity.start(locs);
-        
-        assertCallHistory(ImmutableList.of("doStart"));
-    }
-
-    @Test
-    public void testStopCalledViaMethod() throws Exception {
-        app.start(locs);
-        entity.stop();
-        
-        assertCallHistory(ImmutableList.of("doStart", "doStop"));
-    }
-
-    @Test
-    public void testRestartCalledViaMethod() throws Exception {
-        app.start(locs);
-        entity.restart();
-        
-        assertCallHistory(ImmutableList.of("doStart", "doRestart"));
-    }
-    
-    @Test
-    public void testStopCalledWithoutEffector() throws Exception {
-        app.start(locs);
-        entity.triggerStopOutsideOfEffector();
-        
-        assertCallHistory(ImmutableList.of("doStart", "doStop"));
-    }
-
-    @Test
-    public void testStartCalledViaInvokeEffector() throws Exception {
-        entity.invoke(SubSoftwareProcess.START, ImmutableMap.<String,Object>of("locations", locs)).get();
-        
-        assertCallHistory(ImmutableList.of("doStart"));
-    }
-
-    @Test
-    public void testStopCalledViaInvokeEffector() throws Exception {
-        app.start(locs);
-        entity.invoke(SubSoftwareProcess.STOP, ImmutableMap.<String,Object>of()).get();
-        
-        assertCallHistory(ImmutableList.of("doStart", "doStop"));
-    }
-
-    @Test
-    public void testRestartCalledViaInvokeEffector() throws Exception {
-        app.start(locs);
-        entity.invoke(SubSoftwareProcess.RESTART, ImmutableMap.<String,Object>of()).get();
-        
-        assertCallHistory(ImmutableList.of("doStart", "doRestart"));
-    }
-    
-    private void assertCallHistory(Iterable<String> expected) {
-        List<String> actual = entity.getCallHistory();
-        assertEquals(actual, ImmutableList.copyOf(expected), "actual="+actual);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/VanillaSoftwareProcessAndChildrenIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/VanillaSoftwareProcessAndChildrenIntegrationTest.java b/software/base/src/test/java/brooklyn/entity/basic/VanillaSoftwareProcessAndChildrenIntegrationTest.java
deleted file mode 100644
index 1179cfc..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/VanillaSoftwareProcessAndChildrenIntegrationTest.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import java.util.Collections;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.core.ResourceUtils;
-import org.apache.brooklyn.util.javalang.JavaClassNames;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess.ChildStartableMode;
-
-import com.google.common.base.Stopwatch;
-
-public class VanillaSoftwareProcessAndChildrenIntegrationTest {
-
-    // TODO Why are these tests so slow? Even when the sleep time was 3 seconds instead of 10, they would still take about 10 seconds.
-    
-    // Note that tests run by jenkins can be extremely time-sensitive.
-    // e.g. http://brooklyn.builds.cloudsoftcorp.com/job/Brooklyn-Master-Integration/io.brooklyn$brooklyn-software-base/217/testReport/junit/brooklyn.entity.basic/VanillaSoftwareProcessAndChildrenIntegrationTest/testModeBackground/
-    //      shows a 5 second difference when in background mode, whereas the test originally asserted a difference of <= 1.
-    // Therefore increasing time that tests will take, but decreasing the sensitivity so we don't get such false-negatives.
-    
-    private static final Logger log = LoggerFactory.getLogger(VanillaSoftwareProcessAndChildrenIntegrationTest.class);
-
-    private static final int PARENT_TASK_SLEEP_LENGTH_SECS = 10;
-    private static final int CHILD_TASK_SLEEP_LENGTH_SECS = 10;
-    private static final int CONCURRENT_MAX_ACCEPTABLE_DIFF_SECS = PARENT_TASK_SLEEP_LENGTH_SECS - 1;
-    private static final int SEQUENTIAL_MIN_ACCEPTABLE_DIFF_SECS = PARENT_TASK_SLEEP_LENGTH_SECS - 1;
-    private static final int EARLY_RETURN_GRACE_MS = 20;
-    
-    private TestApplication app;
-    private Location localhost;
-
-    private VanillaSoftwareProcess p1;
-    private VanillaSoftwareProcess p2;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setup() {
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        localhost = app.getManagementContext().getLocationRegistry().resolve("localhost");
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void shutdown() {
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-    }
-
-    @Test(groups = "Integration")
-    public void testModeNone() {
-        prep(ChildStartableMode.NONE);
-        long startTime = startApp();
-
-        Assert.assertNotNull(p1.getAttribute(SoftwareProcess.RUN_DIR));
-        Assert.assertNull(p2.getAttribute(SoftwareProcess.RUN_DIR));
-        Assert.assertTrue(startTime >= PARENT_TASK_SLEEP_LENGTH_SECS*1000 - EARLY_RETURN_GRACE_MS, "startTime="+Time.makeTimeStringRounded(startTime));
-    }
-
-    @Test(groups = "Integration")
-    public void testModeForeground() {
-        prep(ChildStartableMode.FOREGROUND);        
-        long startTime = startApp();
-
-        long timediff = timediff();
-        Assert.assertTrue( Math.abs(timediff) <= CONCURRENT_MAX_ACCEPTABLE_DIFF_SECS, "should have started concurrently, not with time difference "+timediff+" ("+p1+", "+p2+")" );
-        Assert.assertTrue(startTime >= PARENT_TASK_SLEEP_LENGTH_SECS*1000 - EARLY_RETURN_GRACE_MS, "startTime="+Time.makeTimeStringRounded(startTime));
-    }
-
-    @Test(groups = "Integration")
-    public void testModeForegroundLate() {
-        prep(ChildStartableMode.FOREGROUND_LATE);        
-        long startTime = startApp();
-
-        long timediff = timediff();
-        Assert.assertTrue( timediff >= SEQUENTIAL_MIN_ACCEPTABLE_DIFF_SECS, "should have started later, not with time difference "+timediff+" ("+p1+", "+p2+")" );
-        Assert.assertTrue(startTime >= 2*PARENT_TASK_SLEEP_LENGTH_SECS*1000 - EARLY_RETURN_GRACE_MS, "startTime="+Time.makeTimeStringRounded(startTime));
-    }
-
-    @Test(groups = "Integration")
-    public void testModeBackground() {
-        prep(ChildStartableMode.BACKGROUND);
-        long startTime = startApp();
-
-        checkChildComesUpSoon();
-        
-        long timediff = timediff();
-        Assert.assertTrue( Math.abs(timediff) <= CONCURRENT_MAX_ACCEPTABLE_DIFF_SECS, "should have started concurrently, not with time difference "+timediff+" ("+p1+", "+p2+")" );
-        Assert.assertTrue(startTime >= PARENT_TASK_SLEEP_LENGTH_SECS*1000 - EARLY_RETURN_GRACE_MS, "startTime="+Time.makeTimeStringRounded(startTime));
-    }
-
-    @Test(groups = "Integration")
-    public void testModeBackgroundLate() {
-        prep(ChildStartableMode.BACKGROUND_LATE);
-        long startTime = startApp();
-
-        checkChildNotUpYet();
-        checkChildComesUpSoon();
-        
-        long timediff = timediff();
-        Assert.assertTrue( Math.abs(timediff) >= SEQUENTIAL_MIN_ACCEPTABLE_DIFF_SECS, "should have started later, not with time difference "+timediff+" ("+p1+", "+p2+")" );
-        Assert.assertTrue(startTime >= PARENT_TASK_SLEEP_LENGTH_SECS*1000 - EARLY_RETURN_GRACE_MS, "startTime="+Time.makeTimeStringRounded(startTime));
-        
-        // just to prevent warnings
-        waitForBackgroundedTasks(CHILD_TASK_SLEEP_LENGTH_SECS+1);
-        app.stop();
-        app = null;
-    }
-    
-    private long startApp() {
-        Stopwatch stopwatch = Stopwatch.createStarted();
-        app.start(Collections.singleton(localhost));
-        long result = stopwatch.elapsed(TimeUnit.MILLISECONDS);
-        log.info("Took "+Time.makeTimeStringRounded(result)+" for app.start to complete");
-        return result;
-    }
-
-    private void waitForBackgroundedTasks(int secs) {
-        // child task is backgrounded; quick and dirty way to make sure it finishes (after setting service_up)
-        Time.sleep(Duration.seconds(secs));
-    }
-
-    private void checkChildNotUpYet() {
-        Assert.assertFalse(p2.getAttribute(SoftwareProcess.SERVICE_UP));
-    }
-
-    private void checkChildComesUpSoon() {
-        Stopwatch stopwatch = Stopwatch.createStarted();
-        EntityTestUtils.assertAttributeEqualsEventually(p2, Attributes.SERVICE_UP, true);
-        log.info("Took "+Time.makeTimeStringRounded(stopwatch)+" for child-process to be service-up");
-    }
-
-    private long timediff() {
-        Long d1 = getRunTimeUtc(p1);
-        Long d2 = getRunTimeUtc(p2);
-
-        log.info("timestamps for "+JavaClassNames.callerNiceClassAndMethod(1)+" have difference "+(d2-d1));
-
-        return d2 - d1;
-    }
-
-    private Long getRunTimeUtc(VanillaSoftwareProcess p) {
-        Assert.assertNotNull(p.getAttribute(SoftwareProcess.RUN_DIR));
-        return Long.parseLong( Strings.getFirstWordAfter(new ResourceUtils(this).getResourceAsString(Os.mergePaths(p.getAttribute(SoftwareProcess.RUN_DIR), "DATE")), "utc") );
-    }
-    
-    private void prep(ChildStartableMode mode) {
-        String parentCmd = "echo utc `date +%s` > DATE ; echo human `date` >> DATE ; "
-            + "{ nohup sleep 60 & } ; echo $! > $PID_FILE ; sleep "+PARENT_TASK_SLEEP_LENGTH_SECS;
-        
-        String childCmd = "echo utc `date +%s` > DATE ; echo human `date` >> DATE ; "
-                + "{ nohup sleep 60 & } ; echo $! > $PID_FILE ; sleep "+CHILD_TASK_SLEEP_LENGTH_SECS;
-        
-        p1 = app.createAndManageChild(EntitySpec.create(VanillaSoftwareProcess.class)
-            .configure(VanillaSoftwareProcess.LAUNCH_COMMAND, parentCmd)
-            .configure(VanillaSoftwareProcess.CHILDREN_STARTABLE_MODE, mode)
-            );
-        p2 = p1.addChild(EntitySpec.create(VanillaSoftwareProcess.class)
-            .configure(VanillaSoftwareProcess.LAUNCH_COMMAND, childCmd));
-        Entities.manage(p2);
-        
-        log.info("testing "+JavaClassNames.callerNiceClassAndMethod(1)+", using "+p1+" and "+p2);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/lifecycle/MyEntity.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/MyEntity.java b/software/base/src/test/java/brooklyn/entity/basic/lifecycle/MyEntity.java
deleted file mode 100644
index a582b15..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/MyEntity.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic.lifecycle;
-
-import org.apache.brooklyn.api.entity.ImplementedBy;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
-@ImplementedBy(MyEntityImpl.class)
-public interface MyEntity extends SoftwareProcess {
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/lifecycle/MyEntityApp.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/MyEntityApp.java b/software/base/src/test/java/brooklyn/entity/basic/lifecycle/MyEntityApp.java
deleted file mode 100644
index 632489f..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/MyEntityApp.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic.lifecycle;
-
-public class MyEntityApp {
-    public static void main(String[] args) throws InterruptedException {
-        System.out.println("Properties: "+System.getProperties());
-        Thread.sleep(60*60*1000);
-    }
-}



[44/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/AbstractJcloudsSubnetSshMachineLocation.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/AbstractJcloudsSubnetSshMachineLocation.java b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/AbstractJcloudsSubnetSshMachineLocation.java
index c21810d..d4e8615 100644
--- a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/AbstractJcloudsSubnetSshMachineLocation.java
+++ b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/AbstractJcloudsSubnetSshMachineLocation.java
@@ -21,8 +21,7 @@ package org.apache.brooklyn.location.jclouds;
 import java.util.Map;
 
 import org.jclouds.compute.domain.NodeMetadata;
-
-import org.apache.brooklyn.location.basic.SupportsPortForwarding.RequiresPortForwarding;
+import org.apache.brooklyn.location.core.SupportsPortForwarding.RequiresPortForwarding;
 
 public abstract class AbstractJcloudsSubnetSshMachineLocation extends JcloudsSshMachineLocation implements RequiresPortForwarding {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/BrooklynMachinePool.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/BrooklynMachinePool.java b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/BrooklynMachinePool.java
index f52ad0d..dc61807 100644
--- a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/BrooklynMachinePool.java
+++ b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/BrooklynMachinePool.java
@@ -32,10 +32,10 @@ import org.apache.brooklyn.entity.trait.Startable;
 import org.jclouds.compute.domain.NodeMetadata;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.location.jclouds.pool.MachinePool;
 import org.apache.brooklyn.location.jclouds.pool.MachineSet;
 import org.apache.brooklyn.location.jclouds.pool.ReusableMachineTemplate;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.task.BasicExecutionContext;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolver.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolver.java b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolver.java
index 5059a0a..1773470 100644
--- a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolver.java
+++ b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolver.java
@@ -32,12 +32,12 @@ import org.apache.brooklyn.api.location.NoMachinesAvailableException;
 import org.apache.brooklyn.api.mgmt.ManagementContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.BasicLocationRegistry;
-import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
-import org.apache.brooklyn.location.basic.LocationConfigUtils;
-import org.apache.brooklyn.location.basic.LocationInternal;
-import org.apache.brooklyn.location.basic.LocationPropertiesFromBrooklynProperties;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.core.BasicLocationRegistry;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.apache.brooklyn.location.core.LocationConfigUtils;
+import org.apache.brooklyn.location.core.LocationPropertiesFromBrooklynProperties;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 import org.apache.brooklyn.util.exceptions.Exceptions;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsLocation.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsLocation.java b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsLocation.java
index 3d91644..c2f1a28 100644
--- a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsLocation.java
+++ b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsLocation.java
@@ -61,10 +61,10 @@ import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.config.ConfigKey.HasConfigKey;
 import org.apache.brooklyn.core.config.ConfigUtils;
 import org.apache.brooklyn.core.config.Sanitizer;
-import org.apache.brooklyn.core.mgmt.rebind.persister.LocationWithObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.LocationWithObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.jclouds.JcloudsBlobStoreBasedObjectStore;
 import org.apache.brooklyn.location.access.PortMapping;
-import org.apache.brooklyn.location.basic.AbstractLocation;
 import org.apache.brooklyn.location.cloud.AbstractCloudMachineProvisioningLocation;
 import org.apache.brooklyn.location.cloud.names.AbstractCloudMachineNamer;
 import org.apache.brooklyn.location.jclouds.networking.JcloudsPortForwarderExtension;
@@ -132,19 +132,18 @@ import com.google.common.io.Files;
 import com.google.common.net.HostAndPort;
 import com.google.common.primitives.Ints;
 
-import brooklyn.entity.rebind.persister.jclouds.JcloudsBlobStoreBasedObjectStore;
-
 import org.apache.brooklyn.location.access.PortForwardManager;
-import org.apache.brooklyn.location.basic.BasicMachineMetadata;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
-import org.apache.brooklyn.location.basic.LocationConfigUtils;
-import org.apache.brooklyn.location.basic.LocationConfigUtils.OsCredential;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.location.basic.WinRmMachineLocation;
 import org.apache.brooklyn.location.cloud.AvailabilityZoneExtension;
 import org.apache.brooklyn.location.cloud.names.CloudMachineNamer;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.location.core.BasicMachineMetadata;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.apache.brooklyn.location.core.LocationConfigUtils;
+import org.apache.brooklyn.location.core.LocationConfigUtils.OsCredential;
 import org.apache.brooklyn.location.jclouds.JcloudsPredicates.NodeInLocation;
 import org.apache.brooklyn.location.jclouds.templates.PortableTemplateBuilder;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.location.winrm.WinRmMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.collections.MutableSet;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsLocationConfig.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsLocationConfig.java b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsLocationConfig.java
index 03d4432..dd52b75 100644
--- a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsLocationConfig.java
+++ b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsLocationConfig.java
@@ -34,8 +34,8 @@ import org.jclouds.compute.domain.TemplateBuilder;
 import org.jclouds.domain.LoginCredentials;
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
 import org.apache.brooklyn.location.access.PortForwardManager;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
 import org.apache.brooklyn.location.cloud.CloudLocationConfig;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
 import org.apache.brooklyn.util.core.internal.ssh.SshTool;
 
 import com.google.common.annotations.Beta;
@@ -204,7 +204,7 @@ public interface JcloudsLocationConfig extends CloudLocationConfig {
 
     /**
      * CUSTOM_MACHINE_SETUP_SCRIPT_URL accepts a URL location that points to a shell script. 
-     * Please have a look at locations/jclouds/src/main/resources/sample/script/setup-server.sh as an example
+     * Please have a look at locations/jclouds/src/main/resources/org/apache/brooklyn/location/jclouds/sample/setup-server.sh as an example
      */
     public static final ConfigKey<String> CUSTOM_MACHINE_SETUP_SCRIPT_URL = ConfigKeys.newStringConfigKey(
             "setup.script", "Custom script to customize a node");

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsLocationResolver.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsLocationResolver.java b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsLocationResolver.java
index ebb5d57..60ce84f 100644
--- a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsLocationResolver.java
+++ b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsLocationResolver.java
@@ -29,16 +29,16 @@ import org.apache.brooklyn.api.location.LocationRegistry;
 import org.apache.brooklyn.api.location.LocationResolver;
 import org.apache.brooklyn.api.location.LocationSpec;
 import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
-import org.apache.brooklyn.location.basic.LocationConfigUtils;
-import org.apache.brooklyn.location.basic.LocationInternal;
 import org.jclouds.apis.ApiMetadata;
 import org.jclouds.apis.Apis;
 import org.jclouds.providers.ProviderMetadata;
 import org.jclouds.providers.Providers;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.BasicLocationRegistry;
+import org.apache.brooklyn.location.core.BasicLocationRegistry;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.apache.brooklyn.location.core.LocationConfigUtils;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 import org.apache.brooklyn.util.text.Strings;
 
 import com.google.common.collect.ImmutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsMachineLocation.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsMachineLocation.java b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsMachineLocation.java
index 11d20ef..90b4db8 100644
--- a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsMachineLocation.java
+++ b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsMachineLocation.java
@@ -19,7 +19,7 @@
 package org.apache.brooklyn.location.jclouds;
 
 import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.location.basic.HasSubnetHostname;
+import org.apache.brooklyn.location.core.HasSubnetHostname;
 import org.jclouds.compute.domain.NodeMetadata;
 import org.jclouds.compute.domain.Template;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsPropertiesFromBrooklynProperties.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsPropertiesFromBrooklynProperties.java b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsPropertiesFromBrooklynProperties.java
index 8b2356b..6086d08 100644
--- a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsPropertiesFromBrooklynProperties.java
+++ b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsPropertiesFromBrooklynProperties.java
@@ -21,11 +21,11 @@ package org.apache.brooklyn.location.jclouds;
 import java.util.Map;
 
 import org.apache.brooklyn.core.config.ConfigUtils;
-import org.apache.brooklyn.location.basic.DeprecatedKeysMappingBuilder;
-import org.apache.brooklyn.location.basic.LocationPropertiesFromBrooklynProperties;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
+import org.apache.brooklyn.location.core.DeprecatedKeysMappingBuilder;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.apache.brooklyn.location.core.LocationPropertiesFromBrooklynProperties;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 import org.apache.brooklyn.util.javalang.JavaClassNames;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsSshMachineLocation.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsSshMachineLocation.java b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsSshMachineLocation.java
index f315f42..31b414b 100644
--- a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsSshMachineLocation.java
+++ b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsSshMachineLocation.java
@@ -34,10 +34,10 @@ import javax.annotation.Nullable;
 import org.apache.brooklyn.api.location.HardwareDetails;
 import org.apache.brooklyn.api.location.MachineDetails;
 import org.apache.brooklyn.api.location.OsDetails;
-import org.apache.brooklyn.location.basic.BasicHardwareDetails;
-import org.apache.brooklyn.location.basic.BasicMachineDetails;
-import org.apache.brooklyn.location.basic.BasicOsDetails;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.BasicHardwareDetails;
+import org.apache.brooklyn.location.core.BasicMachineDetails;
+import org.apache.brooklyn.location.core.BasicOsDetails;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsWinRmMachineLocation.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsWinRmMachineLocation.java b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsWinRmMachineLocation.java
index b59ce3e..7b84432 100644
--- a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsWinRmMachineLocation.java
+++ b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsWinRmMachineLocation.java
@@ -25,7 +25,7 @@ import java.net.UnknownHostException;
 import java.util.Iterator;
 import java.util.Set;
 
-import org.apache.brooklyn.location.basic.WinRmMachineLocation;
+import org.apache.brooklyn.location.winrm.WinRmMachineLocation;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 import org.apache.brooklyn.util.net.Networking;
 import org.jclouds.compute.domain.NodeMetadata;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/SudoTtyFixingCustomizer.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/SudoTtyFixingCustomizer.java b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/SudoTtyFixingCustomizer.java
index f295790..2552874 100644
--- a/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/SudoTtyFixingCustomizer.java
+++ b/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/SudoTtyFixingCustomizer.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.location.jclouds;
 
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.task.DynamicTasks;
 import org.apache.brooklyn.util.core.task.ssh.SshTasks;
 import org.apache.brooklyn.util.core.task.ssh.SshTasks.OnFailingTask;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/org/apache/brooklyn/policy/jclouds/os/CreateUserPolicy.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/org/apache/brooklyn/policy/jclouds/os/CreateUserPolicy.java b/locations/jclouds/src/main/java/org/apache/brooklyn/policy/jclouds/os/CreateUserPolicy.java
new file mode 100644
index 0000000..805f1d6
--- /dev/null
+++ b/locations/jclouds/src/main/java/org/apache/brooklyn/policy/jclouds/os/CreateUserPolicy.java
@@ -0,0 +1,173 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.policy.jclouds.os;
+
+import java.util.List;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.api.sensor.SensorEvent;
+import org.apache.brooklyn.api.sensor.SensorEventListener;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.core.AbstractEntity;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.policy.core.AbstractPolicy;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+import org.apache.brooklyn.util.core.internal.ssh.SshTool;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.jclouds.compute.config.AdminAccessConfiguration;
+import org.jclouds.scriptbuilder.functions.InitAdminAccess;
+import org.jclouds.scriptbuilder.statements.login.AdminAccess;
+import org.jclouds.scriptbuilder.statements.ssh.SshdConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.annotations.Beta;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+/**
+ * When attached to an entity, this will monitor for when an {@link SshMachineLocation} is added to that entity
+ * (e.g. when a VM has been provisioned for it).
+ * 
+ * The policy will then (asynchronously) add a new user to the VM, with a randomly generated password.
+ * The ssh details will be set as a sensor on the entity.
+ * 
+ * If this is used, it is strongly encouraged to tell users to change the password on first login.
+ * 
+ * A preferred mechanism would be for an external key-management tool to generate ssh key-pairs for
+ * the user, and for the public key to be passed to Brooklyn. However, there is not a customer 
+ * requirement for that yet, so focusing on the password-approach.
+ */
+@Beta
+public class CreateUserPolicy extends AbstractPolicy implements SensorEventListener<Location> {
+
+    // TODO Should add support for authorizing ssh keys as well
+    
+    // TODO Should review duplication with:
+    //  - JcloudsLocationConfig.GRANT_USER_SUDO
+    //    (but config default/description and context of use are different)
+    //  - AdminAccess in JcloudsLocation.createUserStatements
+    
+    // TODO Could make the password explicitly configurable, or auto-generate if not set?
+    
+    private static final Logger LOG = LoggerFactory.getLogger(CreateUserPolicy.class);
+
+    @SetFromFlag("user")
+    public static final ConfigKey<String> VM_USERNAME = ConfigKeys.newStringConfigKey("createuser.vm.user.name");
+
+    @SetFromFlag("grantSudo")
+    public static final ConfigKey<Boolean> GRANT_SUDO = ConfigKeys.newBooleanConfigKey(
+            "createuser.vm.user.grantSudo",
+            "Whether to give the new user sudo rights",
+            false);
+
+    public static final AttributeSensor<String> VM_USER_CREDENTIALS = Sensors.newStringSensor(
+            "createuser.vm.user.credentials",
+            "The \"<user> : <password> @ <hostname>:<port>\"");
+
+    public void setEntity(EntityLocal entity) {
+        super.setEntity(entity);
+        subscribe(entity, AbstractEntity.LOCATION_ADDED, this);
+    }
+
+    @Override
+    public void onEvent(SensorEvent<Location> event) {
+        final Entity entity = event.getSource();
+        final Location loc = event.getValue();
+        if (loc instanceof SshMachineLocation) {
+            addUserAsync(entity, (SshMachineLocation)loc);
+        }
+    }
+
+    protected void addUserAsync(final Entity entity, final SshMachineLocation machine) {
+        ((EntityInternal)entity).getExecutionContext().execute(new Runnable() {
+            public void run() {
+                addUser(entity, machine);
+            }});
+    }
+    
+    protected void addUser(Entity entity, SshMachineLocation machine) {
+        boolean grantSudo = getRequiredConfig(GRANT_SUDO);
+        String user = getRequiredConfig(VM_USERNAME);
+        String password = Identifiers.makeRandomId(12);
+        String hostname = machine.getAddress().getHostName();
+        int port = machine.getPort();
+        String creds = user + " : " + password + " @ " +hostname + ":" + port;
+        
+        LOG.info("Adding auto-generated user "+user+" @ "+hostname+":"+port);
+        
+        // Build the command to create the user
+        // Note AdminAccess requires _all_ fields set, due to http://code.google.com/p/jclouds/issues/detail?id=1095
+        // If jclouds grants Sudo rights, it overwrites the /etc/sudoers, which makes integration tests very dangerous! Not using it.
+        AdminAccess adminAccess = AdminAccess.builder()
+                .adminUsername(user)
+                .adminPassword(password)
+                .grantSudoToAdminUser(false)
+                .resetLoginPassword(true)
+                .loginPassword(password)
+                .authorizeAdminPublicKey(false)
+                .adminPublicKey("ignored")
+                .installAdminPrivateKey(false)
+                .adminPrivateKey("ignore")
+                .lockSsh(false)
+                .build();
+        
+        org.jclouds.scriptbuilder.domain.OsFamily scriptOsFamily = (machine.getMachineDetails().getOsDetails().isWindows()) 
+                ? org.jclouds.scriptbuilder.domain.OsFamily.WINDOWS
+                : org.jclouds.scriptbuilder.domain.OsFamily.UNIX;
+        
+        InitAdminAccess initAdminAccess = new InitAdminAccess(new AdminAccessConfiguration.Default());
+        initAdminAccess.visit(adminAccess);
+        String cmd = adminAccess.render(scriptOsFamily);
+
+        // Exec command to create the user
+        int result = machine.execScript(ImmutableMap.of(SshTool.PROP_RUN_AS_ROOT.getName(), true), "create-user-"+user, ImmutableList.of(cmd));
+        if (result != 0) {
+            throw new IllegalStateException("Failed to auto-generate user, using command "+cmd);
+        }
+
+        // Exec command to grant password-access to sshd (which may have been disabled earlier).
+        cmd = new SshdConfig(ImmutableMap.of("PasswordAuthentication", "yes")).render(scriptOsFamily);
+        result = machine.execScript(ImmutableMap.of(SshTool.PROP_RUN_AS_ROOT.getName(), true), "create-user-"+user, ImmutableList.of(cmd));
+        if (result != 0) {
+            throw new IllegalStateException("Failed to enable ssh-login-with-password, using command "+cmd);
+        }
+
+        // Exec command to grant sudo rights.
+        if (grantSudo) {
+            List<String> cmds = ImmutableList.of(
+                    "cat >> /etc/sudoers <<-'END_OF_JCLOUDS_FILE'\n"+
+                            user+" ALL = (ALL) NOPASSWD:ALL\n"+
+                            "END_OF_JCLOUDS_FILE\n",
+                    "chmod 0440 /etc/sudoers");
+            result = machine.execScript(ImmutableMap.of(SshTool.PROP_RUN_AS_ROOT.getName(), true), "add-user-to-sudoers-"+user, cmds);
+            if (result != 0) {
+                throw new IllegalStateException("Failed to auto-generate user, using command "+cmd);
+            }
+        }
+        
+        ((EntityLocal)entity).setAttribute(VM_USER_CREDENTIALS, creds);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/resources/org/apache/brooklyn/location/jclouds/sample/setup-server.sh
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/resources/org/apache/brooklyn/location/jclouds/sample/setup-server.sh b/locations/jclouds/src/main/resources/org/apache/brooklyn/location/jclouds/sample/setup-server.sh
new file mode 100755
index 0000000..cdb5dcc
--- /dev/null
+++ b/locations/jclouds/src/main/resources/org/apache/brooklyn/location/jclouds/sample/setup-server.sh
@@ -0,0 +1,31 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#  http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+echo Appending nameserver 8.8.8.8 to /etc/resolv.conf
+sudo -s -- '/bin/echo nameserver 8.8.8.8 >> /etc/resolv.conf'
+unset OS
+OS=`head -1 /etc/issue | awk '{ print $1 }'`
+unset OS_MAJOR
+OS_MAJOR=`head -1 /etc/issue | awk '{ print $4 }' | cut -d'.' -f1`
+if [ $OS = "CentOS" -a $OS_MAJOR -eq 6 ]; then
+    echo Appending options single-request-reopen to /etc/resolv.conf
+    sudo -s -- '/bin/echo options single-request-reopen >> /etc/resolv.conf'
+fi
+echo Changing default gateway to ${defaultGateway}
+sudo -s -- '/sbin/ip route replace default via ${defaultGateway} dev eth0'

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/resources/sample/script/setup-server.sh
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/resources/sample/script/setup-server.sh b/locations/jclouds/src/main/resources/sample/script/setup-server.sh
deleted file mode 100755
index cdb5dcc..0000000
--- a/locations/jclouds/src/main/resources/sample/script/setup-server.sh
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/usr/bin/env bash
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#  http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied.  See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-echo Appending nameserver 8.8.8.8 to /etc/resolv.conf
-sudo -s -- '/bin/echo nameserver 8.8.8.8 >> /etc/resolv.conf'
-unset OS
-OS=`head -1 /etc/issue | awk '{ print $1 }'`
-unset OS_MAJOR
-OS_MAJOR=`head -1 /etc/issue | awk '{ print $4 }' | cut -d'.' -f1`
-if [ $OS = "CentOS" -a $OS_MAJOR -eq 6 ]; then
-    echo Appending options single-request-reopen to /etc/resolv.conf
-    sudo -s -- '/bin/echo options single-request-reopen >> /etc/resolv.conf'
-fi
-echo Changing default gateway to ${defaultGateway}
-sudo -s -- '/sbin/ip route replace default via ${defaultGateway} dev eth0'

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BlobStoreCleaner.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BlobStoreCleaner.java b/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BlobStoreCleaner.java
deleted file mode 100644
index 4b40176..0000000
--- a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BlobStoreCleaner.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.rebind.persister.jclouds;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import org.jclouds.ContextBuilder;
-import org.jclouds.blobstore.BlobStoreContext;
-import org.jclouds.blobstore.domain.PageSet;
-import org.jclouds.blobstore.domain.StorageMetadata;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
-import org.apache.brooklyn.location.cloud.CloudLocationConfig;
-import org.apache.brooklyn.location.jclouds.JcloudsLocation;
-
-/** Utility for cleaning up after test leaks. Most should not leak of course, but if they do... */
-public class BlobStoreCleaner {
-
-    private static String locationSpec = BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC;
-
-    private static final Logger log = LoggerFactory.getLogger(BlobStoreCleaner.class);
-    
-    public static void main(String[] args) {
-        LocalManagementContextForTests mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault()); 
-        JcloudsLocation location = (JcloudsLocation) mgmt.getLocationRegistry().resolve(locationSpec);
-            
-        String identity = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_IDENTITY), "identity must not be null");
-        String credential = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_CREDENTIAL), "credential must not be null");
-        String provider = checkNotNull(location.getConfig(LocationConfigKeys.CLOUD_PROVIDER), "provider must not be null");
-        String endpoint = location.getConfig(CloudLocationConfig.CLOUD_ENDPOINT);
-
-        BlobStoreContext context = ContextBuilder.newBuilder(provider)
-                .credentials(identity, credential)
-                .endpoint(endpoint)
-                .buildView(BlobStoreContext.class);
-        
-        PageSet<? extends StorageMetadata> containers = context.getBlobStore().list();
-        for (StorageMetadata container: containers) {
-            if (container.getName().matches("brooklyn.*-test.*")
-                // to kill all containers here
-//                || container.getName().matches(".*")
-                ) {
-                log.info("killing - "+container.getName());
-                context.getBlobStore().deleteContainer(container.getName());
-            } else {
-                log.info("KEEPING - "+container.getName());
-            }
-        }
-        context.close();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BlobStoreExpiryTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BlobStoreExpiryTest.java b/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BlobStoreExpiryTest.java
deleted file mode 100644
index b3877dc..0000000
--- a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BlobStoreExpiryTest.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.rebind.persister.jclouds;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import static org.jclouds.openstack.reference.AuthHeaders.URL_SUFFIX;
-
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.util.List;
-import java.util.Map.Entry;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.http.HttpTool;
-import org.apache.brooklyn.util.core.http.HttpToolResponse;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-import org.apache.http.client.HttpClient;
-import org.jclouds.blobstore.BlobStoreContext;
-import org.jclouds.blobstore.domain.PageSet;
-import org.jclouds.blobstore.domain.StorageMetadata;
-import org.jclouds.domain.Credentials;
-import org.jclouds.openstack.domain.AuthenticationResponse;
-import org.jclouds.openstack.reference.AuthHeaders;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
-import org.apache.brooklyn.location.cloud.CloudLocationConfig;
-import org.apache.brooklyn.location.jclouds.JcloudsLocation;
-import org.apache.brooklyn.location.jclouds.JcloudsUtil;
-
-import com.google.common.base.Preconditions;
-import com.google.common.cache.LoadingCache;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableMap.Builder;
-import com.google.inject.Inject;
-
-@Test(groups={"Live", "Live-sanity"})
-public class BlobStoreExpiryTest {
-
-    private static final Logger log = LoggerFactory.getLogger(BlobStoreExpiryTest.class);
-    
-    /**
-     * Live tests as written require a location defined as follows:
-     * 
-     * <code>
-     * brooklyn.location.named.brooklyn-jclouds-objstore-test-1==jclouds:swift:https://ams01.objectstorage.softlayer.net/auth/v1.0
-     * brooklyn.location.named.brooklyn-jclouds-objstore-test-1.identity=IBMOS1234-5:yourname
-     * brooklyn.location.named.brooklyn-jclouds-objstore-test-1.credential=0123abcd.......
-     * </code>
-     */
-    
-    public static final String PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC = BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC;
-    public static final String CONTAINER_PREFIX = "brooklyn-persistence-test";
-    private String locationSpec = PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC;
-    
-    private JcloudsLocation location;
-    private BlobStoreContext context;
-
-    private ManagementContext mgmt;
-    private String testContainerName;
-
-    private String identity;
-    private String credential;
-    private String provider;
-    private String endpoint;
-
-    public synchronized BlobStoreContext getSwiftBlobStoreContext() {
-        if (context==null) {
-            if (location==null) {
-                Preconditions.checkNotNull(locationSpec, "locationSpec required for remote object store when location is null");
-                Preconditions.checkNotNull(mgmt, "mgmt required for remote object store when location is null");
-                location = (JcloudsLocation) mgmt.getLocationRegistry().resolve(locationSpec);
-            }
-            
-            identity = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_IDENTITY), "identity must not be null");
-            credential = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_CREDENTIAL), "credential must not be null");
-            provider = checkNotNull(location.getConfig(LocationConfigKeys.CLOUD_PROVIDER), "provider must not be null");
-            endpoint = location.getConfig(CloudLocationConfig.CLOUD_ENDPOINT);
-
-            context = JcloudsUtil.newBlobstoreContext(provider, endpoint, identity, credential);
-        }
-        return context;
-    }
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setup() {
-        testContainerName = CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(8);
-        mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void teardown() {
-        Entities.destroyAll(mgmt);
-        if (context!=null) context.close();
-        context = null;
-    }
-
-    public void testRenewAuthSucceedsInSwiftObjectStore() throws Exception {
-        doTestRenewAuth();
-    }
-    
-    protected void doTestRenewAuth() throws Exception {
-        getSwiftBlobStoreContext();
-        
-        injectShortLivedTokenForSwiftAuth();
-        
-        context.getBlobStore().createContainerInLocation(null, testContainerName);
-        
-        assertContainerFound();
-        
-        log.info("created container, now sleeping for expiration");
-        
-        Time.sleep(Duration.TEN_SECONDS);
-        
-        assertContainerFound();
-
-        context.getBlobStore().deleteContainer(testContainerName);
-    }
-
-    private void assertContainerFound() {
-        PageSet<? extends StorageMetadata> ps = context.getBlobStore().list();
-        BlobStoreTest.assertHasItemNamed(ps, testContainerName);
-    }
-
-    private void injectShortLivedTokenForSwiftAuth() throws Exception {
-        URL endpointUrl = new URL(endpoint);
-
-        HttpToolResponse tokenHttpResponse1 = requestTokenWithExplicitLifetime(endpointUrl,
-            identity, credential, Duration.FIVE_SECONDS);
-        
-        Builder<String, URI> servicesMapBuilder = ImmutableMap.builder();
-        for (Entry<String, List<String>> entry : tokenHttpResponse1.getHeaderLists().entrySet()) {
-            if (entry.getKey().toLowerCase().endsWith(URL_SUFFIX.toLowerCase()) ||
-                    entry.getKey().toLowerCase().endsWith("X-Auth-Token-Expires".toLowerCase())){
-                servicesMapBuilder.put(entry.getKey(), URI.create(entry.getValue().iterator().next()));
-            }
-        }
-        AuthenticationResponse authResponse = new AuthenticationResponse(tokenHttpResponse1.getHeaderLists().get(AuthHeaders.AUTH_TOKEN).get(0), servicesMapBuilder.build());
-
-        getAuthCache().put(new Credentials(identity, credential), authResponse);
-    }
-
-    private LoadingCache<Credentials, AuthenticationResponse> getAuthCache() {
-        return context.utils().injector().getInstance(CachePeeker.class).authenticationResponseCache;
-    }
-    
-    public static class CachePeeker {
-        private final LoadingCache<Credentials, AuthenticationResponse> authenticationResponseCache;
-
-        @Inject
-        protected CachePeeker(LoadingCache<Credentials, AuthenticationResponse> authenticationResponseCache) {
-           this.authenticationResponseCache = authenticationResponseCache;
-        }
-    }
-    
-    public static HttpToolResponse requestTokenWithExplicitLifetime(URL url, String user, String key, Duration expiration) throws URISyntaxException {
-        HttpClient client = HttpTool.httpClientBuilder().build();
-        HttpToolResponse response = HttpTool.httpGet(client, url.toURI(), MutableMap.<String,String>of()
-            .add(AuthHeaders.AUTH_USER, user)
-            .add(AuthHeaders.AUTH_KEY, key)
-            .add("Host", url.getHost())
-            .add("X-Auth-New-Token", "" + true)
-            .add("X-Auth-Token-Lifetime", "" + expiration.toSeconds())
-            );
-//        curl -v https://ams01.objectstorage.softlayer.net/auth/v1.0/v1.0 -H "X-Auth-User: IBMOS12345-2:username" -H "X-Auth-Key: <API KEY>" -H "Host: ams01.objectstorage.softlayer.net" -H "X-Auth-New-Token: true" -H "X-Auth-Token-Lifetime: 15"
-        log.info("Requested token with explicit lifetime: "+expiration+" at "+url+"\n"+response+"\n"+response.getHeaderLists());
-        return response;
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BlobStorePersistencePerformanceTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BlobStorePersistencePerformanceTest.java b/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BlobStorePersistencePerformanceTest.java
deleted file mode 100644
index acd5775..0000000
--- a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BlobStorePersistencePerformanceTest.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
-*/
-package brooklyn.entity.rebind.persister.jclouds;
-
-import java.util.List;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore.StoreObjectAccessor;
-import org.apache.brooklyn.core.test.qa.performance.AbstractPerformanceTest;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-
-public class BlobStorePersistencePerformanceTest extends AbstractPerformanceTest {
-
-    public static final String LOCATION_SPEC = "named:brooklyn-jclouds-objstore-test-1";
-    
-    JcloudsBlobStoreBasedObjectStore objectStore;
-    StoreObjectAccessor blobstoreAccessor;
-    
-    @BeforeMethod(alwaysRun=true)
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-
-        objectStore = new JcloudsBlobStoreBasedObjectStore(LOCATION_SPEC, "BlobStorePersistencePerformanceTest");
-        objectStore.injectManagementContext(mgmt);
-        objectStore.prepareForSharedUse(PersistMode.AUTO, HighAvailabilityMode.AUTO);
-        blobstoreAccessor = objectStore.newAccessor(Identifiers.makeRandomId(8));
-        
-        app.start(ImmutableList.of(loc));
-    }
-
-    @AfterMethod(alwaysRun=true)
-    @Override
-    public void tearDown() throws Exception {
-        super.tearDown();
-        if (blobstoreAccessor != null) blobstoreAccessor.delete();
-        if (objectStore != null) {
-            objectStore.deleteCompletely();
-            objectStore.close();
-        }
-    }
-    
-    protected int numIterations() {
-        return 100;
-    }
-    
-     @Test(groups={"Live", "Acceptance"})
-     public void testStoreObjectPuts() throws Exception {
-         int numIterations = numIterations();
-         double minRatePerSec = 10 * PERFORMANCE_EXPECTATION;
-         final AtomicInteger i = new AtomicInteger();
-         
-         measureAndAssert("StoreObjectAccessor.put", numIterations, minRatePerSec, new Runnable() {
-             public void run() {
-                 blobstoreAccessor.put(""+i.incrementAndGet());
-             }});
-     }
- 
-     @Test(groups={"Live", "Acceptance"})
-     public void testStoreObjectGet() throws Exception {
-         // The file system will have done a lot of caching here - we are unlikely to touch the disk more than once.
-         int numIterations = numIterations();
-         double minRatePerSec = 10 * PERFORMANCE_EXPECTATION;
-
-         measureAndAssert("FileBasedStoreObjectAccessor.get", numIterations, minRatePerSec, new Runnable() {
-             public void run() {
-                 blobstoreAccessor.get();
-             }});
-     }
- 
-     @Test(groups={"Live", "Acceptance"})
-     public void testStoreObjectDelete() throws Exception {
-         int numIterations = numIterations();
-         double minRatePerSec = 10 * PERFORMANCE_EXPECTATION;
-
-         // Will do 10% warm up runs first
-         final List<StoreObjectAccessor> blobstoreAccessors = Lists.newArrayList();
-         for (int i = 0; i < (numIterations * 1.1 + 1); i++) {
-             blobstoreAccessors.add(objectStore.newAccessor("storeObjectDelete-"+i));
-         }
-         
-         final AtomicInteger i = new AtomicInteger();
-
-         try {
-             measureAndAssert("FileBasedStoreObjectAccessor.delete", numIterations, minRatePerSec, new Runnable() {
-                 public void run() {
-                     StoreObjectAccessor blobstoreAccessor = blobstoreAccessors.get(i.getAndIncrement());
-                     blobstoreAccessor.delete();
-                 }});
-         } finally {
-             for (StoreObjectAccessor blobstoreAccessor : blobstoreAccessors) {
-                 blobstoreAccessor.delete();
-             }
-         }
-     }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BlobStoreTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BlobStoreTest.java b/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BlobStoreTest.java
deleted file mode 100644
index 65cfda5..0000000
--- a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BlobStoreTest.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.rebind.persister.jclouds;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.io.IOException;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.util.stream.Streams;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.jclouds.blobstore.BlobStoreContext;
-import org.jclouds.blobstore.domain.Blob;
-import org.jclouds.blobstore.domain.PageSet;
-import org.jclouds.blobstore.domain.StorageMetadata;
-import org.jclouds.blobstore.options.ListContainerOptions;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
-import org.apache.brooklyn.location.cloud.CloudLocationConfig;
-import org.apache.brooklyn.location.jclouds.JcloudsLocation;
-import org.apache.brooklyn.location.jclouds.JcloudsUtil;
-
-import com.google.common.base.Preconditions;
-
-@Test(groups={"Live", "Live-sanity"})
-public class BlobStoreTest {
-
-    /**
-     * Live tests as written require a location defined as follows:
-     * 
-     * <code>
-     * brooklyn.location.named.brooklyn-jclouds-objstore-test-1==jclouds:swift:https://ams01.objectstorage.softlayer.net/auth/v1.0
-     * brooklyn.location.named.brooklyn-jclouds-objstore-test-1.identity=IBMOS1234-5:yourname
-     * brooklyn.location.named.brooklyn-jclouds-objstore-test-1.credential=0123abcd.......
-     * </code>
-     */
-    public static final String PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC = "named:brooklyn-jclouds-objstore-test-1";
-    
-    public static final String CONTAINER_PREFIX = "brooklyn-persistence-test";
-    
-    private String locationSpec = PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC;
-    
-    private JcloudsLocation location;
-    private BlobStoreContext context;
-
-    private ManagementContext mgmt;
-    private String testContainerName;
-
-    public synchronized BlobStoreContext getBlobStoreContext() {
-        if (context==null) {
-            if (location==null) {
-                Preconditions.checkNotNull(locationSpec, "locationSpec required for remote object store when location is null");
-                Preconditions.checkNotNull(mgmt, "mgmt required for remote object store when location is null");
-                location = (JcloudsLocation) mgmt.getLocationRegistry().resolve(locationSpec);
-            }
-            
-            String identity = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_IDENTITY), "identity must not be null");
-            String credential = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_CREDENTIAL), "credential must not be null");
-            String provider = checkNotNull(location.getConfig(LocationConfigKeys.CLOUD_PROVIDER), "provider must not be null");
-            String endpoint = location.getConfig(CloudLocationConfig.CLOUD_ENDPOINT);
-
-            context = JcloudsUtil.newBlobstoreContext(provider, endpoint, identity, credential);
-        }
-        return context;
-    }
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setup() {
-        testContainerName = CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(8);
-        mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());
-        getBlobStoreContext();
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void teardown() {
-        Entities.destroyAll(mgmt);
-    }
-    
-    public void testCreateListDestroyContainer() throws IOException {
-        context.getBlobStore().createContainerInLocation(null, testContainerName);
-        context.getBlobStore().list(testContainerName);
-        PageSet<? extends StorageMetadata> ps = context.getBlobStore().list();
-        assertHasItemNamed(ps, testContainerName);
-        
-        Blob b = context.getBlobStore().blobBuilder("my-blob-1").payload(Streams.newInputStreamWithContents("hello world")).build();
-        context.getBlobStore().putBlob(testContainerName, b);
-        
-        Blob b2 = context.getBlobStore().getBlob(testContainerName, "my-blob-1");
-        Assert.assertEquals(Streams.readFullyString(b2.getPayload().openStream()), "hello world");
-        
-        context.getBlobStore().deleteContainer(testContainerName);
-    }
-    
-    public void testCreateListDestroySimpleDirInContainer() throws IOException {
-        context.getBlobStore().createContainerInLocation(null, testContainerName);
-        context.getBlobStore().createDirectory(testContainerName, "my-dir-1");
-        
-        PageSet<? extends StorageMetadata> ps = context.getBlobStore().list(testContainerName);
-        assertHasItemNamed(ps, "my-dir-1");
-        
-        Blob b = context.getBlobStore().blobBuilder("my-blob-1").payload(Streams.newInputStreamWithContents("hello world")).build();
-        context.getBlobStore().putBlob(testContainerName+"/"+"my-dir-1", b);
-        
-        ps = context.getBlobStore().list(testContainerName, ListContainerOptions.Builder.inDirectory("my-dir-1"));
-        assertHasItemNamed(ps, "my-dir-1/my-blob-1");
-
-        // both these syntaxes work:
-        Blob b2 = context.getBlobStore().getBlob(testContainerName+"/"+"my-dir-1", "my-blob-1");
-        Assert.assertEquals(Streams.readFullyString(b2.getPayload().openStream()), "hello world");
-
-        Blob b3 = context.getBlobStore().getBlob(testContainerName, "my-dir-1"+"/"+"my-blob-1");
-        Assert.assertEquals(Streams.readFullyString(b3.getPayload().openStream()), "hello world");
-
-        context.getBlobStore().deleteContainer(testContainerName);
-    }
-
-    static void assertHasItemNamed(PageSet<? extends StorageMetadata> ps, String name) {
-        if (!hasItemNamed(ps, name))
-            Assert.fail("No item named '"+name+"' in "+ps);
-    }
-
-    static boolean hasItemNamed(PageSet<? extends StorageMetadata> ps, String name) {
-        for (StorageMetadata sm: ps)
-            if (name==null || name.equals(sm.getName())) return true;
-        return false;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BrooklynMementoPersisterJcloudsObjectStoreTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BrooklynMementoPersisterJcloudsObjectStoreTest.java b/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BrooklynMementoPersisterJcloudsObjectStoreTest.java
deleted file mode 100644
index 550cc8c..0000000
--- a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/BrooklynMementoPersisterJcloudsObjectStoreTest.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.rebind.persister.jclouds;
-
-
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynMementoPersisterTestFixture;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.apache.brooklyn.util.time.Duration;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-/**
- * @author Andrea Turli
- */
-@Test(groups={"Live", "Live-sanity"})
-public class BrooklynMementoPersisterJcloudsObjectStoreTest extends BrooklynMementoPersisterTestFixture {
-
-    @Override @BeforeMethod
-    public void setUp() throws Exception { super.setUp(); }
-    
-    protected LocalManagementContext newPersistingManagementContext() {
-        objectStore = new JcloudsBlobStoreBasedObjectStore(
-            BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4));
-        return RebindTestUtils.managementContextBuilder(classLoader, objectStore)
-            .persistPeriod(Duration.ONE_MILLISECOND)
-            .properties(BrooklynProperties.Factory.newDefault())
-            .buildStarted();
-    }
-    
-    @Test(groups={"Live", "Live-sanity"})
-    @Override
-    public void testCheckPointAndLoadMemento() throws Exception {
-        super.testCheckPointAndLoadMemento();
-    }
-    
-    @Test(groups={"Live", "Live-sanity"})
-    @Override
-    public void testDeleteAndLoadMemento() throws Exception {
-        super.testDeleteAndLoadMemento();
-    }
-    
-    @Test(groups={"Live", "Live-sanity"})
-    @Override
-    public void testLoadAndCheckpointRawMemento() throws Exception {
-        super.testLoadAndCheckpointRawMemento();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/EntityToBlobStorePersistencePerformanceTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/EntityToBlobStorePersistencePerformanceTest.java b/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/EntityToBlobStorePersistencePerformanceTest.java
deleted file mode 100644
index 92c11fd..0000000
--- a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/EntityToBlobStorePersistencePerformanceTest.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
-*/
-package brooklyn.entity.rebind.persister.jclouds;
-
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
-import org.apache.brooklyn.core.test.qa.performance.EntityPersistencePerformanceTest;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.Test;
-
-public class EntityToBlobStorePersistencePerformanceTest extends EntityPersistencePerformanceTest {
-
-    private static final String LOCATION_SPEC = BlobStorePersistencePerformanceTest.LOCATION_SPEC;
-    
-    private JcloudsBlobStoreBasedObjectStore objectStore;
-
-    @Override
-    protected LocalManagementContext createOrigManagementContext() {
-        objectStore = new JcloudsBlobStoreBasedObjectStore(LOCATION_SPEC, "EntityToBlobStorePersistencePerformanceTest");
-        
-        return RebindTestUtils.managementContextBuilder(classLoader, objectStore)
-                .forLive(true)
-                .persistPeriodMillis(getPersistPeriodMillis())
-                .buildStarted();
-    }
-
-    @AfterMethod(alwaysRun=true)
-    @Override
-    public void tearDown() throws Exception {
-        super.tearDown();
-        if (objectStore != null) {
-            objectStore.deleteCompletely();
-            objectStore.close();
-        }
-    }
-
-    @Test(groups="Live")
-    @Override
-    public void testManyEntities() throws Exception {
-        super.testManyEntities();
-    }
-    
-    @Test(groups="Live")
-    @Override
-    public void testRapidChanges() throws Exception {
-        super.testRapidChanges();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/HighAvailabilityManagerJcloudsObjectStoreTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/HighAvailabilityManagerJcloudsObjectStoreTest.java b/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/HighAvailabilityManagerJcloudsObjectStoreTest.java
deleted file mode 100644
index 3268b0b..0000000
--- a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/HighAvailabilityManagerJcloudsObjectStoreTest.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.rebind.persister.jclouds;
-
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.ha.HighAvailabilityManagerTestFixture;
-import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-@Test(groups={"Live", "Live-sanity"})
-public class HighAvailabilityManagerJcloudsObjectStoreTest extends HighAvailabilityManagerTestFixture {
-
-    protected ManagementContextInternal newLocalManagementContext() {
-        return new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());
-    }
-
-    @Override @BeforeMethod
-    public void setUp() throws Exception { super.setUp(); }
-    
-    protected PersistenceObjectStore newPersistenceObjectStore() {
-        return new JcloudsBlobStoreBasedObjectStore(
-            BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4));
-    }
-
-    @Test(groups="Live", invocationCount=5) //run fewer times w softlayer... 
-    public void testGetManagementPlaneStatusManyTimes() throws Exception {
-        testGetManagementPlaneStatus();
-    }
-    
-    @Test(groups={"Live", "Live-sanity"})
-    @Override
-    public void testDoesNotPromoteIfMasterTimeoutNotExpired() throws Exception {
-        super.testDoesNotPromoteIfMasterTimeoutNotExpired();
-    }
-    
-    @Test(groups={"Live", "Live-sanity"})
-    @Override
-    public void testGetManagementPlaneStatus() throws Exception {
-        super.testGetManagementPlaneStatus();
-    }
-    
-    @Test(groups={"Live", "Live-sanity"})
-    @Override
-    public void testPromotes() throws Exception {
-        super.testPromotes();
-    }
-
-    @Test(groups={"Live", "Live-sanity"})
-    @Override
-    public void testGetManagementPlaneSyncStateInfersTimedOutNodeAsFailed() throws Exception {
-        super.testGetManagementPlaneSyncStateInfersTimedOutNodeAsFailed();
-    }
-    
-    @Test(groups={"Live", "Live-sanity"})
-    @Override
-    public void testGetManagementPlaneSyncStateDoesNotThrowNpeBeforePersisterSet() throws Exception {
-        super.testGetManagementPlaneSyncStateDoesNotThrowNpeBeforePersisterSet();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/JcloudsBlobStoreBasedObjectStoreTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/JcloudsBlobStoreBasedObjectStoreTest.java b/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/JcloudsBlobStoreBasedObjectStoreTest.java
deleted file mode 100644
index fee274d..0000000
--- a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/JcloudsBlobStoreBasedObjectStoreTest.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.rebind.persister.jclouds;
-
-
-import java.util.List;
-
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynPersistenceUtils;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore.StoreObjectAccessor;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.apache.brooklyn.util.time.Duration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Stopwatch;
-
-/**
- * @author Andrea Turli
- */
-@Test(groups={"Live", "Live-sanity"})
-public class JcloudsBlobStoreBasedObjectStoreTest {
-
-    private static final Logger log = LoggerFactory.getLogger(JcloudsBlobStoreBasedObjectStoreTest.class);
-    
-    private List<PersistenceObjectStore> objectStores = MutableList.of();;
-    private LocalManagementContext mgmt;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception { 
-        mgmt = LocalManagementContextForTests.builder(true).useDefaultProperties().build();
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        for (PersistenceObjectStore store: objectStores) store.deleteCompletely();
-        Entities.destroyAll(mgmt);
-        objectStores.clear();
-    }
-
-    public PersistenceObjectStore newObjectStore(String spec, String container) {
-        PersistenceObjectStore newObjectStore = BrooklynPersistenceUtils.newPersistenceObjectStore(mgmt, spec, container);
-        objectStores.add(newObjectStore);
-        return newObjectStore;
-    }
-    
-    @Test(groups={"Integration"})
-    public void testLocalhost() throws Exception {
-        doTestWithStore( newObjectStore(null, 
-            BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4)) );
-    }
-    
-    @Test(groups={"Integration"})
-    public void testLocalhostWithSubPathInContainerName() throws Exception {
-        doTestWithStore( newObjectStore(null, 
-            BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4)+"/subpath1/subpath2") );
-    }
-    
-    @Test(groups={"Live", "Live-sanity"})
-    public void testJclouds() throws Exception {
-        doTestWithStore( newObjectStore(BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, 
-            BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4)) );
-    }
-    
-    @Test(groups={"Live", "Live-sanity"})
-    public void testJcloudsWithSubPathInContainerName() throws Exception {
-        doTestWithStore( newObjectStore(BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, 
-            BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4)+"/subpath1/subpath2") );
-    }
-    
-    protected void doTestWithStore(PersistenceObjectStore objectStore) {
-        log.info("testing against "+objectStore.getSummaryName());
-        
-        objectStore.createSubPath("foo");
-        StoreObjectAccessor f = objectStore.newAccessor("foo/file1.txt");
-        Assert.assertFalse(f.exists());
-
-        Stopwatch timer = Stopwatch.createStarted();
-        f.append("Hello world");
-        log.info("created in "+Duration.of(timer));
-        timer.reset();
-        Assert.assertEquals(f.get(), "Hello world");
-        log.info("retrieved in "+Duration.of(timer));
-        Assert.assertTrue(f.exists());
-        
-        timer.reset();
-        List<String> files = objectStore.listContentsWithSubPath("foo");
-        log.info("list retrieved in "+Duration.of(timer)+"; is: "+files);
-        Assert.assertEquals(files, MutableList.of("foo/file1.txt"));
-        
-        f.delete();
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/JcloudsExpect100ContinueTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/JcloudsExpect100ContinueTest.java b/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/JcloudsExpect100ContinueTest.java
deleted file mode 100644
index 43943c6..0000000
--- a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/JcloudsExpect100ContinueTest.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.rebind.persister.jclouds;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.jclouds.blobstore.BlobStore;
-import org.jclouds.blobstore.BlobStoreContext;
-import org.jclouds.blobstore.domain.Blob;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.jclouds.JcloudsLocation;
-import org.apache.brooklyn.location.jclouds.JcloudsUtil;
-
-import ch.qos.logback.classic.Level;
-import ch.qos.logback.classic.Logger;
-
-import com.google.common.base.Charsets;
-import com.google.common.io.ByteSource;
-
-public class JcloudsExpect100ContinueTest {
-    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(JcloudsExpect100ContinueTest.class);
-
-    private static String LOCATION_SPEC = BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC;
-    private static final String OBJECT_NAME_PUT = "test_put";
-    private static final String OBJECT_NAME_GET = "test_get";
-    
-    private ManagementContext mgmt;
-    private BlobStoreContext context;
-    private String containerName;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        // It's important to disable jclouds debug logging
-        // as it "fixes" the issue.
-        setInfoLevel(Logger.ROOT_LOGGER_NAME);
-        setInfoLevel("jclouds");
-        setInfoLevel("org.jclouds");
-
-        mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());
-        JcloudsLocation jcloudsLocation = (JcloudsLocation) mgmt.getLocationRegistry().resolve(LOCATION_SPEC);
-        context = JcloudsUtil.newBlobstoreContext(
-                jcloudsLocation.getProvider(),
-                jcloudsLocation.getEndpoint(),
-                jcloudsLocation.getIdentity(),
-                jcloudsLocation.getCredential());
-        containerName = BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(8);
-        context.getBlobStore().createContainerInLocation(null, containerName);
-    }
-
-    private void setInfoLevel(String loggerName) {
-        Logger logger = (Logger) LoggerFactory.getLogger(loggerName);
-        logger.setLevel(Level.INFO);
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        try {
-            context.getBlobStore().deleteContainer(containerName);
-        } catch (Exception e){}
-        context.close();
-        Entities.destroyAll(mgmt);
-    }
-    
-    @Test(groups = "Live", timeOut=240000)
-    public void testPutAfterUnclosedGet() {
-        put(OBJECT_NAME_PUT, getContent());
-        put(OBJECT_NAME_GET, getContent());
-
-        for (int i = 1; i <= 50; i++) {
-            long start = System.currentTimeMillis();
-            get(OBJECT_NAME_GET);
-            long afterGet = System.currentTimeMillis();
-            LOG.info(i + ". GET @" + (afterGet - start));
-
-            System.gc();
-            System.gc();
-            System.gc();
-            sleep(1000);
-
-            // Without excluding Expect: 100-Continue header
-            // the PUT is supposed to block until the server
-            // times out
-
-            long beforePut = System.currentTimeMillis();
-            put(OBJECT_NAME_PUT, getContent());
-            long end = System.currentTimeMillis();
-            LOG.info(i + ". PUT @" + (end - beforePut));
-        }
-    }
-
-    private String getContent() {
-        return "1234567890";
-    }
-
-    private void put(String name, String content) {
-        BlobStore blobStore = context.getBlobStore();
-        byte[] bytes = content.getBytes(Charsets.UTF_8);
-        Blob blob = blobStore.blobBuilder(name)
-                .payload(ByteSource.wrap(bytes))
-                .contentLength(bytes.length)
-                .build();
-        try {
-            blobStore.putBlob(containerName, blob);
-        } catch (Exception e) {
-            LOG.error("PUT " + name + " failed", e);
-        }
-    }
-
-    private Blob get(String name) {
-        try {
-            BlobStore blobStore = context.getBlobStore();
-            return blobStore.getBlob(containerName, name);
-        } catch (Exception e) {
-            LOG.error("GET " + name + " failed", e);
-            return null;
-        }
-    }
-
-    private void sleep(long millis) {
-        try {
-            Thread.sleep(millis);
-        } catch (InterruptedException e) {
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/JcloudsObjectStoreAccessorWriterTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/JcloudsObjectStoreAccessorWriterTest.java b/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/JcloudsObjectStoreAccessorWriterTest.java
deleted file mode 100644
index 76c2bfd..0000000
--- a/locations/jclouds/src/test/java/brooklyn/entity/rebind/persister/jclouds/JcloudsObjectStoreAccessorWriterTest.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.rebind.persister.jclouds;
-
-import java.io.IOException;
-
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceStoreObjectAccessorWriterTestFixture;
-import org.apache.brooklyn.core.mgmt.rebind.persister.StoreObjectAccessorLocking;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore.StoreObjectAccessorWithLock;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.apache.brooklyn.util.time.Duration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-@Test(groups={"Live", "Live-sanity"})
-public class JcloudsObjectStoreAccessorWriterTest extends PersistenceStoreObjectAccessorWriterTestFixture {
-
-    private static final Logger log = LoggerFactory.getLogger(JcloudsObjectStoreAccessorWriterTest.class);
-    
-    private JcloudsBlobStoreBasedObjectStore store;
-    private LocalManagementContextForTests mgmt;
-
-    @Override @BeforeMethod
-    public void setUp() throws Exception {
-        store = new JcloudsBlobStoreBasedObjectStore(
-            BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4));
-        store.injectManagementContext(mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault()));
-        store.prepareForSharedUse(PersistMode.CLEAN, HighAvailabilityMode.DISABLED);
-        super.setUp();
-    }
-
-    @Override @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        super.tearDown();
-        if (mgmt!=null) Entities.destroyAll(mgmt);
-        if (store!=null) store.deleteCompletely();
-    }
-    
-    protected StoreObjectAccessorWithLock newPersistenceStoreObjectAccessor() throws IOException {
-        return newPersistenceStoreObjectAccessor(store, "");
-    }
-    protected StoreObjectAccessorWithLock newPersistenceStoreObjectAccessor(JcloudsBlobStoreBasedObjectStore aStore, String prefix) throws IOException {
-        return new StoreObjectAccessorLocking(aStore.newAccessor(prefix+"sample-file-"+Identifiers.makeRandomId(4)));
-    }
-
-    @Override
-    protected Duration getLastModifiedResolution() {
-        // Not sure what timing resolution is on things like Softlayer's Swift.
-        // It passed for Aled repeatedly on 2014-11-05 with 2 seconds.
-        return Duration.seconds(2);
-    }
-    
-    protected int biggishSize() {
-        // bit smaller since it's actually uploading here!
-        return 10000;
-    }
-
-    /** Tests what happen when we ask the store to be in a container with a path, e.g. path1/path2 
-     * and then the accessor to a file within that (path3/file) --
-     * this does it an emulated way, where the store tracks the subpath so we don't have to */
-    @Test(groups={"Live"})
-    public void testNestedPath1() throws IOException {
-        mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());
-        String path1 = BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4);
-        String path2 = BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4);
-        String path3 = BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4);
-        JcloudsBlobStoreBasedObjectStore store0 = null;
-        try {
-            store0 = new JcloudsBlobStoreBasedObjectStore(BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, Urls.mergePaths(path1, path2));
-            store0.injectManagementContext(mgmt);
-            store0.prepareForSharedUse(PersistMode.CLEAN, HighAvailabilityMode.DISABLED);
-
-            newPersistenceStoreObjectAccessor(store0, path3+"/").put("hello world");
-        } catch (Exception e) {
-            log.warn("Failed with: "+e, e);
-            throw Exceptions.propagate(e);
-            
-        } finally {
-            store0.deleteCompletely();
-            
-            JcloudsBlobStoreBasedObjectStore storeD = new JcloudsBlobStoreBasedObjectStore(BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, path1);
-            storeD.injectManagementContext(mgmt);
-            storeD.prepareForSharedUse(PersistMode.CLEAN, HighAvailabilityMode.DISABLED);
-            storeD.deleteCompletely();
-        }
-    }
-
-    /** Tests what happen when we ask the store to be in a container with a path, e.g. path1/path2 
-     * and then the accessor to a file within that (path3/file) --
-     * this does it the "official" way, where we ask for the store's container
-     * to be the first path segment */
-    @Test(groups={"Live"})
-    public void testNestedPath2() throws IOException {
-        mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());
-        String path1 = BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4);
-        String path2 = BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4);
-        String path3 = BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4);
-        JcloudsBlobStoreBasedObjectStore store1 = null, store2 = null;
-        try {
-            store1 = new JcloudsBlobStoreBasedObjectStore(BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, 
-                path1);
-            store1.injectManagementContext(mgmt);
-            store1.prepareForSharedUse(PersistMode.CLEAN, HighAvailabilityMode.DISABLED);
-            store1.createSubPath(path2);
-            newPersistenceStoreObjectAccessor(store1, path2+"/"+path3+"/").put("hello world");
-            
-            store2 = new JcloudsBlobStoreBasedObjectStore(BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, 
-                Urls.mergePaths(path1, path2));
-            store2.injectManagementContext(mgmt);
-            store2.prepareForSharedUse(PersistMode.CLEAN, HighAvailabilityMode.DISABLED);
-
-            newPersistenceStoreObjectAccessor(store2, path3+"/").put("hello world");
-            
-        } catch (Exception e) {
-            e.printStackTrace();
-        } finally {
-            // this doesn't work
-//            store2.deleteCompletely();
-            // this is how you have to do it:
-            store1.newAccessor(path2).delete();
-            
-            store1.deleteCompletely();
-        }
-    }
-
-    @Test(groups={"Live", "Live-sanity"})
-    @Override
-    public void testWriteBacklogThenDeleteWillLeaveFileDeleted() throws Exception {
-        super.testWriteBacklogThenDeleteWillLeaveFileDeleted();
-    }
-    
-    @Test(groups={"Live", "Live-sanity"})
-    @Override
-    public void testWritesFile() throws Exception {
-        super.testWritesFile();
-    }
-
-    @Test(groups={"Live", "Live-sanity"})
-    @Override
-    public void testLastModifiedTime() throws Exception {
-        super.testLastModifiedTime();
-    }
-    
-    @Test(groups={"Live", "Live-sanity"})
-    @Override
-    public void testExists() throws Exception {
-        super.testExists();
-    }
-    
-    @Test(groups={"Live", "Live-sanity"})
-    @Override
-    public void testAppendsFile() throws Exception {
-        super.testAppendsFile();
-    }
-}



[28/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/software/winrm/WindowsPerformanceCounterSensors.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/software/winrm/WindowsPerformanceCounterSensors.java b/software/base/src/main/java/brooklyn/entity/software/winrm/WindowsPerformanceCounterSensors.java
deleted file mode 100644
index 05a0482..0000000
--- a/software/base/src/main/java/brooklyn/entity/software/winrm/WindowsPerformanceCounterSensors.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software.winrm;
-
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.brooklyn.api.entity.EntityInitializer;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.sensor.feed.windows.WindowsPerformanceCounterFeed;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.text.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.reflect.TypeToken;
-
-public class WindowsPerformanceCounterSensors implements EntityInitializer {
-
-    private static final Logger LOG = LoggerFactory.getLogger(WindowsPerformanceCounterSensors.class);
-
-    public final static ConfigKey<Set<Map<String, String>>> PERFORMANCE_COUNTERS = ConfigKeys.newConfigKey(new TypeToken<Set<Map<String, String>>>(){}, "performance.counters");
-
-    protected final Set<Map<String, String>> sensors;
-
-    public WindowsPerformanceCounterSensors(ConfigBag params) {
-        sensors = params.get(PERFORMANCE_COUNTERS);
-    }
-
-    public WindowsPerformanceCounterSensors(Map<String, String> params) {
-        this(ConfigBag.newInstance(params));
-    }
-
-    @Override
-    public void apply(EntityLocal entity) {
-        WindowsPerformanceCounterFeed.Builder builder = WindowsPerformanceCounterFeed.builder()
-                .entity(entity);
-        for (Map<String, String> sensorConfig : sensors) {
-            String name = sensorConfig.get("name");
-            String sensorType = sensorConfig.get("sensorType");
-            Class<?> clazz;
-            try {
-                clazz = Strings.isNonEmpty(sensorType)
-                        ? ((EntityInternal)entity).getManagementContext().getCatalog().getRootClassLoader().loadClass(sensorType) 
-                        : String.class;
-            } catch (ClassNotFoundException e) {
-                throw new IllegalStateException("Could not load type "+sensorType+" for sensor "+name, e);
-            }
-            builder.addSensor(sensorConfig.get("counter"), Sensors.newSensor(clazz, name, sensorConfig.get("description")));
-        }
-        builder.build();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/event/feed/jmx/JmxAttributePollConfig.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/event/feed/jmx/JmxAttributePollConfig.java b/software/base/src/main/java/brooklyn/event/feed/jmx/JmxAttributePollConfig.java
deleted file mode 100644
index ac8a27d..0000000
--- a/software/base/src/main/java/brooklyn/event/feed/jmx/JmxAttributePollConfig.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.event.feed.jmx;
-
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
-
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.sensor.feed.PollConfig;
-
-import com.google.common.base.Function;
-import com.google.common.base.Functions;
-
-public class JmxAttributePollConfig<T> extends PollConfig<Object, T, JmxAttributePollConfig<T>>{
-
-    private ObjectName objectName;
-    private String attributeName;
-
-    @SuppressWarnings({ "unchecked", "rawtypes" })
-    public JmxAttributePollConfig(AttributeSensor<T> sensor) {
-        super(sensor);
-        onSuccess((Function)Functions.identity());
-    }
-
-    public JmxAttributePollConfig(JmxAttributePollConfig<T> other) {
-        super(other);
-        this.objectName = other.objectName;
-        this.attributeName = other.attributeName;
-    }
-
-    public ObjectName getObjectName() {
-        return objectName;
-    }
-    
-    public String getAttributeName() {
-        return attributeName;
-    }
-    
-    public JmxAttributePollConfig<T> objectName(ObjectName val) {
-        this.objectName = val; return this;
-    }
-    
-    public JmxAttributePollConfig<T> objectName(String val) {
-        try {
-            return objectName(new ObjectName(val));
-        } catch (MalformedObjectNameException e) {
-            throw new IllegalArgumentException("Invalid object name ("+val+")", e);
-        }
-    }
-    
-    public JmxAttributePollConfig<T> attributeName(String val) {
-        this.attributeName = val; return this;
-    }
-    
-    @Override protected String toStringBaseName() { return "jmx"; }
-    @Override protected String toStringPollSource() { return objectName+":"+attributeName; }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/event/feed/jmx/JmxFeed.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/event/feed/jmx/JmxFeed.java b/software/base/src/main/java/brooklyn/event/feed/jmx/JmxFeed.java
deleted file mode 100644
index 82e953b..0000000
--- a/software/base/src/main/java/brooklyn/event/feed/jmx/JmxFeed.java
+++ /dev/null
@@ -1,437 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.event.feed.jmx;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-
-import javax.management.Notification;
-import javax.management.NotificationFilter;
-import javax.management.NotificationListener;
-import javax.management.ObjectName;
-
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.sensor.feed.AbstractFeed;
-import org.apache.brooklyn.sensor.feed.AttributePollHandler;
-import org.apache.brooklyn.sensor.feed.DelegatingPollHandler;
-import org.apache.brooklyn.sensor.feed.PollHandler;
-import org.apache.brooklyn.sensor.feed.Poller;
-import org.apache.brooklyn.util.time.Duration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.SetMultimap;
-import com.google.common.collect.Sets;
-import com.google.common.reflect.TypeToken;
-
-
-/**
- * Provides a feed of attribute values, by polling or subscribing over jmx.
- * 
- * Example usage (e.g. in an entity that extends {@link SoftwareProcessImpl}):
- * <pre>
- * {@code
- * private JmxFeed feed;
- * 
- * //@Override
- * protected void connectSensors() {
- *   super.connectSensors();
- *   
- *   feed = JmxFeed.builder()
- *       .entity(this)
- *       .period(500, TimeUnit.MILLISECONDS)
- *       .pollAttribute(new JmxAttributePollConfig<Integer>(ERROR_COUNT)
- *           .objectName(requestProcessorMbeanName)
- *           .attributeName("errorCount"))
- *       .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP)
- *           .objectName(serverMbeanName)
- *           .attributeName("Started")
- *           .onError(Functions.constant(false)))
- *       .build();
- * }
- * 
- * {@literal @}Override
- * protected void disconnectSensors() {
- *   super.disconnectSensors();
- *   if (feed != null) feed.stop();
- * }
- * }
- * </pre>
- * 
- * @author aled
- */
-public class JmxFeed extends AbstractFeed {
-
-    public static final Logger log = LoggerFactory.getLogger(JmxFeed.class);
-
-    public static final long JMX_CONNECTION_TIMEOUT_MS = 120*1000;
-
-    public static final ConfigKey<JmxHelper> HELPER = ConfigKeys.newConfigKey(JmxHelper.class, "helper");
-    public static final ConfigKey<Boolean> OWN_HELPER = ConfigKeys.newBooleanConfigKey("ownHelper");
-    public static final ConfigKey<String> JMX_URI = ConfigKeys.newStringConfigKey("jmxUri");
-    public static final ConfigKey<Long> JMX_CONNECTION_TIMEOUT = ConfigKeys.newLongConfigKey("jmxConnectionTimeout");
-    
-    @SuppressWarnings("serial")
-    public static final ConfigKey<SetMultimap<String, JmxAttributePollConfig<?>>> ATTRIBUTE_POLLS = ConfigKeys.newConfigKey(
-            new TypeToken<SetMultimap<String, JmxAttributePollConfig<?>>>() {},
-            "attributePolls");
-
-    @SuppressWarnings("serial")
-    public static final ConfigKey<SetMultimap<List<?>, JmxOperationPollConfig<?>>> OPERATION_POLLS = ConfigKeys.newConfigKey(
-            new TypeToken<SetMultimap<List<?>, JmxOperationPollConfig<?>>>() {},
-            "operationPolls");
-
-    @SuppressWarnings("serial")
-    public static final ConfigKey<SetMultimap<NotificationFilter, JmxNotificationSubscriptionConfig<?>>> NOTIFICATION_SUBSCRIPTIONS = ConfigKeys.newConfigKey(
-            new TypeToken<SetMultimap<NotificationFilter, JmxNotificationSubscriptionConfig<?>>>() {},
-            "notificationPolls");
-
-    public static Builder builder() {
-        return new Builder();
-    }
-    
-    public static class Builder {
-        private EntityLocal entity;
-        private JmxHelper helper;
-        private long jmxConnectionTimeout = JMX_CONNECTION_TIMEOUT_MS;
-        private long period = 500;
-        private TimeUnit periodUnits = TimeUnit.MILLISECONDS;
-        private List<JmxAttributePollConfig<?>> attributePolls = Lists.newArrayList();
-        private List<JmxOperationPollConfig<?>> operationPolls = Lists.newArrayList();
-        private List<JmxNotificationSubscriptionConfig<?>> notificationSubscriptions = Lists.newArrayList();
-        private String uniqueTag;
-        private volatile boolean built;
-        
-        public Builder entity(EntityLocal val) {
-            this.entity = val;
-            return this;
-        }
-        public Builder helper(JmxHelper val) {
-            this.helper = val;
-            return this;
-        }
-        public Builder period(Duration duration) {
-            return period(duration.toMilliseconds(), TimeUnit.MILLISECONDS);
-        }
-        public Builder period(long millis) {
-            return period(millis, TimeUnit.MILLISECONDS);
-        }
-        public Builder period(long val, TimeUnit units) {
-            this.period = val;
-            this.periodUnits = units;
-            return this;
-        }
-        public Builder pollAttribute(JmxAttributePollConfig<?> config) {
-            attributePolls.add(config);
-            return this;
-        }
-        public Builder pollOperation(JmxOperationPollConfig<?> config) {
-            operationPolls.add(config);
-            return this;
-        }
-        public Builder subscribeToNotification(JmxNotificationSubscriptionConfig<?> config) {
-            notificationSubscriptions.add(config);
-            return this;
-        }
-        public Builder uniqueTag(String uniqueTag) {
-            this.uniqueTag = uniqueTag;
-            return this;
-        }
-        public JmxFeed build() {
-            built = true;
-            JmxFeed result = new JmxFeed(this);
-            result.setEntity(checkNotNull(entity, "entity"));
-            result.start();
-            return result;
-        }
-        @Override
-        protected void finalize() {
-            if (!built) log.warn("JmxFeed.Builder created, but build() never called");
-        }
-    }
-
-    private final SetMultimap<ObjectName, NotificationListener> notificationListeners = HashMultimap.create();
-
-    /**
-     * For rebind; do not call directly; use builder
-     */
-    public JmxFeed() {
-    }
-
-    protected JmxFeed(Builder builder) {
-        super();
-        if (builder.helper != null) {
-            JmxHelper helper = builder.helper;
-            setConfig(HELPER, helper);
-            setConfig(OWN_HELPER, false);
-            setConfig(JMX_URI, helper.getUrl());
-        }
-        setConfig(JMX_CONNECTION_TIMEOUT, builder.jmxConnectionTimeout);
-        
-        SetMultimap<String, JmxAttributePollConfig<?>> attributePolls = HashMultimap.<String,JmxAttributePollConfig<?>>create();
-        for (JmxAttributePollConfig<?> config : builder.attributePolls) {
-            if (!config.isEnabled()) continue;
-            @SuppressWarnings({ "rawtypes", "unchecked" })
-            JmxAttributePollConfig<?> configCopy = new JmxAttributePollConfig(config);
-            if (configCopy.getPeriod() < 0) configCopy.period(builder.period, builder.periodUnits);
-            attributePolls.put(configCopy.getObjectName().getCanonicalName() + configCopy.getAttributeName(), configCopy);
-        }
-        setConfig(ATTRIBUTE_POLLS, attributePolls);
-        
-        SetMultimap<List<?>, JmxOperationPollConfig<?>> operationPolls = HashMultimap.<List<?>,JmxOperationPollConfig<?>>create();
-        for (JmxOperationPollConfig<?> config : builder.operationPolls) {
-            if (!config.isEnabled()) continue;
-            @SuppressWarnings({ "rawtypes", "unchecked" })
-            JmxOperationPollConfig<?> configCopy = new JmxOperationPollConfig(config);
-            if (configCopy.getPeriod() < 0) configCopy.period(builder.period, builder.periodUnits);
-            operationPolls.put(configCopy.buildOperationIdentity(), configCopy);
-        }
-        setConfig(OPERATION_POLLS, operationPolls);
-        
-        SetMultimap<NotificationFilter, JmxNotificationSubscriptionConfig<?>> notificationSubscriptions = HashMultimap.create();
-        for (JmxNotificationSubscriptionConfig<?> config : builder.notificationSubscriptions) {
-            if (!config.isEnabled()) continue;
-            notificationSubscriptions.put(config.getNotificationFilter(), config);
-        }
-        setConfig(NOTIFICATION_SUBSCRIPTIONS, notificationSubscriptions);
-        initUniqueTag(builder.uniqueTag, attributePolls, operationPolls, notificationSubscriptions);
-    }
-
-    @Override
-    public void setEntity(EntityLocal entity) {
-        if (getConfig(HELPER) == null) {
-            JmxHelper helper = new JmxHelper(entity);
-            setConfig(HELPER, helper);
-            setConfig(OWN_HELPER, true);
-            setConfig(JMX_URI, helper.getUrl());
-        }
-        super.setEntity(entity);
-    }
-    
-    public String getJmxUri() {
-        return getConfig(JMX_URI);
-    }
-    
-    protected JmxHelper getHelper() {
-        return getConfig(HELPER);
-    }
-    
-    @SuppressWarnings("unchecked")
-    protected Poller<Object> getPoller() {
-        return (Poller<Object>) super.getPoller();
-    }
-    
-    @Override
-    protected boolean isConnected() {
-        return super.isConnected() && getHelper().isConnected();
-    }
-    
-    @Override
-    protected void preStart() {
-        /*
-         * All actions on the JmxHelper are done async (through the poller's threading) so we don't 
-         * block on start for a long time (e.g. if the entity is not contactable and doing a rebind 
-         * on restart of brooklyn). Without that, one gets a 120 second pause with it stuck in a 
-         * stack trace like:
-         * 
-         *      at brooklyn.event.feed.jmx.JmxHelper.sleep(JmxHelper.java:640)
-         *      at brooklyn.event.feed.jmx.JmxHelper.connect(JmxHelper.java:320)
-         *      at brooklyn.event.feed.jmx.JmxFeed.preStart(JmxFeed.java:172)
-         *      at brooklyn.event.feed.AbstractFeed.start(AbstractFeed.java:68)
-         *      at brooklyn.event.feed.jmx.JmxFeed$Builder.build(JmxFeed.java:119)
-         *      at brooklyn.entity.java.JavaAppUtils.connectMXBeanSensors(JavaAppUtils.java:109)
-         *      at brooklyn.entity.java.VanillaJavaApp.connectSensors(VanillaJavaApp.java:97)
-         *      at brooklyn.entity.basic.SoftwareProcessImpl.callRebindHooks(SoftwareProcessImpl.java:189)
-         *      at brooklyn.entity.basic.SoftwareProcessImpl.rebind(SoftwareProcessImpl.java:235)
-         *      ...
-         *      at brooklyn.entity.rebind.RebindManagerImpl.rebind(RebindManagerImpl.java:184)
-         */
-        final SetMultimap<NotificationFilter, JmxNotificationSubscriptionConfig<?>> notificationSubscriptions = getConfig(NOTIFICATION_SUBSCRIPTIONS);
-        final SetMultimap<List<?>, JmxOperationPollConfig<?>> operationPolls = getConfig(OPERATION_POLLS);
-        final SetMultimap<String, JmxAttributePollConfig<?>> attributePolls = getConfig(ATTRIBUTE_POLLS);
-        
-        getPoller().submit(new Callable<Void>() {
-               public Void call() {
-                   getHelper().connect(getConfig(JMX_CONNECTION_TIMEOUT));
-                   return null;
-               }
-               @Override public String toString() { return "Connect JMX "+getHelper().getUrl(); }
-           });
-        
-        for (final NotificationFilter filter : notificationSubscriptions.keySet()) {
-            getPoller().submit(new Callable<Void>() {
-                public Void call() {
-                    // TODO Could config.getObjectName have wildcards? Is this code safe?
-                    Set<JmxNotificationSubscriptionConfig<?>> configs = notificationSubscriptions.get(filter);
-                    NotificationListener listener = registerNotificationListener(configs);
-                    ObjectName objectName = Iterables.get(configs, 0).getObjectName();
-                    notificationListeners.put(objectName, listener);
-                    return null;
-                }
-                @Override public String toString() { return "Register JMX notifications: "+notificationSubscriptions.get(filter); }
-            });
-        }
-        
-        // Setup polling of sensors
-        for (final String jmxAttributeName : attributePolls.keys()) {
-            registerAttributePoller(attributePolls.get(jmxAttributeName));
-        }
-        
-        // Setup polling of operations
-        for (final List<?> operationIdentifier : operationPolls.keys()) {
-            registerOperationPoller(operationPolls.get(operationIdentifier));
-        }
-    }
-    
-    @Override
-    protected void preStop() {
-        super.preStop();
-
-        for (Map.Entry<ObjectName, NotificationListener> entry : notificationListeners.entries()) {
-            unregisterNotificationListener(entry.getKey(), entry.getValue());
-        }
-        notificationListeners.clear();
-    }
-    
-    @Override
-    protected void postStop() {
-        super.postStop();
-        JmxHelper helper = getHelper();
-        Boolean ownHelper = getConfig(OWN_HELPER);
-        if (helper != null && ownHelper) helper.terminate();
-    }
-    
-    /**
-     * Registers to poll a jmx-operation for an ObjectName, where all the given configs are for the same ObjectName + operation + parameters.
-     */
-    private void registerOperationPoller(Set<JmxOperationPollConfig<?>> configs) {
-        Set<AttributePollHandler<? super Object>> handlers = Sets.newLinkedHashSet();
-        long minPeriod = Integer.MAX_VALUE;
-        
-        final ObjectName objectName = Iterables.get(configs, 0).getObjectName();
-        final String operationName = Iterables.get(configs, 0).getOperationName();
-        final List<String> signature = Iterables.get(configs, 0).getSignature();
-        final List<?> params = Iterables.get(configs, 0).getParams();
-        
-        for (JmxOperationPollConfig<?> config : configs) {
-            handlers.add(new AttributePollHandler<Object>(config, getEntity(), this));
-            if (config.getPeriod() > 0) minPeriod = Math.min(minPeriod, config.getPeriod());
-        }
-        
-        getPoller().scheduleAtFixedRate(
-                new Callable<Object>() {
-                    public Object call() throws Exception {
-                        if (log.isDebugEnabled()) log.debug("jmx operation polling for {} sensors at {} -> {}", new Object[] {getEntity(), getJmxUri(), operationName});
-                        if (signature.size() == params.size()) {
-                            return getHelper().operation(objectName, operationName, signature, params);
-                        } else {
-                            return getHelper().operation(objectName, operationName, params.toArray());
-                        }
-                    }
-                }, 
-                new DelegatingPollHandler<Object>(handlers), minPeriod);
-    }
-
-    /**
-     * Registers to poll a jmx-attribute for an ObjectName, where all the given configs are for that same ObjectName + attribute.
-     */
-    private void registerAttributePoller(Set<JmxAttributePollConfig<?>> configs) {
-        Set<AttributePollHandler<? super Object>> handlers = Sets.newLinkedHashSet();
-        long minPeriod = Integer.MAX_VALUE;
-        
-        final ObjectName objectName = Iterables.get(configs, 0).getObjectName();
-        final String jmxAttributeName = Iterables.get(configs, 0).getAttributeName();
-        
-        for (JmxAttributePollConfig<?> config : configs) {
-            handlers.add(new AttributePollHandler<Object>(config, getEntity(), this));
-            if (config.getPeriod() > 0) minPeriod = Math.min(minPeriod, config.getPeriod());
-        }
-        
-        // TODO Not good calling this holding the synchronization lock
-        getPoller().scheduleAtFixedRate(
-                new Callable<Object>() {
-                    public Object call() throws Exception {
-                        if (log.isTraceEnabled()) log.trace("jmx attribute polling for {} sensors at {} -> {}", new Object[] {getEntity(), getJmxUri(), jmxAttributeName});
-                        return getHelper().getAttribute(objectName, jmxAttributeName);
-                    }
-                }, 
-                new DelegatingPollHandler<Object>(handlers), minPeriod);
-    }
-
-    /**
-     * Registers to subscribe to notifications for an ObjectName, where all the given configs are for that same ObjectName + filter.
-     */
-    private NotificationListener registerNotificationListener(Set<JmxNotificationSubscriptionConfig<?>> configs) {
-        final List<AttributePollHandler<? super javax.management.Notification>> handlers = Lists.newArrayList();
-
-        final ObjectName objectName = Iterables.get(configs, 0).getObjectName();
-        final NotificationFilter filter = Iterables.get(configs, 0).getNotificationFilter();
-
-        for (final JmxNotificationSubscriptionConfig<?> config : configs) {
-            AttributePollHandler<javax.management.Notification> handler = new AttributePollHandler<javax.management.Notification>(config, getEntity(), this) {
-                @Override protected Object transformValueOnSuccess(javax.management.Notification val) {
-                    if (config.getOnNotification() != null) {
-                        return config.getOnNotification().apply(val);
-                    } else {
-                        Object result = super.transformValueOnSuccess(val);
-                        if (result instanceof javax.management.Notification)
-                            return ((javax.management.Notification)result).getUserData();
-                        return result;
-                    }
-                }
-            };
-            handlers.add(handler);
-        }
-        final PollHandler<javax.management.Notification> compoundHandler = new DelegatingPollHandler<javax.management.Notification>(handlers);
-        
-        NotificationListener listener = new NotificationListener() {
-            @Override public void handleNotification(Notification notification, Object handback) {
-                compoundHandler.onSuccess(notification);
-            }
-        };
-        getHelper().addNotificationListener(objectName, listener, filter);
-        
-        return listener;
-    }
-    
-    private void unregisterNotificationListener(ObjectName objectName, NotificationListener listener) {
-        try {
-            getHelper().removeNotificationListener(objectName, listener);
-        } catch (RuntimeException e) {
-            log.warn("Failed to unregister listener: "+objectName+", "+listener+"; continuing...", e);
-        }
-    }
-    
-    @Override
-    public String toString() {
-        return "JmxFeed["+(getManagementContext()!=null&&getManagementContext().isRunning()?getJmxUri():"mgmt-not-running")+"]";
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/event/feed/jmx/JmxHelper.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/event/feed/jmx/JmxHelper.java b/software/base/src/main/java/brooklyn/event/feed/jmx/JmxHelper.java
deleted file mode 100644
index cfc405e..0000000
--- a/software/base/src/main/java/brooklyn/event/feed/jmx/JmxHelper.java
+++ /dev/null
@@ -1,725 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.event.feed.jmx;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import static org.apache.brooklyn.util.JavaGroovyEquivalents.groovyTruth;
-import groovy.time.TimeDuration;
-
-import java.io.IOException;
-import java.security.KeyStore;
-import java.security.PrivateKey;
-import java.security.cert.Certificate;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Set;
-import java.util.WeakHashMap;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicReference;
-
-import javax.management.AttributeNotFoundException;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.InvalidAttributeValueException;
-import javax.management.JMX;
-import javax.management.ListenerNotFoundException;
-import javax.management.MBeanServerConnection;
-import javax.management.MalformedObjectNameException;
-import javax.management.NotCompliantMBeanException;
-import javax.management.NotificationFilter;
-import javax.management.NotificationListener;
-import javax.management.ObjectInstance;
-import javax.management.ObjectName;
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.TabularData;
-import javax.management.remote.JMXConnector;
-import javax.management.remote.JMXConnectorFactory;
-import javax.management.remote.JMXServiceURL;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.util.core.crypto.SecureKeys;
-import org.apache.brooklyn.util.crypto.SslTrustUtils;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.exceptions.RuntimeInterruptedException;
-import org.apache.brooklyn.util.jmx.jmxmp.JmxmpAgent;
-import org.apache.brooklyn.util.repeat.Repeater;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.java.JmxSupport;
-import brooklyn.entity.java.UsesJmx;
-
-import com.google.common.base.Preconditions;
-import com.google.common.base.Throwables;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-
-public class JmxHelper {
-
-    private static final Logger LOG = LoggerFactory.getLogger(JmxHelper.class);
-
-    public static final String JMX_URL_FORMAT = "service:jmx:rmi:///jndi/rmi://%s:%d/%s";
-    // first host:port may be ignored, so above is sufficient, but not sure
-    public static final String RMI_JMX_URL_FORMAT = "service:jmx:rmi://%s:%d/jndi/rmi://%s:%d/%s";
-    // jmxmp
-    public static final String JMXMP_URL_FORMAT = "service:jmx:jmxmp://%s:%d";
-    
-    // Tracks the MBeans we have failed to find, with a set keyed off the url
-    private static final Map<String, Set<ObjectName>> notFoundMBeansByUrl = Collections.synchronizedMap(new WeakHashMap<String, Set<ObjectName>>());
-
-    public static final Map<String, String> CLASSES = ImmutableMap.<String,String>builder()
-            .put("Integer", Integer.TYPE.getName())
-            .put("Long", Long.TYPE.getName())
-            .put("Boolean", Boolean.TYPE.getName())
-            .put("Byte", Byte.TYPE.getName())
-            .put("Character", Character.TYPE.getName())
-            .put("Double", Double.TYPE.getName())
-            .put("Float", Float.TYPE.getName())
-            .put("GStringImpl", String.class.getName())
-            .put("LinkedHashMap", Map.class.getName())
-            .put("TreeMap", Map.class.getName())
-            .put("HashMap", Map.class.getName())
-            .put("ConcurrentHashMap", Map.class.getName())
-            .put("TabularDataSupport", TabularData.class.getName())
-            .put("CompositeDataSupport", CompositeData.class.getName())
-            .build();
-
-    /** constructs a JMX URL suitable for connecting to the given entity, being smart about JMX/RMI vs JMXMP */
-    public static String toJmxUrl(EntityLocal entity) {
-        String url = entity.getAttribute(UsesJmx.JMX_URL);
-        if (url != null) {
-            return url;
-        } else {
-            new JmxSupport(entity, null).setJmxUrl();
-            url = entity.getAttribute(UsesJmx.JMX_URL);
-            return Preconditions.checkNotNull(url, "Could not find URL for "+entity);
-        }
-    }
-
-    /** constructs an RMI/JMX URL with the given inputs 
-     * (where the RMI Registry Port should be non-null, and at least one must be non-null) */
-    public static String toRmiJmxUrl(String host, Integer jmxRmiServerPort, Integer rmiRegistryPort, String context) {
-        if (rmiRegistryPort != null && rmiRegistryPort > 0) {
-            if (jmxRmiServerPort!=null && jmxRmiServerPort > 0 && jmxRmiServerPort!=rmiRegistryPort) {
-                // we have an explicit known JMX RMI server port (e.g. because we are using the agent),
-                // distinct from the RMI registry port
-                // (if the ports are the same, it is a short-hand, and don't use this syntax!)
-                return String.format(RMI_JMX_URL_FORMAT, host, jmxRmiServerPort, host, rmiRegistryPort, context);
-            }
-            return String.format(JMX_URL_FORMAT, host, rmiRegistryPort, context);
-        } else if (jmxRmiServerPort!=null && jmxRmiServerPort > 0) {
-            LOG.warn("No RMI registry port set for "+host+"; attempting to use JMX port for RMI lookup");
-            return String.format(JMX_URL_FORMAT, host, jmxRmiServerPort, context);
-        } else {
-            LOG.warn("No RMI/JMX details set for "+host+"; returning null");
-            return null;
-        }
-    }
-
-    /** constructs a JMXMP URL for connecting to the given host and port */
-    public static String toJmxmpUrl(String host, Integer jmxmpPort) {
-        return "service:jmx:jmxmp://"+host+(jmxmpPort!=null ? ":"+jmxmpPort : "");
-    }
-    
-    final EntityLocal entity;
-    final String url;
-    final String user;
-    final String password;
-
-    private volatile transient JMXConnector connector;
-    private volatile transient MBeanServerConnection connection;
-    private transient boolean triedConnecting;
-    private transient boolean failedReconnecting;
-    private transient long failedReconnectingTime;
-    private int minTimeBetweenReconnectAttempts = 1000;
-    private final AtomicBoolean terminated = new AtomicBoolean();
-    
-    // Tracks the MBeans we have failed to find for this JmsHelper's connection URL (so can log just once for each)
-    private final Set<ObjectName> notFoundMBeans;
-
-    public JmxHelper(EntityLocal entity) {
-        this(toJmxUrl(entity), entity, entity.getAttribute(UsesJmx.JMX_USER), entity.getAttribute(UsesJmx.JMX_PASSWORD));
-        
-        if (entity.getAttribute(UsesJmx.JMX_URL) == null) {
-            entity.setAttribute(UsesJmx.JMX_URL, url);
-        }
-    }
-    
-    // TODO split this in to two classes, one for entities, and one entity-neutral
-    // (simplifying set of constructors below)
-    
-    public JmxHelper(String url) {
-        this(url, null, null);
-    }
-
-    public JmxHelper(String url, String user, String password) {
-        this(url, null, user, password);
-    }
-    
-    public JmxHelper(String url, EntityLocal entity, String user, String password) {
-        this.url = url;
-        this.entity = entity;
-        this.user = user;
-        this.password = password;
-
-        synchronized (notFoundMBeansByUrl) {
-            Set<ObjectName> set = notFoundMBeansByUrl.get(url);
-            if (set == null) {
-                set = Collections.synchronizedSet(Collections.newSetFromMap(new WeakHashMap<ObjectName, Boolean>()));
-                notFoundMBeansByUrl.put(url, set);
-            }
-            notFoundMBeans = set;
-        }
-    }
-
-    public void setMinTimeBetweenReconnectAttempts(int val) {
-        minTimeBetweenReconnectAttempts = val;
-    }
-    
-    public String getUrl(){
-        return url;
-    }
-
-    // ============== connection related calls =======================
-
-    //for tesing purposes
-    protected MBeanServerConnection getConnection() {
-        return connection;
-    }
-
-    /**
-     * Checks if the JmxHelper is connected. Returned value could be stale as soon
-     * as it is received.
-     *
-     * This method is thread safe.
-     *
-     * @return true if connected, false otherwise.
-     */
-    public boolean isConnected() {
-        return connection!=null;
-    }
-
-    /**
-     * Reconnects. If it already is connected, it disconnects first.
-     *
-     * @throws IOException
-     */
-    public synchronized void reconnectWithRetryDampened() throws IOException {
-        // If we've already tried reconnecting very recently, don't try again immediately
-        if (failedReconnecting) {
-            long timeSince = (System.currentTimeMillis() - failedReconnectingTime);
-            if (timeSince < minTimeBetweenReconnectAttempts) {
-                String msg = "Not reconnecting to JMX at "+url+" because attempt failed "+Time.makeTimeStringRounded(timeSince)+" ago";
-                throw new IllegalStateException(msg);
-            }
-        }
-        
-        reconnect();
-    }
-    
-    public synchronized void reconnect() throws IOException {
-        disconnect();
-
-        try {
-            connect();
-            failedReconnecting = false;
-        } catch (Exception e) {
-            if (failedReconnecting) {
-                if (LOG.isDebugEnabled()) LOG.debug("unable to re-connect to JMX url (repeated failure): {}: {}", url, e);
-            } else {
-                LOG.debug("unable to re-connect to JMX url {} (rethrowing): {}", url, e);
-                failedReconnecting = true;
-            }
-            failedReconnectingTime = System.currentTimeMillis();
-            throw Throwables.propagate(e);
-        }
-    }
-
-    /** attempts to connect immediately */
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    public synchronized void connect() throws IOException {
-        if (terminated.get()) throw new IllegalStateException("JMX Helper "+this+" already terminated");
-        if (connection != null) return;
-
-        triedConnecting = true;
-        if (connector != null) connector.close();
-        JMXServiceURL serviceUrl = new JMXServiceURL(url);
-        Map env = getConnectionEnvVars();
-        try {
-            connector = JMXConnectorFactory.connect(serviceUrl, env);
-        } catch (NullPointerException npe) {
-            //some software -- eg WSO2 -- will throw an NPE exception if the JMX connection can't be created, instead of an IOException.
-            //this is a break of contract with the JMXConnectorFactory.connect method, so this code verifies if the NPE is
-            //thrown by a known offender (wso2) and if so replaces the bad exception by a new IOException.
-            //ideally WSO2 will fix this bug and we can remove this code.
-            boolean thrownByWso2 = npe.getStackTrace()[0].toString().contains("org.wso2.carbon.core.security.CarbonJMXAuthenticator.authenticate");
-            if (thrownByWso2) {
-                throw new IOException("Failed to connect to url "+url+". NullPointerException is thrown, but replaced by an IOException to fix a WSO2 JMX problem", npe);
-            } else {
-                throw npe;
-            }
-        } catch (IOException e) {
-            Exceptions.propagateIfFatal(e);
-            if (terminated.get()) {
-                throw new IllegalStateException("JMX Helper "+this+" already terminated", e);
-            } else {
-                throw e;
-            }
-        }
-        connection = connector.getMBeanServerConnection();
-        
-        if (terminated.get()) {
-            disconnectNow();
-            throw new IllegalStateException("JMX Helper "+this+" already terminated");
-        }
-    }
-
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    public Map getConnectionEnvVars() {
-        Map env = new LinkedHashMap();
-        
-        if (groovyTruth(user) && groovyTruth(password)) {
-            String[] creds = new String[] {user, password};
-            env.put(JMXConnector.CREDENTIALS, creds);
-        }
-        
-        if (entity!=null && groovyTruth(entity.getConfig(UsesJmx.JMX_SSL_ENABLED))) {
-            env.put("jmx.remote.profiles", JmxmpAgent.TLS_JMX_REMOTE_PROFILES);
-
-            PrivateKey key = entity.getConfig(UsesJmx.JMX_SSL_ACCESS_KEY);
-            Certificate cert = entity.getConfig(UsesJmx.JMX_SSL_ACCESS_CERT);
-            KeyStore ks = SecureKeys.newKeyStore();
-            try {
-                KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
-                if (key!=null) {
-                    ks.setKeyEntry("brooklyn-jmx-access", key, "".toCharArray(), new Certificate[] { cert });
-                }
-                kmf.init(ks, "".toCharArray());
-
-                TrustManager tms = 
-                        // TODO use root cert for trusting server
-                        //trustStore!=null ? SecureKeys.getTrustManager(trustStore) : 
-                        SslTrustUtils.TRUST_ALL;
-
-                SSLContext ctx = SSLContext.getInstance("TLSv1");
-                ctx.init(kmf.getKeyManagers(), new TrustManager[] { tms }, null);
-                SSLSocketFactory ssf = ctx.getSocketFactory(); 
-                env.put(JmxmpAgent.TLS_SOCKET_FACTORY_PROPERTY, ssf); 
-                
-            } catch (Exception e) {
-                LOG.warn("Error setting key "+key+" for "+entity+": "+e, e);
-            }
-        }
-        
-        return env;
-    }
-
-    /**
-     * Continuously attempts to connect for at least the indicated amount of time; or indefinitely if -1. This method
-     * is useful when you are not sure if the system you are trying to connect to already is up and running.
-     *
-     * This method doesn't throw an Exception, but returns true on success, false otherwise.
-     *
-     * TODO: What happens if already connected?
-     *
-     * @param timeoutMs
-     * @return
-     */
-    public boolean connect(long timeoutMs) {
-        if (LOG.isDebugEnabled()) LOG.debug("Connecting to JMX URL: {} ({})", url, ((timeoutMs == -1) ? "indefinitely" : timeoutMs+"ms timeout"));
-        long startMs = System.currentTimeMillis();
-        long endMs = (timeoutMs == -1) ? Long.MAX_VALUE : (startMs + timeoutMs);
-        long currentTime = startMs;
-        Throwable lastError = null;
-        int attempt = 0;
-        while (currentTime <= endMs) {
-            currentTime = System.currentTimeMillis();
-            if (attempt != 0) sleep(100); //sleep 100 to prevent thrashing and facilitate interruption
-            if (LOG.isTraceEnabled()) LOG.trace("trying connection to {} at time {}", url, currentTime);
-
-            try {
-                connect();
-                return true;
-            } catch (Exception e) {
-                Exceptions.propagateIfFatal(e);
-                if (!terminated.get() && shouldRetryOn(e)) {
-                    if (LOG.isDebugEnabled()) LOG.debug("Attempt {} failed connecting to {} ({})", new Object[] {attempt + 1, url, e.getMessage()});
-                    lastError = e;
-                } else {
-                    throw Exceptions.propagate(e);
-                }
-            }
-            attempt++;
-        }
-        LOG.warn("unable to connect to JMX url: "+url, lastError);
-        return false;
-    }
-
-    private boolean shouldRetryOn(Exception e) {
-        // Expect SecurityException, IOException, etc.
-        // But can also see things like javax.naming.ServiceUnavailableException with WSO2 app-servers.
-        // So let's not try to second guess strange behaviours that future entities will exhibit.
-        //
-        // However, if it was our request that was invalid then not worth retrying.
-        
-        if (e instanceof AttributeNotFoundException) return false;
-        if (e instanceof InstanceAlreadyExistsException) return false;
-        if (e instanceof InstanceNotFoundException) return false;
-        if (e instanceof InvalidAttributeValueException) return false;
-        if (e instanceof ListenerNotFoundException) return false;
-        if (e instanceof MalformedObjectNameException) return false;
-        if (e instanceof NotCompliantMBeanException) return false;
-        if (e instanceof InterruptedException) return false;
-        if (e instanceof RuntimeInterruptedException) return false;
-
-        return true;
-    }
-
-    /**
-     * A thread-safe version of {@link #disconnectNow()}.
-     *
-     * This method is threadsafe.
-     */
-    public synchronized void disconnect() {
-        disconnectNow();
-    }
-    
-    /**
-     * Disconnects, preventing subsequent connections to be made. Method doesn't throw an exception.
-     *
-     * Can safely be called if already disconnected.
-     *
-     * This method is not threadsafe, but will thus not block if 
-     * another thread is taking a long time for connections to timeout.
-     * 
-     * Any concurrent requests will likely get an IOException - see
-     * {@linkplain http://docs.oracle.com/javase/7/docs/api/javax/management/remote/JMXConnector.html#close()}.
-     * 
-     */
-    public void terminate() {
-        terminated.set(true);
-        disconnectNow();
-    }
-    
-    protected void disconnectNow() {
-        triedConnecting = false;
-        if (connector != null) {
-            if (LOG.isDebugEnabled()) LOG.debug("Disconnecting from JMX URL {}", url);
-            try {
-                connector.close();
-            } catch (Exception e) {
-                // close attempts to connect to close cleanly; and if it can't, it throws;
-                // often we disconnect as part of shutdown, even if the other side has already stopped --
-                // so swallow exceptions (no situations known where we need a clean closure on the remote side)
-                if (LOG.isDebugEnabled()) LOG.debug("Caught exception disconnecting from JMX at {} ({})", url, e.getMessage());
-                if (LOG.isTraceEnabled()) LOG.trace("Details for exception disconnecting JMX", e);
-            } finally {
-                connector = null;
-                connection = null;
-            }
-        }
-    }
-
-    /**
-     * Gets a usable MBeanServerConnection.
-     *
-     * Method is threadsafe.
-     *
-     * @returns the MBeanServerConnection
-     * @throws IllegalStateException if not connected.
-     */
-    private synchronized MBeanServerConnection getConnectionOrFail() {
-        if (isConnected())
-            return getConnection();
-
-        if (triedConnecting) {
-            throw new IllegalStateException("Failed to connect to JMX at "+url);
-        } else {
-            String msg = "Not connected (and not attempted to connect) to JMX at "+url+
-                    (failedReconnecting ? (" (last reconnect failure at "+ Time.makeDateString(failedReconnectingTime) + ")") : "");
-            throw new IllegalStateException(msg);
-        }
-    }
-
-    private <T> T invokeWithReconnect(Callable<T> task) {
-        try {
-            return task.call();
-        } catch (Exception e) {
-            if (shouldRetryOn(e)) {
-                try {
-                    reconnectWithRetryDampened();
-                    return task.call();
-                } catch (Exception e2) {
-                    throw Throwables.propagate(e2);
-                }
-            } else {
-                throw Throwables.propagate(e);
-            }
-        }
-    }
-
-    // ====================== query related calls =======================================
-
-    /**
-     * Converts from an object name pattern to a real object name, by querying with findMBean; 
-     * if no matching MBean can be found (or if more than one match found) then returns null.
-     * If the supplied object name is not a pattern then just returns that. If the 
-     */
-    public ObjectName toLiteralObjectName(ObjectName objectName) {
-        if (checkNotNull(objectName, "objectName").isPattern()) {
-            ObjectInstance bean = findMBean(objectName);    
-            return (bean != null) ? bean.getObjectName() : null;
-        } else {
-            return objectName;
-        }
-    }
-    
-    public Set<ObjectInstance> findMBeans(final ObjectName objectName) {
-        return invokeWithReconnect(new Callable<Set<ObjectInstance>>() {
-                public Set<ObjectInstance> call() throws Exception {
-                    return getConnectionOrFail().queryMBeans(objectName, null);
-                }});
-    }
-
-    public ObjectInstance findMBean(ObjectName objectName) {
-        Set<ObjectInstance> beans = findMBeans(objectName);
-        if (beans.size() == 1) {
-            notFoundMBeans.remove(objectName);
-            return Iterables.getOnlyElement(beans);
-        } else {
-            boolean changed = notFoundMBeans.add(objectName);
-
-            if (beans.size() > 1) {
-                if (changed) {
-                    LOG.warn("JMX object name query returned {} values for {} at {}; ignoring all",
-                            new Object[] {beans.size(), objectName.getCanonicalName(), url});
-                } else {
-                    if (LOG.isDebugEnabled()) LOG.debug("JMX object name query returned {} values for {} at {} (repeating); ignoring all", 
-                            new Object[] {beans.size(), objectName.getCanonicalName(), url});
-                }
-            } else {
-                if (changed) {
-                    LOG.warn("JMX object {} not found at {}", objectName.getCanonicalName(), url);
-                } else {
-                    if (LOG.isDebugEnabled()) LOG.debug("JMX object {} not found at {} (repeating)", objectName.getCanonicalName(), url);
-                }
-            }
-            return null;
-        }
-    }
-
-    public Set<ObjectInstance> doesMBeanExistsEventually(final ObjectName objectName, Duration timeout) {
-        return doesMBeanExistsEventually(objectName, timeout.toMilliseconds(), TimeUnit.MILLISECONDS);
-    }
-    public Set<ObjectInstance> doesMBeanExistsEventually(final ObjectName objectName, TimeDuration timeout) {
-        return doesMBeanExistsEventually(objectName, timeout.toMilliseconds(), TimeUnit.MILLISECONDS);
-    }
-    
-    public Set<ObjectInstance> doesMBeanExistsEventually(final ObjectName objectName, long timeoutMillis) {
-        return doesMBeanExistsEventually(objectName, timeoutMillis, TimeUnit.MILLISECONDS);
-    }
-    
-    public Set<ObjectInstance> doesMBeanExistsEventually(String objectName, Duration timeout) {
-        return doesMBeanExistsEventually(createObjectName(objectName), timeout);
-    }
-    public Set<ObjectInstance> doesMBeanExistsEventually(String objectName, TimeDuration timeout) {
-        return doesMBeanExistsEventually(createObjectName(objectName), timeout);
-    }
-    
-    public Set<ObjectInstance> doesMBeanExistsEventually(String objectName, long timeout, TimeUnit timeUnit) {
-        return doesMBeanExistsEventually(createObjectName(objectName), timeout, timeUnit);
-    }
-
-    /** returns set of beans found, with retry, empty set if none after timeout */
-    public Set<ObjectInstance> doesMBeanExistsEventually(final ObjectName objectName, long timeout, TimeUnit timeUnit) {
-        final long timeoutMillis = timeUnit.toMillis(timeout);
-        final AtomicReference<Set<ObjectInstance>> beans = new AtomicReference<Set<ObjectInstance>>(ImmutableSet.<ObjectInstance>of());
-        try {
-            Repeater.create("Wait for "+objectName)
-                    .limitTimeTo(timeout, timeUnit)
-                    .every(500, TimeUnit.MILLISECONDS)
-                    .until(new Callable<Boolean>() {
-                            public Boolean call() {
-                                connect(timeoutMillis);
-                                beans.set(findMBeans(objectName));
-                                return !beans.get().isEmpty();
-                            }})
-                    .rethrowException()
-                    .run();
-            return beans.get();
-        } catch (Exception e) {
-            throw Exceptions.propagate(e);
-        }
-    }
-
-    public void assertMBeanExistsEventually(ObjectName objectName, Duration timeout) {
-        assertMBeanExistsEventually(objectName, timeout.toMilliseconds(), TimeUnit.MILLISECONDS);
-    }
-    public void assertMBeanExistsEventually(ObjectName objectName, TimeDuration timeout) {
-        assertMBeanExistsEventually(objectName, timeout.toMilliseconds(), TimeUnit.MILLISECONDS);
-    }
-    
-    public void assertMBeanExistsEventually(ObjectName objectName, long timeoutMillis) {
-        assertMBeanExistsEventually(objectName, timeoutMillis, TimeUnit.MILLISECONDS);
-    }
-    
-    public void assertMBeanExistsEventually(ObjectName objectName, long timeout, TimeUnit timeUnit) {
-        Set<ObjectInstance> beans = doesMBeanExistsEventually(objectName, timeout, timeUnit);
-        if (beans.size() != 1) {
-            throw new IllegalStateException("MBean "+objectName+" not found within "+timeout+
-                    (beans.size() > 1 ? "; found multiple matches: "+beans : ""));
-        }
-    }
-
-    /**
-     * Returns a specific attribute for a JMX {@link ObjectName}.
-     */
-    public Object getAttribute(ObjectName objectName, final String attribute) {
-        final ObjectName realObjectName = toLiteralObjectName(objectName);
-        
-        if (realObjectName != null) {
-            Object result = invokeWithReconnect(new Callable<Object>() {
-                    public Object call() throws Exception {
-                        return getConnectionOrFail().getAttribute(realObjectName, attribute);
-                    }});
-
-            if (LOG.isTraceEnabled()) LOG.trace("From {}, for jmx attribute {}.{}, got value {}", new Object[] {url, objectName.getCanonicalName(), attribute, result});
-            return result;
-        } else {
-            return null;
-        }
-    }
-
-    public void setAttribute(String objectName, String attribute, Object val) {
-        setAttribute(createObjectName(objectName), attribute, val);
-    }
-
-    public void setAttribute(ObjectName objectName, final String attribute, final Object val) {
-        final ObjectName realObjectName = toLiteralObjectName(objectName);
-        
-        if (realObjectName != null) {
-            invokeWithReconnect(new Callable<Void>() {
-                    public Void call() throws Exception {
-                        getConnectionOrFail().setAttribute(realObjectName, new javax.management.Attribute(attribute, val));
-                        return null;
-                    }});
-            if (LOG.isTraceEnabled()) LOG.trace("From {}, for jmx attribute {}.{}, set value {}", new Object[] {url, objectName.getCanonicalName(), attribute, val});
-        } else {
-            if (LOG.isDebugEnabled()) LOG.debug("From {}, cannot set attribute {}.{}, because mbean not found", new Object[] {url, objectName.getCanonicalName(), attribute});
-        }
-    }
-
-    /** @see #operation(ObjectName, String, Object ...) */
-    public Object operation(String objectName, String method, Object... arguments) {
-        return operation(createObjectName(objectName), method, arguments);
-    }
-
-    /**
-     * Executes an operation on a JMX {@link ObjectName}.
-     */
-    public Object operation(ObjectName objectName, final String method, final Object... arguments) {
-        final ObjectName realObjectName = toLiteralObjectName(objectName);
-        final String[] signature = new String[arguments.length];
-        for (int i = 0; i < arguments.length; i++) {
-            Class<?> clazz = arguments[i].getClass();
-            signature[i] = (CLASSES.containsKey(clazz.getSimpleName()) ? CLASSES.get(clazz.getSimpleName()) : clazz.getName());
-        }
-        
-        Object result = invokeWithReconnect(new Callable<Object>() {
-                public Object call() throws Exception {
-                    return getConnectionOrFail().invoke(realObjectName, method, arguments, signature);
-                }});
-
-        if (LOG.isTraceEnabled()) LOG.trace("From {}, for jmx operation {}.{}({}), got value {}", new Object[] {url, realObjectName.getCanonicalName(), method, Arrays.asList(arguments), 
-                result});
-        return result;
-    }
-
-    public void addNotificationListener(String objectName, NotificationListener listener) {
-        addNotificationListener(createObjectName(objectName), listener, null);
-    }
-    
-    public void addNotificationListener(String objectName, NotificationListener listener, NotificationFilter filter) {
-        addNotificationListener(createObjectName(objectName), listener, filter);
-    }
-
-    public void addNotificationListener(ObjectName objectName, NotificationListener listener) {
-        addNotificationListener(objectName, listener, null);
-    }
-    
-    public void addNotificationListener(final ObjectName objectName, final NotificationListener listener, final NotificationFilter filter) {
-        invokeWithReconnect(new Callable<Void>() {
-                public Void call() throws Exception {
-                    getConnectionOrFail().addNotificationListener(objectName, listener, filter, null);
-                    return null;
-                }});
-    }
-
-    public void removeNotificationListener(String objectName, NotificationListener listener) {
-        removeNotificationListener(createObjectName(objectName), listener);
-    }
-
-    public void removeNotificationListener(final ObjectName objectName, final NotificationListener listener) {
-        removeNotificationListener(objectName, listener, null);
-    }
-    
-    public void removeNotificationListener(final ObjectName objectName, final NotificationListener listener, final NotificationFilter filter) {
-        if (isConnected()) invokeWithReconnect(new Callable<Void>() {
-                public Void call() throws Exception {
-                    getConnectionOrFail().removeNotificationListener(objectName, listener, filter, null);
-                    return null;
-                }});
-    }
-
-    public <M> M getProxyObject(String objectName, Class<M> mbeanInterface) {
-        return getProxyObject(createObjectName(objectName), mbeanInterface);
-    }
-
-    public <M> M getProxyObject(ObjectName objectName, Class<M> mbeanInterface) {
-        MBeanServerConnection connection = getConnectionOrFail();
-        return JMX.newMBeanProxy(connection, objectName, mbeanInterface, false);
-    }
-
-    public static ObjectName createObjectName(String name) {
-        try {
-            return new ObjectName(name);
-        } catch (MalformedObjectNameException e) {
-            throw Throwables.propagate(e);
-        }
-    }
-    
-    private static void sleep(long sleepTimeMillis) {
-        try {
-            Thread.sleep(sleepTimeMillis);
-        } catch (InterruptedException e) {
-            throw new RuntimeInterruptedException(e);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/event/feed/jmx/JmxNotificationFilters.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/event/feed/jmx/JmxNotificationFilters.java b/software/base/src/main/java/brooklyn/event/feed/jmx/JmxNotificationFilters.java
deleted file mode 100644
index 8cf5d62..0000000
--- a/software/base/src/main/java/brooklyn/event/feed/jmx/JmxNotificationFilters.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.event.feed.jmx;
-
-import javax.management.Notification;
-import javax.management.NotificationFilter;
-import javax.management.NotificationFilterSupport;
-
-public class JmxNotificationFilters {
-
-    private JmxNotificationFilters() {} // instead use static utility methods
-    
-    /**
-     * Matches the given notification type.
-     * @see {@link NotificationFilterSupport#enableType(String)}
-     */
-    public static NotificationFilter matchesType(String type) {
-        return matchesTypes(type);
-    }
-
-    /**
-     * Matches any of the given notification types.
-     * @see {@link NotificationFilterSupport#enableType(String)}
-     */
-    public static NotificationFilter matchesTypes(String... types) {
-        NotificationFilterSupport result = new NotificationFilterSupport();
-        for (String type : types) {
-            result.enableType(type);
-        }
-        return result;
-    }
-
-    /**
-     * @deprecated since 0.6.0;
-     *             only works if this brooklyn class is on the classpath of the JVM that your 
-     *             subscribing to notifications on (because it tries to push the filter instance
-     *             to that JVM). So of very limited use in real-world java processes to be managed.
-     *             Therefore this will be deleted to avoid people hitting this surprising behaviour.
-     */
-    @SuppressWarnings("serial")
-    public static NotificationFilter matchesTypeRegex(final String typeRegex) {
-        return new NotificationFilter() {
-            @Override public boolean isNotificationEnabled(Notification notif) {
-                return notif.getType().matches(typeRegex);
-            }
-        };
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/event/feed/jmx/JmxNotificationSubscriptionConfig.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/event/feed/jmx/JmxNotificationSubscriptionConfig.java b/software/base/src/main/java/brooklyn/event/feed/jmx/JmxNotificationSubscriptionConfig.java
deleted file mode 100644
index b27ffef..0000000
--- a/software/base/src/main/java/brooklyn/event/feed/jmx/JmxNotificationSubscriptionConfig.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.event.feed.jmx;
-
-import javax.management.MalformedObjectNameException;
-import javax.management.Notification;
-import javax.management.NotificationFilter;
-import javax.management.ObjectName;
-
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.sensor.feed.FeedConfig;
-import org.apache.brooklyn.util.collections.MutableList;
-
-import com.google.common.base.Function;
-import com.google.common.base.Functions;
-
-public class JmxNotificationSubscriptionConfig<T> extends FeedConfig<javax.management.Notification, T, JmxNotificationSubscriptionConfig<T>>{
-
-    private ObjectName objectName;
-    private NotificationFilter notificationFilter;
-    private Function<Notification, T> onNotification;
-
-    @SuppressWarnings({ "unchecked", "rawtypes" })
-    public JmxNotificationSubscriptionConfig(AttributeSensor<T> sensor) {
-        super(sensor);
-        onSuccess((Function)Functions.identity());
-    }
-
-    public JmxNotificationSubscriptionConfig(JmxNotificationSubscriptionConfig<T> other) {
-        super(other);
-        this.objectName = other.objectName;
-        this.notificationFilter = other.notificationFilter;
-        this.onNotification = other.onNotification;
-    }
-
-    public ObjectName getObjectName() {
-        return objectName;
-    }
-
-    public NotificationFilter getNotificationFilter() {
-        return notificationFilter;
-    }
-    
-    public Function<Notification, T> getOnNotification() {
-        return onNotification;
-    }
-    
-    public JmxNotificationSubscriptionConfig<T> objectName(ObjectName val) {
-        this.objectName = val; return this;
-    }
-    
-    public JmxNotificationSubscriptionConfig<T> objectName(String val) {
-        try {
-            return objectName(new ObjectName(val));
-        } catch (MalformedObjectNameException e) {
-            throw new IllegalArgumentException("Invalid object name ("+val+")", e);
-        }
-    }
-    
-    public JmxNotificationSubscriptionConfig<T> notificationFilter(NotificationFilter val) {
-        this.notificationFilter = val; return this;
-    }
-
-    public JmxNotificationSubscriptionConfig<T> onNotification(Function<Notification,T> val) {
-        this.onNotification = val; return this;
-    }
-
-    @Override
-    protected Object toStringPollSource() {
-        return objectName;
-    }
-
-    @Override
-    protected MutableList<Object> equalsFields() {
-        return super.equalsFields()
-            .appendIfNotNull(notificationFilter).appendIfNotNull(onNotification);
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/event/feed/jmx/JmxOperationPollConfig.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/event/feed/jmx/JmxOperationPollConfig.java b/software/base/src/main/java/brooklyn/event/feed/jmx/JmxOperationPollConfig.java
deleted file mode 100644
index 169f330..0000000
--- a/software/base/src/main/java/brooklyn/event/feed/jmx/JmxOperationPollConfig.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.event.feed.jmx;
-
-import java.util.Collections;
-import java.util.List;
-
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
-
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.sensor.feed.PollConfig;
-
-import com.google.common.base.Function;
-import com.google.common.base.Functions;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-
-public class JmxOperationPollConfig<T> extends PollConfig<Object, T, JmxOperationPollConfig<T>>{
-
-    private ObjectName objectName;
-    private String operationName;
-    private List<String> signature = Collections.emptyList();
-    private List<?> params = Collections.emptyList();
-
-    @SuppressWarnings({ "unchecked", "rawtypes" })
-    public JmxOperationPollConfig(AttributeSensor<T> sensor) {
-        super(sensor);
-        onSuccess((Function)Functions.identity());
-    }
-
-    public JmxOperationPollConfig(JmxOperationPollConfig<T> other) {
-        super(other);
-        this.objectName = other.objectName;
-        this.operationName = other.operationName;
-        this.signature = other.signature != null ? ImmutableList.copyOf(other.signature) : null;
-        this.params = other.params != null ? ImmutableList.copyOf(other.params) : null;
-    }
-
-    public ObjectName getObjectName() {
-        return objectName;
-    }
-    
-    public String getOperationName() {
-        return operationName;
-    }
-    
-    public List<String> getSignature() {
-        return signature;
-    }
-    
-    public List<?> getParams() {
-        return params;
-    }
-    
-    public JmxOperationPollConfig<T> objectName(ObjectName val) {
-        this.objectName = val; return this;
-    }
-    
-    public JmxOperationPollConfig<T> objectName(String val) {
-        try {
-            return objectName(new ObjectName(val));
-        } catch (MalformedObjectNameException e) {
-            throw new IllegalArgumentException("Invalid object name ("+val+")", e);
-        }
-    }
-
-    public JmxOperationPollConfig<T> operationName(String val) {
-        this.operationName = val; return this;
-    }
-    
-    public JmxOperationPollConfig<T> operationSignature(List<String> val) {
-        this.signature = val; return this;
-    }
-    
-    public JmxOperationPollConfig<T> operationParams(List<?> val) {
-        this.params = val; return this;
-    }
-
-    public List<?> buildOperationIdentity() {
-        // FIXME Have a build() method for ensuring signature is set, and making class subsequently immutable?
-        return ImmutableList.of(operationName, buildSignature(), params);
-    }
-    
-    private List<String> buildSignature() {
-        if (signature != null && signature.size() == params.size()) {
-            return signature;
-        } else {
-            List<String> derivedSignature = Lists.newLinkedList();
-            for (Object param : params) {
-                Class<?> clazz = (param != null) ? param.getClass() : null;
-                String clazzName = (clazz != null) ? 
-                         (JmxHelper.CLASSES.containsKey(clazz.getSimpleName()) ? 
-                                 JmxHelper.CLASSES.get(clazz.getSimpleName()) : clazz.getName()) : 
-                         Object.class.getName();
-                derivedSignature.add(clazzName);
-            }
-            return derivedSignature;
-        }
-    }
-
-    @Override protected String toStringBaseName() { return "jmx"; }
-    @Override protected String toStringPollSource() { return objectName+":"+operationName+(params!=null ? params : "[]"); }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/event/feed/jmx/JmxValueFunctions.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/event/feed/jmx/JmxValueFunctions.java b/software/base/src/main/java/brooklyn/event/feed/jmx/JmxValueFunctions.java
deleted file mode 100644
index 0b61b42..0000000
--- a/software/base/src/main/java/brooklyn/event/feed/jmx/JmxValueFunctions.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.event.feed.jmx;
-
-import java.util.List;
-import java.util.Map;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.TabularData;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Function;
-import com.google.common.collect.Maps;
-
-public class JmxValueFunctions {
-
-    private static final Logger log = LoggerFactory.getLogger(JmxValueFunctions.class);
-    
-    /**
-     * @return a closure that converts a TabularDataSupport to a map.
-     */
-    public static Function<TabularData, Map> tabularDataToMap() {
-        return new Function<TabularData, Map>() {
-            @Override public Map apply(TabularData input) {
-                return tabularDataToMap(input);
-            }};
-    }
-
-    public static Function<TabularData, Map> tabularDataToMapOfMaps() {
-        return new Function<TabularData, Map>() {
-            @Override public Map apply(TabularData input) {
-                return tabularDataToMapOfMaps(input);
-            }};
-    }
-
-    public static Function<CompositeData,Map> compositeDataToMap() {
-        return new Function<CompositeData, Map>() {
-            @Override public Map apply(CompositeData input) {
-                return compositeDataToMap(input);
-            }};
-    }
-    
-    public static Map tabularDataToMap(TabularData table) {
-        Map<String, Object> result = Maps.newLinkedHashMap();
-        for (Object entry : table.values()) {
-            CompositeData data = (CompositeData) entry; //.getValue()
-            for (String key : data.getCompositeType().keySet()) {
-                Object old = result.put(key, data.get(key));
-                if (old != null) {
-                    log.warn("tablularDataToMap has overwritten key {}", key);
-                }
-            }
-        }
-        return result;
-    }
-    
-    public static Map<List<?>, Map<String, Object>> tabularDataToMapOfMaps(TabularData table) {
-        Map<List<?>, Map<String, Object>> result = Maps.newLinkedHashMap();
-        for (Object k : table.keySet()) {
-            final Object[] kValues = ((List<?>)k).toArray();
-            CompositeData v = (CompositeData) table.get(kValues);
-            result.put((List<?>)k, compositeDataToMap(v));
-        }
-        return result;
-    }
-    
-    public static Map<String, Object> compositeDataToMap(CompositeData data) {
-        Map<String, Object> result = Maps.newLinkedHashMap();
-        for (String key : data.getCompositeType().keySet()) {
-            Object old = result.put(key, data.get(key));
-            if (old != null) {
-                log.warn("compositeDataToMap has overwritten key {}", key);
-            }
-        }
-        return result;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynCluster.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynCluster.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynCluster.java
new file mode 100644
index 0000000..daf7369
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynCluster.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.entity.brooklynnode.effector.BrooklynNodeUpgradeEffectorBody;
+import org.apache.brooklyn.entity.group.DynamicCluster;
+import org.apache.brooklyn.sensor.core.Sensors;
+
+@ImplementedBy(BrooklynClusterImpl.class)
+public interface BrooklynCluster extends DynamicCluster {
+    
+    ConfigKey<EntitySpec<?>> MEMBER_SPEC = ConfigKeys.newConfigKeyWithDefault(DynamicCluster.MEMBER_SPEC, 
+            EntitySpec.create(BrooklynNode.class));
+    
+    AttributeSensor<BrooklynNode> MASTER_NODE = Sensors.newSensor(
+            BrooklynNode.class, "brooklyncluster.master", "Pointer to the child node with MASTER state in the cluster");
+
+    interface SelectMasterEffector {
+        ConfigKey<String> NEW_MASTER_ID = ConfigKeys.newStringConfigKey(
+                "brooklyncluster.new_master_id", "The ID of the node to become master", null);
+        Effector<Void> SELECT_MASTER = Effectors.effector(Void.class, "selectMaster")
+                .description("Select a new master in the cluster")
+                .parameter(NEW_MASTER_ID)
+                .buildAbstract();
+    }
+
+    Effector<Void> SELECT_MASTER = SelectMasterEffector.SELECT_MASTER;
+
+    interface UpgradeClusterEffector {
+        ConfigKey<String> DOWNLOAD_URL = BrooklynNode.DOWNLOAD_URL.getConfigKey();
+        ConfigKey<Map<String,Object>> EXTRA_CONFIG = BrooklynNodeUpgradeEffectorBody.EXTRA_CONFIG;
+
+        Effector<Void> UPGRADE_CLUSTER = Effectors.effector(Void.class, "upgradeCluster")
+                .description("Upgrade the cluster with new distribution version, "
+                    + "by provisioning new nodes with the new version, failing over, "
+                    + "and then deprovisioning the original nodes")
+                .parameter(BrooklynNode.SUGGESTED_VERSION)
+                .parameter(DOWNLOAD_URL)
+                .parameter(EXTRA_CONFIG)
+                .buildAbstract();
+    }
+
+    Effector<Void> UPGRADE_CLUSTER = UpgradeClusterEffector.UPGRADE_CLUSTER;
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynClusterImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynClusterImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynClusterImpl.java
new file mode 100644
index 0000000..61b0ba5
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynClusterImpl.java
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import java.util.Collection;
+import java.util.concurrent.Callable;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
+import org.apache.brooklyn.entity.brooklynnode.effector.BrooklynClusterUpgradeEffectorBody;
+import org.apache.brooklyn.entity.brooklynnode.effector.SelectMasterEffectorBody;
+import org.apache.brooklyn.entity.core.EntityFunctions;
+import org.apache.brooklyn.entity.core.EntityPredicates;
+import org.apache.brooklyn.entity.group.DynamicClusterImpl;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic.ServiceProblemsLogic;
+import org.apache.brooklyn.sensor.enricher.Enrichers;
+import org.apache.brooklyn.sensor.feed.function.FunctionFeed;
+import org.apache.brooklyn.sensor.feed.function.FunctionPollConfig;
+import org.apache.brooklyn.util.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.Iterables;
+
+public class BrooklynClusterImpl extends DynamicClusterImpl implements BrooklynCluster {
+
+    private static final String MSG_NO_MASTER = "No master node in cluster";
+    private static final String MSG_TOO_MANY_MASTERS = "Too many master nodes in cluster";
+
+    private static final Logger LOG = LoggerFactory.getLogger(BrooklynClusterImpl.class);
+
+    // TODO should we set a default MEMBER_SPEC ?  difficult though because we'd need to set a password
+
+    @Override
+    public void init() {
+        super.init();
+        getMutableEntityType().addEffector(SelectMasterEffectorBody.SELECT_MASTER);
+        getMutableEntityType().addEffector(BrooklynClusterUpgradeEffectorBody.UPGRADE_CLUSTER);
+
+        ServiceProblemsLogic.updateProblemsIndicator(this, MASTER_NODE, MSG_NO_MASTER);
+        addFeed(FunctionFeed.builder()
+                .entity(this)
+                .poll(new FunctionPollConfig<Object, BrooklynNode>(MASTER_NODE)
+                        .period(Duration.ONE_SECOND)
+                        .callable(new MasterChildFinder()))
+                .build());
+        
+        addEnricher( Enrichers.builder().transforming(MASTER_NODE)
+            .uniqueTag("master-node-web-uri")
+            .publishing(BrooklynNode.WEB_CONSOLE_URI)
+            .computing(EntityFunctions.attribute(BrooklynNode.WEB_CONSOLE_URI))
+            .build() );
+    }
+
+    private final class MasterChildFinder implements Callable<BrooklynNode> {
+        @Override
+        public BrooklynNode call() throws Exception {
+            return findMasterChild();
+        }
+    }
+
+    BrooklynNode findMasterChild() {
+        Collection<Entity> masters = FluentIterable.from(getMembers())
+                .filter(EntityPredicates.attributeEqualTo(BrooklynNode.MANAGEMENT_NODE_STATE, ManagementNodeState.MASTER))
+                .toList();
+
+        if (masters.size() == 0) {
+            ServiceProblemsLogic.updateProblemsIndicator(this, MASTER_NODE, MSG_NO_MASTER);
+            return null;
+            
+        } else if (masters.size() == 1) {
+            ServiceStateLogic.ServiceProblemsLogic.clearProblemsIndicator(this, MASTER_NODE);
+            return (BrooklynNode)Iterables.getOnlyElement(masters);
+            
+        } else if (masters.size() == 2) {
+            LOG.warn("Two masters detected, probably a handover just occured: " + masters);
+
+            //Don't clearProblemsIndicator - if there were no masters previously why have two now.
+            //But also don't set it. Probably hit a window where we have a new master
+            //its BrooklynNode picked it up, but the BrooklynNode
+            //for the old master hasn't refreshed its state yet.
+            //Just pick one of them, should sort itself out in next update.
+            
+            //TODO Do set such indicator if this continues for an extended period of time
+            
+            return (BrooklynNode)masters.iterator().next();
+            
+        } else {
+            ServiceProblemsLogic.updateProblemsIndicator(this, MASTER_NODE, MSG_TOO_MANY_MASTERS);
+            String msg = "Multiple (>=3) master nodes in cluster: " + masters;
+            LOG.error(msg);
+            throw new IllegalStateException(msg);
+            
+        }
+    }
+
+}


[50/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/LegacyAbstractLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/LegacyAbstractLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/LegacyAbstractLocationTest.java
deleted file mode 100644
index 551d18c..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/LegacyAbstractLocationTest.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNotEquals;
-import static org.testng.Assert.assertTrue;
-
-import java.util.Collections;
-import java.util.Map;
-
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-
-public class LegacyAbstractLocationTest {
-
-    private static class ConcreteLocation extends AbstractLocation {
-        @SetFromFlag(defaultVal="mydefault")
-        String myfield;
-
-        public ConcreteLocation() {
-            super();
-        }
-
-        public ConcreteLocation(Map properties) {
-            super(properties);
-        }
-    }
-
-    @AfterMethod(alwaysRun = true)
-    public void tearDown(){
-        // nothing to tear down; did not create a management context
-    }
-
-    @Test
-    public void testEquals() {
-        AbstractLocation l1 = new ConcreteLocation(MutableMap.of("id", "1", "name", "bob"));
-        AbstractLocation l2 = new ConcreteLocation(MutableMap.of("id", "1", "name", "frank"));
-        AbstractLocation l3 = new ConcreteLocation(MutableMap.of("id", "2", "name", "frank"));
-        assertEquals(l1, l2);
-        assertNotEquals(l2, l3);
-    }
-
-    @Test
-    public void nullNameAndParentLocationIsAcceptable() {
-        AbstractLocation location = new ConcreteLocation(MutableMap.of("name", null, "parentLocation", null));
-        assertEquals(location.getDisplayName(), null);
-        assertEquals(location.getParent(), null);
-    }
-
-    @Test
-    public void testSettingParentLocation() {
-        AbstractLocation location = new ConcreteLocation();
-        AbstractLocation locationSub = new ConcreteLocation();
-        locationSub.setParent(location);
-        
-        assertEquals(ImmutableList.copyOf(location.getChildren()), ImmutableList.of(locationSub));
-        assertEquals(locationSub.getParent(), location);
-    }
-
-    @Test
-    public void testClearingParentLocation() {
-        AbstractLocation location = new ConcreteLocation();
-        AbstractLocation locationSub = new ConcreteLocation();
-        locationSub.setParent(location);
-        
-        locationSub.setParent(null);
-        assertEquals(ImmutableList.copyOf(location.getChildren()), Collections.emptyList());
-        assertEquals(locationSub.getParent(), null);
-    }
-    
-    @Test
-    public void testContainsLocation() {
-        AbstractLocation location = new ConcreteLocation();
-        AbstractLocation locationSub = new ConcreteLocation();
-        locationSub.setParent(location);
-        
-        assertTrue(location.containsLocation(location));
-        assertTrue(location.containsLocation(locationSub));
-        assertFalse(locationSub.containsLocation(location));
-    }
-
-
-    @Test
-    public void queryingNameReturnsNameGivenInConstructor() {
-        String name = "Outer Mongolia";
-        AbstractLocation location = new ConcreteLocation(MutableMap.of("name", "Outer Mongolia"));
-        assertEquals(location.getDisplayName(), name);;
-    }
-
-    @Test
-    public void constructorParentLocationReturnsExpectedLocation() {
-        AbstractLocation parent = new ConcreteLocation(MutableMap.of("name", "Middle Earth"));
-        AbstractLocation child = new ConcreteLocation(MutableMap.of("name", "The Shire", "parentLocation", parent));
-        assertEquals(child.getParent(), parent);
-        assertEquals(ImmutableList.copyOf(parent.getChildren()), ImmutableList.of(child));
-    }
-
-    @Test
-    public void setParentLocationReturnsExpectedLocation() {
-        AbstractLocation parent = new ConcreteLocation(MutableMap.of("name", "Middle Earth"));
-        AbstractLocation child = new ConcreteLocation(MutableMap.of("name", "The Shire"));
-        child.setParent(parent);
-        assertEquals(child.getParent(), parent);
-        assertEquals(ImmutableList.copyOf(parent.getChildren()), ImmutableList.of(child));
-    }
-    
-    @Test
-    public void testAddChildToParentLocationReturnsExpectedLocation() {
-        AbstractLocation parent = new ConcreteLocation(MutableMap.of("id", "1"));
-        AbstractLocation child = new ConcreteLocation(MutableMap.of("id", "2"));
-        parent.addChild(child);
-        assertEquals(child.getParent(), parent);
-        assertEquals(ImmutableList.copyOf(parent.getChildren()), ImmutableList.of(child));
-    }
-
-    @Test
-    public void testFieldSetFromFlag() {
-        ConcreteLocation loc = new ConcreteLocation(MutableMap.of("myfield", "myval"));
-        assertEquals(loc.myfield, "myval");
-    }
-    
-    @Test
-    public void testFieldSetFromFlagUsesDefault() {
-        ConcreteLocation loc = new ConcreteLocation();
-        assertEquals(loc.myfield, "mydefault");
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/LocalhostLocationResolverTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/LocalhostLocationResolverTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/LocalhostLocationResolverTest.java
deleted file mode 100644
index 6ecd0f5..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/LocalhostLocationResolverTest.java
+++ /dev/null
@@ -1,264 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
-
-import java.util.List;
-import java.util.Map;
-import java.util.NoSuchElementException;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.util.text.StringEscapes.JavaStringEscapes;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-
-public class LocalhostLocationResolverTest {
-
-    private BrooklynProperties brooklynProperties;
-    private LocalManagementContext managementContext;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        managementContext = LocalManagementContextForTests.newInstance();
-        brooklynProperties = managementContext.getBrooklynProperties();
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (managementContext != null) Entities.destroyAll(managementContext);
-    }
-    
-    @Test
-    public void testTakesLocalhostScopedProperties() {
-        brooklynProperties.put("brooklyn.location.localhost.privateKeyFile", "myprivatekeyfile");
-        brooklynProperties.put("brooklyn.location.localhost.publicKeyFile", "mypublickeyfile");
-        brooklynProperties.put("brooklyn.location.localhost.privateKeyData", "myprivateKeyData");
-        brooklynProperties.put("brooklyn.location.localhost.publicKeyData", "myPublicKeyData");
-        brooklynProperties.put("brooklyn.location.localhost.privateKeyPassphrase", "myprivateKeyPassphrase");
-
-        Map<String, Object> conf = resolve("localhost").config().getBag().getAllConfig();
-        
-        assertEquals(conf.get("privateKeyFile"), "myprivatekeyfile");
-        assertEquals(conf.get("publicKeyFile"), "mypublickeyfile");
-        assertEquals(conf.get("privateKeyData"), "myprivateKeyData");
-        assertEquals(conf.get("publicKeyData"), "myPublicKeyData");
-        assertEquals(conf.get("privateKeyPassphrase"), "myprivateKeyPassphrase");
-    }
-
-    @Test
-    public void testTakesLocalhostDeprecatedScopedProperties() {
-        brooklynProperties.put("brooklyn.localhost.privateKeyFile", "myprivatekeyfile");
-        brooklynProperties.put("brooklyn.localhost.publicKeyFile", "mypublickeyfile");
-        brooklynProperties.put("brooklyn.localhost.privateKeyData", "myprivateKeyData");
-        brooklynProperties.put("brooklyn.localhost.publicKeyData", "myPublicKeyData");
-        brooklynProperties.put("brooklyn.localhost.privateKeyPassphrase", "myprivateKeyPassphrase");
-
-        Map<String, Object> conf = resolve("localhost").config().getBag().getAllConfig();
-        
-        assertEquals(conf.get("privateKeyFile"), "myprivatekeyfile");
-        assertEquals(conf.get("publicKeyFile"), "mypublickeyfile");
-        assertEquals(conf.get("privateKeyData"), "myprivateKeyData");
-        assertEquals(conf.get("publicKeyData"), "myPublicKeyData");
-        assertEquals(conf.get("privateKeyPassphrase"), "myprivateKeyPassphrase");
-    }
-
-    @Test
-    public void testTakesDeprecatedProperties() {
-        brooklynProperties.put("brooklyn.localhost.private-key-file", "myprivatekeyfile");
-        brooklynProperties.put("brooklyn.localhost.public-key-file", "mypublickeyfile");
-        brooklynProperties.put("brooklyn.localhost.private-key-data", "myprivateKeyData");
-        brooklynProperties.put("brooklyn.localhost.public-key-data", "myPublicKeyData");
-        brooklynProperties.put("brooklyn.localhost.private-key-passphrase", "myprivateKeyPassphrase");
-        Map<String, Object> conf = resolve("localhost").config().getBag().getAllConfig();
-        
-        assertEquals(conf.get("privateKeyFile"), "myprivatekeyfile");
-        assertEquals(conf.get("publicKeyFile"), "mypublickeyfile");
-        assertEquals(conf.get("privateKeyData"), "myprivateKeyData");
-        assertEquals(conf.get("publicKeyData"), "myPublicKeyData");
-        assertEquals(conf.get("privateKeyPassphrase"), "myprivateKeyPassphrase");
-    }
-    
-    @Test
-    public void testPropertyScopePrescedence() {
-        brooklynProperties.put("brooklyn.location.named.mynamed", "localhost");
-        
-        // prefer those in "named" over everything else
-        brooklynProperties.put("brooklyn.location.named.mynamed.privateKeyFile", "privateKeyFile-inNamed");
-        brooklynProperties.put("brooklyn.location.localhost.privateKeyFile", "privateKeyFile-inProviderSpecific");
-        brooklynProperties.put("brooklyn.localhost.privateKeyFile", "privateKeyFile-inGeneric");
-
-        // prefer those in provider-specific over generic
-        brooklynProperties.put("brooklyn.location.localhost.publicKeyFile", "publicKeyFile-inProviderSpecific");
-        brooklynProperties.put("brooklyn.location.publicKeyFile", "publicKeyFile-inGeneric");
-
-        // prefer location-generic if nothing else
-        brooklynProperties.put("brooklyn.location.privateKeyData", "privateKeyData-inGeneric");
-
-        Map<String, Object> conf = resolve("named:mynamed").config().getBag().getAllConfig();
-        
-        assertEquals(conf.get("privateKeyFile"), "privateKeyFile-inNamed");
-        assertEquals(conf.get("publicKeyFile"), "publicKeyFile-inProviderSpecific");
-        assertEquals(conf.get("privateKeyData"), "privateKeyData-inGeneric");
-    }
-
-    @Test
-    public void testLocalhostLoads() {
-        Assert.assertTrue(resolve("localhost") instanceof LocalhostMachineProvisioningLocation);
-    }
-
-    @Test
-    public void testThrowsOnInvalid() throws Exception {
-        assertThrowsNoSuchElement("wrongprefix");
-        assertThrowsIllegalArgument("localhost(name=abc"); // no closing bracket
-        assertThrowsIllegalArgument("localhost(name)"); // no value for name
-        assertThrowsIllegalArgument("localhost(name=)"); // no value for name
-    }
-    
-
-    @Test
-    public void testAcceptsList() {
-        List<Location> l = getLocationResolver().resolve(ImmutableList.of("localhost"));
-        assertEquals(l.size(), 1, "l="+l);
-        assertTrue(l.get(0) instanceof LocalhostMachineProvisioningLocation, "l="+l);
-    }
-
-    @SuppressWarnings("unchecked")
-    @Test
-    public void testRegistryCommaResolution() throws NoMachinesAvailableException {
-        List<Location> l;
-        l = getLocationResolver().resolve(JavaStringEscapes.unwrapJsonishListIfPossible("localhost,localhost,localhost"));
-        assertEquals(l.size(), 3, "l="+l);
-        assertTrue(l.get(0) instanceof LocalhostMachineProvisioningLocation, "l="+l);
-        assertTrue(l.get(1) instanceof LocalhostMachineProvisioningLocation, "l="+l);
-        assertTrue(l.get(2) instanceof LocalhostMachineProvisioningLocation, "l="+l);
-
-        // And check works if comma in brackets
-        l = getLocationResolver().resolve(JavaStringEscapes.unwrapJsonishListIfPossible(
-            "[ \"byon:(hosts=\\\"192.168.0.1\\\",user=bob)\", \"byon:(hosts=\\\"192.168.0.2\\\",user=bob2)\" ]"));
-        assertEquals(l.size(), 2, "l="+l);
-        assertTrue(l.get(0) instanceof FixedListMachineProvisioningLocation, "l="+l);
-        assertTrue(l.get(1) instanceof FixedListMachineProvisioningLocation, "l="+l);
-        assertEquals(((FixedListMachineProvisioningLocation<SshMachineLocation>)l.get(0)).obtain().getUser(), "bob");
-        assertEquals(((FixedListMachineProvisioningLocation<SshMachineLocation>)l.get(1)).obtain().getUser(), "bob2");
-    }
-
-    @Test(expectedExceptions={NoSuchElementException.class})
-    public void testRegistryCommaResolutionInListNotAllowed1() throws NoMachinesAvailableException {
-        // disallowed since 0.7.0
-        getLocationResolver().resolve(ImmutableList.of("localhost,localhost,localhost"));
-    }
-
-    @Test(expectedExceptions={IllegalArgumentException.class})
-    public void testRegistryCommaResolutionInListNotAllowed2() throws NoMachinesAvailableException {
-        // disallowed since 0.7.0
-        // fails because it interprets the entire string as a single spec, which does not parse
-        getLocationResolver().resolve(ImmutableList.of("localhost(),localhost()"));
-    }
-
-    @Test(expectedExceptions={IllegalArgumentException.class})
-    public void testRegistryCommaResolutionInListNotAllowed3() throws NoMachinesAvailableException {
-        // disallowed since 0.7.0
-        // fails because it interprets the entire string as a single spec, which does not parse
-        getLocationResolver().resolve(ImmutableList.of("localhost(name=a),localhost(name=b)"));
-    }
-
-    @Test(expectedExceptions={IllegalArgumentException.class})
-    public void testDoesNotAcceptsListOLists() {
-        ((BasicLocationRegistry)managementContext.getLocationRegistry()).resolve(ImmutableList.of(ImmutableList.of("localhost")));
-    }
-
-    @Test
-    public void testResolvesExplicitName() throws Exception {
-        Location location = resolve("localhost(name=myname)");
-        assertTrue(location instanceof LocalhostMachineProvisioningLocation);
-        assertEquals(location.getDisplayName(), "myname");
-    }
-    
-    @Test
-    public void testWithOldStyleColon() throws Exception {
-        Location location = resolve("localhost:(name=myname)");
-        assertTrue(location instanceof LocalhostMachineProvisioningLocation);
-        assertEquals(location.getDisplayName(), "myname");
-    }
-    
-    @Test
-    public void testResolvesPropertiesInSpec() throws Exception {
-        LocationInternal location = resolve("localhost(privateKeyFile=myprivatekeyfile,name=myname)");
-        assertTrue(location instanceof LocalhostMachineProvisioningLocation);
-        assertEquals(location.getDisplayName(), "myname");
-        assertEquals(location.config().getBag().getStringKey("privateKeyFile"), "myprivatekeyfile");
-    }
-    
-    @Test
-    public void testResolvesDefaultName() throws Exception {
-        Location location = resolve("localhost");
-        assertTrue(location instanceof LocalhostMachineProvisioningLocation);
-        assertEquals(location.getDisplayName(), "localhost");
-
-        Location location2 = resolve("localhost()");
-        assertTrue(location2 instanceof LocalhostMachineProvisioningLocation);
-        assertEquals(location2.getDisplayName(), "localhost");
-    }
-    
-    private BasicLocationRegistry getLocationResolver() {
-        return (BasicLocationRegistry) managementContext.getLocationRegistry();
-    }
-    
-    private LocationInternal resolve(String val) {
-        Location l = managementContext.getLocationRegistry().resolve(val);
-        Assert.assertNotNull(l);
-        return (LocationInternal) l;
-    }
-    
-    private void assertThrowsNoSuchElement(String val) {
-        try {
-            resolve(val);
-            fail();
-        } catch (NoSuchElementException e) {
-            // success
-        }
-
-        // and check the long form returns an Absent (not throwing)
-        Assert.assertTrue(managementContext.getLocationRegistry().resolve(val, false, null).isAbsent());
-    }
-    
-    private void assertThrowsIllegalArgument(String val) {
-        try {
-            resolve(val);
-            fail();
-        } catch (IllegalArgumentException e) {
-            // success
-        }
-        
-        // and check the long form returns an Absent (not throwing)
-        Assert.assertTrue(managementContext.getLocationRegistry().resolve(val, false, null).isAbsent());
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/LocalhostMachineProvisioningLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/LocalhostMachineProvisioningLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/LocalhostMachineProvisioningLocationTest.java
deleted file mode 100644
index f7a1618..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/LocalhostMachineProvisioningLocationTest.java
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.fail;
-
-import java.net.ServerSocket;
-
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.net.Networking;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.api.location.PortRange;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.location.geo.HostGeoInfo;
-
-public class LocalhostMachineProvisioningLocationTest {
-
-    private static final Logger log = LoggerFactory.getLogger(LocalhostMachineProvisioningLocationTest.class);
-    
-    private LocalManagementContext mgmt;
-
-    @BeforeMethod
-    @AfterClass
-    protected void clearStatics() {
-        LocalhostMachineProvisioningLocation.clearStaticData();
-    }
-    
-    @BeforeClass
-    protected void setup() {
-        mgmt = LocalManagementContextForTests.newInstance();
-    }
-    
-    @AfterClass
-    protected void teardown() {
-        Entities.destroyAll(mgmt);
-    }
-    
-    protected LocalhostMachineProvisioningLocation newLocalhostProvisioner() {
-        return mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class));
-    }
-    
-    protected LocalhostMachineProvisioningLocation newLocalhostProvisionerWithAddress(String address) {
-        return mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class)
-            .configure("address", address));
-    }
-    
-    @Test
-    public void defaultInvocationCanProvisionALocalhostInstance() throws Exception {
-        LocalhostMachineProvisioningLocation provisioner = mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class));
-        SshMachineLocation machine = provisioner.obtain();
-        assertNotNull(machine);
-        assertEquals(machine.address, Networking.getLocalHost());
-    }
-
-    @Test
-    public void testUsesLocationNameProvided() throws Exception {
-        LocalhostMachineProvisioningLocation provisioner = newLocalhostProvisionerWithAddress("localhost");
-        assertEquals(((SshMachineLocation)provisioner.obtain()).getAddress().getHostName(), "localhost");
-
-        LocalhostMachineProvisioningLocation provisioner2 = newLocalhostProvisionerWithAddress("1.2.3.4");
-        assertEquals(((SshMachineLocation)provisioner2.obtain()).getAddress().getHostName(), "1.2.3.4");
-        
-        LocalhostMachineProvisioningLocation provisioner3 = newLocalhostProvisionerWithAddress("127.0.0.1");
-        assertEquals(((SshMachineLocation)provisioner3.obtain()).getAddress().getHostName(), "127.0.0.1");
-    }
-    
-    public void provisionWithASpecificNumberOfInstances() throws NoMachinesAvailableException {
-        LocalhostMachineProvisioningLocation provisioner = mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class)
-            .configure("count", 2));
-
-        // first machine
-        SshMachineLocation first = provisioner.obtain();
-        assertNotNull(first);
-        assertEquals(first.address, Networking.getLocalHost());
-
-        // second machine
-        SshMachineLocation second = provisioner.obtain();
-        assertNotNull(second);
-        assertEquals(second.address, Networking.getLocalHost());
-
-        // third machine - fails
-        try {
-            SshMachineLocation third = provisioner.obtain();
-            fail("did not throw expected exception; got "+third);
-        } catch (NoMachinesAvailableException e) {
-            /* expected */
-        }
-    }
-    
-    @Test
-    public void obtainTwoAddressesInRangeThenDontObtain() throws Exception {
-        LocalhostMachineProvisioningLocation p = newLocalhostProvisioner();
-        SshMachineLocation m = p.obtain();
-
-        // Find two ports that are free, rather than risk false-negatives if a port was left open by something else.
-        int start = 48311;
-        while (true) {
-            if (Networking.isPortAvailable(m.getAddress(), start) && Networking.isPortAvailable(m.getAddress(), start+1)) {
-                break;
-            } else {
-                start++;
-            }
-        }
-        PortRange r = PortRanges.fromString(""+start+"-"+(start+1));
-        
-        try {
-            int i1 = m.obtainPort(r);
-            Assert.assertEquals(i1, start);
-            int i2 = m.obtainPort(r);
-            Assert.assertEquals(i2, start+1);
-            
-            //should fail
-            int i3 = m.obtainPort(r);
-            Assert.assertEquals(i3, -1);
-
-            //releasing and reapplying should succed
-            m.releasePort(i2);
-            int i4 = m.obtainPort(r);
-            Assert.assertEquals(i4, i2);
-
-        } finally {
-            m.releasePort(start);
-            m.releasePort(start+1);
-        }
-    }
-    
-    @Test
-    public void obtainLowNumberedPortsAutomatically() throws Exception {
-        LocalhostMachineProvisioningLocation p = newLocalhostProvisioner();
-        SshMachineLocation m = p.obtain();
-        int start = 983;  //random rarely used port, not that it matters
-        try {
-            int actual = m.obtainPort(PortRanges.fromInteger(start));
-            Assert.assertEquals(actual, start);
-        } finally {
-            m.releasePort(start);
-        }
-
-    }
-
-    @Test
-    public void obtainPortFailsIfInUse() throws Exception {
-        LocalhostMachineProvisioningLocation p = newLocalhostProvisioner();
-        SshMachineLocation m = p.obtain();
-        
-        // Find two ports that are free, rather than risk false-negatives if a port was left open by something else.
-        int start = 48311;
-        while (true) {
-            if (Networking.isPortAvailable(m.getAddress(), start) && Networking.isPortAvailable(m.getAddress(), start+1)) {
-                break;
-            } else {
-                start++;
-            }
-        }
-        PortRange r = PortRanges.fromString(""+start+"-"+(start+1));
-
-        ServerSocket ss = null;
-        try {
-            ss = new ServerSocket(start, 0, m.getAddress());
-            int i1 = m.obtainPort(r);
-            Assert.assertEquals(i1, start+1);
-        } finally {
-            if (ss!=null) ss.close();
-            m.releasePort(start);
-            m.releasePort(start+1);
-        }
-    }
-
-    @Test
-    public void obtainLocationWithGeography() throws Exception {
-        mgmt.getBrooklynProperties().put("brooklyn.location.named.lhx", "localhost");
-        // bogus location so very little chance of it being what maxmind returns!
-        mgmt.getBrooklynProperties().put("brooklyn.location.named.lhx.latitude", 42d);
-        mgmt.getBrooklynProperties().put("brooklyn.location.named.lhx.longitude", -20d);
-        MachineProvisioningLocation<?> p = (MachineProvisioningLocation<?>) mgmt.getLocationRegistry().resolve("named:lhx");
-        SshMachineLocation m = (SshMachineLocation) p.obtain(MutableMap.of());
-        HostGeoInfo geo = HostGeoInfo.fromLocation(m);
-        log.info("Geo info for "+m+" is: "+geo);
-        Assert.assertEquals(geo.latitude, 42d, 0.00001);
-        Assert.assertEquals(geo.longitude, -20d, 0.00001);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/LocalhostProvisioningAndAccessTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/LocalhostProvisioningAndAccessTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/LocalhostProvisioningAndAccessTest.java
deleted file mode 100644
index f6ba35d..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/LocalhostProvisioningAndAccessTest.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-
-import java.util.Arrays;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.entity.core.Entities;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class LocalhostProvisioningAndAccessTest {
-
-    private LocalManagementContext mgmt;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        mgmt = new LocalManagementContext(BrooklynProperties.Factory.newDefault());
-    }
-    
-    @AfterMethod(alwaysRun = true)
-    public void tearDown(){
-        if (mgmt != null) Entities.destroyAll(mgmt);
-    }
-
-    @Test(groups="Integration")
-    public void testProvisionAndConnect() throws Exception {
-        Location location = mgmt.getLocationRegistry().resolve("localhost");
-        assertTrue(location instanceof LocalhostMachineProvisioningLocation);
-        SshMachineLocation m = ((LocalhostMachineProvisioningLocation)location).obtain();
-        int result = m.execCommands("test", Arrays.asList("echo hello world"));
-        assertEquals(result, 0);
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/LocationConfigTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/LocationConfigTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/LocationConfigTest.java
deleted file mode 100644
index 9a18d5c..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/LocationConfigTest.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableMap;
-
-public class LocationConfigTest {
-
-    // TODO Duplication of LocationConfigTest, but with locations instead of entities
-    
-    private ManagementContext managementContext;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        managementContext = LocalManagementContextForTests.newInstance();
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() {
-        if (managementContext != null) Entities.destroyAll(managementContext);
-    }
-
-    @Test
-    public void testConfigBagContainsMatchesForConfigKeyName() throws Exception {
-        LocationInternal loc = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class)
-                .configure("mylocation.myconfig", "myval1")
-                .configure("mylocation.myconfigwithflagname", "myval2"));
-        
-        assertEquals(loc.config().getBag().getAllConfig(), ImmutableMap.of("mylocation.myconfig", "myval1", "mylocation.myconfigwithflagname", "myval2"));
-        assertEquals(loc.config().getLocalBag().getAllConfig(), ImmutableMap.of("mylocation.myconfig", "myval1", "mylocation.myconfigwithflagname", "myval2"));
-        Assert.assertEquals(loc.getAllConfig(true), ImmutableMap.of("mylocation.myconfig", "myval1", "mylocation.myconfigwithflagname", "myval2"));
-        Assert.assertEquals(loc.getAllConfig(false), ImmutableMap.of("mylocation.myconfig", "myval1", "mylocation.myconfigwithflagname", "myval2"));
-    }
-
-    // TODO Note difference compared to Location, where both flag-name + config-key-name are in the ConfigBag
-    @Test
-    public void testConfigBagContainsMatchesForFlagName() throws Exception {
-        // Prefers flag-name, over config-key's name
-        LocationInternal loc = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class)
-                .configure("myconfigflagname", "myval"));
-        
-        assertEquals(loc.config().getBag().getAllConfig(), ImmutableMap.of("mylocation.myconfigwithflagname", "myval", "myconfigflagname", "myval"));
-        assertEquals(loc.config().getLocalBag().getAllConfig(), ImmutableMap.of("mylocation.myconfigwithflagname", "myval", "myconfigflagname", "myval"));
-        Assert.assertEquals(loc.getAllConfig(true), ImmutableMap.of("mylocation.myconfigwithflagname", "myval", "myconfigflagname", "myval"));
-        Assert.assertEquals(loc.getAllConfig(false), ImmutableMap.of("mylocation.myconfigwithflagname", "myval", "myconfigflagname", "myval"));
-    }
-
-    @Test
-    public void testConfigBagContainsUnmatched() throws Exception {
-        LocationInternal loc = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class)
-                .configure("notThere", "notThereVal"));
-        
-        assertEquals(loc.config().getBag().getAllConfig(), ImmutableMap.of("notThere", "notThereVal"));
-        assertEquals(loc.config().getLocalBag().getAllConfig(), ImmutableMap.of("notThere", "notThereVal"));
-        Assert.assertEquals(loc.getAllConfig(true), ImmutableMap.of("notThere", "notThereVal"));
-        Assert.assertEquals(loc.getAllConfig(false), ImmutableMap.of("notThere", "notThereVal"));
-    }
-    
-    // TODO Note difference from entity: child's bag contains both the flag-name and the config-key-name
-    @Test
-    public void testChildConfigBagInheritsUnmatchedAtParent() throws Exception {
-        LocationInternal loc = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class)
-                .configure("mychildlocation.myconfig", "myval1")
-                .configure("notThere", "notThereVal"));
-
-        LocationInternal child = managementContext.getLocationManager().createLocation(LocationSpec.create(MyChildLocation.class)
-                .parent(loc));
-
-        assertEquals(child.config().getBag().getAllConfig(), ImmutableMap.of("mychildlocation.myconfig", "myval1", "notThere", "notThereVal"));
-        assertEquals(child.config().getLocalBag().getAllConfig(), ImmutableMap.of());
-        Assert.assertEquals(child.getAllConfig(true), ImmutableMap.of("mychildlocation.myconfig", "myval1", "notThere", "notThereVal"));
-        Assert.assertEquals(child.getAllConfig(false), ImmutableMap.of());
-    }
-    
-    // TODO Fails for location, but passes for entity; not worth fixing here; locations will soon be entities!
-    @Test(groups="WIP")
-    public void testChildConfigBagInheritsFlagNameFromParentSetsOwnConfigKey() throws Exception {
-        LocationInternal loc = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class)
-                .configure("mychildconfigflagname", "myval"));
-
-        LocationInternal child = managementContext.getLocationManager().createLocation(LocationSpec.create(MyChildLocation.class)
-                .parent(loc));
-
-        assertEquals(child.config().getBag().getAllConfig(), ImmutableMap.of("mychildlocation.myconfigwithflagname", "myval"));
-        assertEquals(child.config().getLocalBag().getAllConfig(), ImmutableMap.of());
-        Assert.assertEquals(child.getAllConfig(true), ImmutableMap.of("mychildlocation.myconfigwithflagname", "myval"));
-        Assert.assertEquals(child.getAllConfig(false), ImmutableMap.of());
-    }
-    
-    @Test
-    public void testChildInheritsFromParent() throws Exception {
-        LocationInternal loc = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class)
-                .configure("mylocation.myconfig", "myval1"));
-
-        LocationInternal child = managementContext.getLocationManager().createLocation(LocationSpec.create(MyChildLocation.class)
-                .parent(loc));
-
-        assertEquals(child.config().getBag().getAllConfig(), ImmutableMap.of("mylocation.myconfig", "myval1"));
-        assertEquals(child.config().getLocalBag().getAllConfig(), ImmutableMap.of());
-        Assert.assertEquals(child.getAllConfig(true), ImmutableMap.of("mylocation.myconfig", "myval1"));
-        Assert.assertEquals(child.getAllConfig(false), ImmutableMap.of());
-    }
-    
-    @Test
-    public void testChildCanOverrideConfigUsingKeyName() throws Exception {
-        LocationInternal location = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class)
-                .configure("mychildlocation.myconfigwithflagname", "myval")
-                .configure("notThere", "notThereVal"));
-
-        LocationInternal child = managementContext.getLocationManager().createLocation(LocationSpec.create(MyChildLocation.class)
-                .parent(location)
-                .configure("mychildlocation.myconfigwithflagname", "overrideMyval")
-                .configure("notThere", "overrideNotThereVal"));
-
-        assertEquals(child.config().getBag().getAllConfig(), ImmutableMap.of("mychildlocation.myconfigwithflagname", "overrideMyval", "notThere", "overrideNotThereVal"));
-        assertEquals(child.config().getLocalBag().getAllConfig(), ImmutableMap.of("mychildlocation.myconfigwithflagname", "overrideMyval", "notThere", "overrideNotThereVal"));
-        Assert.assertEquals(child.getAllConfig(true), ImmutableMap.of("mychildlocation.myconfigwithflagname", "overrideMyval", "notThere", "overrideNotThereVal"));
-        Assert.assertEquals(child.getAllConfig(false), ImmutableMap.of("mychildlocation.myconfigwithflagname", "overrideMyval", "notThere", "overrideNotThereVal"));
-    }
-    
-    // TODO Note difference compared to Location, where both flag-name + config-key-name are in the ConfigBag
-    @Test
-    public void testChildCanOverrideConfigUsingFlagName() throws Exception {
-        LocationInternal loc = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class)
-                .configure("mychildlocation.myconfigwithflagname", "myval"));
-
-        LocationInternal child = managementContext.getLocationManager().createLocation(LocationSpec.create(MyChildLocation.class)
-                .parent(loc)
-                .configure("mychildconfigflagname", "overrideMyval"));
-
-        assertEquals(child.config().getBag().getAllConfig(), ImmutableMap.of("mychildlocation.myconfigwithflagname", "overrideMyval", "mychildconfigflagname", "overrideMyval"));
-        assertEquals(child.config().getLocalBag().getAllConfig(), ImmutableMap.of("mychildlocation.myconfigwithflagname", "overrideMyval", "mychildconfigflagname", "overrideMyval"));
-        Assert.assertEquals(child.getAllConfig(true), ImmutableMap.of("mychildlocation.myconfigwithflagname", "overrideMyval", "mychildconfigflagname", "overrideMyval"));
-        Assert.assertEquals(child.getAllConfig(false), ImmutableMap.of("mychildlocation.myconfigwithflagname", "overrideMyval", "mychildconfigflagname", "overrideMyval"));
-    }
-    
-    @Test
-    public void testLocationCanOverrideConfigDefaultValue() throws Exception {
-        LocationInternal loc = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class));
-        LocationInternal subloc = managementContext.getLocationManager().createLocation(LocationSpec.create(MySubLocation.class));
-
-        Assert.assertEquals(loc.getConfig(MyLocation.MY_CONFIG_WITH_DEFAULT), "mydefault");
-        Assert.assertEquals(loc.getConfig(ConfigKeys.newStringConfigKey("mylocation.myconfigwithdefault", "", "differentdefault")), "mydefault");
-        
-        Assert.assertEquals(subloc.getConfig(MySubLocation.MY_CONFIG_WITH_DEFAULT), "mysubdefault");
-        Assert.assertEquals(subloc.getConfig(MyLocation.MY_CONFIG_WITH_DEFAULT), "mysubdefault");
-    }
-    
-    @SuppressWarnings("serial")
-    public static class MyLocation extends AbstractLocation {
-        public static final ConfigKey<String> MY_CONFIG = ConfigKeys.newStringConfigKey("mylocation.myconfig");
-
-        @SetFromFlag("myconfigflagname")
-        public static final ConfigKey<String> MY_CONFIG_WITH_FLAGNAME = ConfigKeys.newStringConfigKey("mylocation.myconfigwithflagname");
-        
-        public static final ConfigKey<String> MY_CONFIG_WITH_DEFAULT = ConfigKeys.newStringConfigKey("mylocation.myconfigwithdefault", "", "mydefault");
-    }
-    
-    @SuppressWarnings("serial")
-    public static class MyChildLocation extends AbstractLocation {
-        public static final ConfigKey<String> MY_CHILD_CONFIG = ConfigKeys.newStringConfigKey("mychildlocation.myconfig");
-
-        @SetFromFlag("mychildconfigflagname")
-        public static final ConfigKey<String> MY_CHILD_CONFIG_WITH_FLAGNAME = ConfigKeys.newStringConfigKey("mychildlocation.myconfigwithflagname");
-    }
-    
-    @SuppressWarnings("serial")
-    public static class MySubLocation extends MyLocation {
-        public static final ConfigKey<String> MY_CONFIG_WITH_DEFAULT = ConfigKeys.newConfigKeyWithDefault(MyLocation.MY_CONFIG_WITH_DEFAULT, "mysubdefault");
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/LocationConfigUtilsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/LocationConfigUtilsTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/LocationConfigUtilsTest.java
deleted file mode 100644
index c9f600e..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/LocationConfigUtilsTest.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-
-import java.io.File;
-
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-@Test
-public class LocationConfigUtilsTest {
-
-    // set these system properties differently if needed to fix your tests
-    public static final String SSH_PRIVATE_KEY_FILE_WITH_TILDE = System.getProperty("sshPrivateKey", "~/.ssh/id_rsa");
-    public static final String SSH_PUBLIC_KEY_FILE_WITH_TILDE = System.getProperty("sshPublicKey", "~/.ssh/id_rsa.pub");
-    // these should work as they are on classpath
-    public static final String SSH_PRIVATE_KEY_FILE_WITH_PASSPHRASE = System.getProperty("sshPrivateKeyWithPassphrase", "/brooklyn/util/crypto/sample_rsa_passphrase.pem");
-    public static final String SSH_PRIVATE_KEY_FILE = System.getProperty("sshPrivateKeySample", "/org/apache/brooklyn/location/basic/sample_id_rsa");
-    public static final String SSH_PUBLIC_KEY_FILE = System.getProperty("sshPublicKeySample", "/org/apache/brooklyn/location/basic/sample_id_rsa.pub");
-    
-    public void testPreferPrivateKeyDataOverFile() throws Exception {
-        ConfigBag config = ConfigBag.newInstance();
-        config.put(LocationConfigKeys.PRIVATE_KEY_DATA, "mydata");
-        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE);
-        
-        LocationConfigUtils.OsCredential creds = LocationConfigUtils.getOsCredential(config).doKeyValidation(false);
-        Assert.assertTrue(creds.hasKey());
-        // warnings, as it is malformed
-        Assert.assertFalse(creds.getWarningMessages().isEmpty());
-
-        String data = creds.getPrivateKeyData();
-        assertEquals(data, "mydata");
-    }
-
-    @Test(expectedExceptions=IllegalStateException.class)
-    public void testInvalidKeyData() throws Exception {
-        ConfigBag config = ConfigBag.newInstance();
-        config.put(LocationConfigKeys.PRIVATE_KEY_DATA, "mydata");
-        
-        LocationConfigUtils.OsCredential creds = LocationConfigUtils.getOsCredential(config).doKeyValidation(false);
-        Assert.assertTrue(creds.hasKey());
-        Assert.assertFalse(creds.getWarningMessages().isEmpty());
-        
-        creds.checkNoErrors();
-    }
-
-    public void testPreferPublicKeyDataOverFileAndNoPrivateKeyRequired() throws Exception {
-        ConfigBag config = ConfigBag.newInstance();
-        config.put(LocationConfigKeys.PUBLIC_KEY_DATA, "mydata");
-        config.put(LocationConfigKeys.PUBLIC_KEY_FILE, SSH_PUBLIC_KEY_FILE);
-        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, "");
-        
-        LocationConfigUtils.OsCredential creds = LocationConfigUtils.getOsCredential(config);
-        String data = creds.getPublicKeyData();
-        assertEquals(data, "mydata");
-        Assert.assertNull(creds.getPreferredCredential());
-        Assert.assertFalse(creds.hasPassword());
-        Assert.assertFalse(creds.hasKey());
-        // and not even any warnings here
-        Assert.assertTrue(creds.getWarningMessages().isEmpty());
-    }
-    
-    @Test(groups="Integration")  // requires ~/.ssh/id_rsa
-    public void testReadsPrivateKeyFileWithTildePath() throws Exception {
-        ConfigBag config = ConfigBag.newInstance();
-        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE_WITH_TILDE);
-
-        // don't mind if it has a passphrase
-        String data = LocationConfigUtils.getOsCredential(config).doKeyValidation(false).getPreferredCredential();
-        assertTrue(data != null && data.length() > 0);
-    }
-    
-    @Test(groups="Integration")
-    public void testReadsPrivateKeyFileWithPassphrase() throws Exception {
-        ConfigBag config = ConfigBag.newInstance();
-        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE_WITH_PASSPHRASE);
-
-        LocationConfigUtils.OsCredential cred = LocationConfigUtils.getOsCredential(config).doKeyValidation(false);
-        String data = cred.getPreferredCredential();
-        assertTrue(data != null && data.length() > 0);
-        Assert.assertFalse(data.isEmpty());
-        
-        cred.doKeyValidation(true);
-        try {
-            cred.checkNoErrors();
-            Assert.fail("check should fail as passphrase needed");
-        } catch (IllegalStateException exception) {
-        }
-
-        config.put(LocationConfigKeys.PRIVATE_KEY_PASSPHRASE, "passphrase");
-        cred.checkNoErrors();
-        
-        config.put(LocationConfigKeys.PRIVATE_KEY_PASSPHRASE, "wrong_passphrase");
-        try {
-            cred.checkNoErrors();
-            Assert.fail("check should fail as passphrase needed");
-        } catch (IllegalStateException exception) {
-        }
-    }
-    
-    public void testReadsPrivateKeyFileWithMultipleColonSeparatedFilesWithGoodLast() throws Exception {
-        ConfigBag config = ConfigBag.newInstance();
-        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, "/path/does/not/exist"+File.pathSeparator+SSH_PRIVATE_KEY_FILE);
-        
-        String data = LocationConfigUtils.getOsCredential(config).getPreferredCredential();
-        assertTrue(data != null && data.length() > 0);
-    }
-    
-    public void testReadsPrivateKeyFileWithMultipleColonSeparatedFilesWithGoodFirst() throws Exception {
-        ConfigBag config = ConfigBag.newInstance();
-        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE+File.pathSeparator+"/path/does/not/exist");
-
-        String data = LocationConfigUtils.getOsCredential(config).getPreferredCredential();
-        assertTrue(data != null && data.length() > 0);
-    }
-    
-    @Test(groups="Integration")  // requires ~/.ssh/id_rsa
-    public void testReadsPublicKeyFileWithTildePath() throws Exception {
-        ConfigBag config = ConfigBag.newInstance();
-        config.put(LocationConfigKeys.PUBLIC_KEY_FILE, SSH_PUBLIC_KEY_FILE_WITH_TILDE);
-        
-        // don't mind if it has a passphrase
-        String data = LocationConfigUtils.getOsCredential(config).doKeyValidation(false).getPublicKeyData();
-        assertTrue(data != null && data.length() > 0);
-    }
-    
-    public void testInfersPublicKeyFileFromPrivateKeyFile() throws Exception {
-        ConfigBag config = ConfigBag.newInstance();
-        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE);
-        
-        String data = LocationConfigUtils.getOsCredential(config).getPublicKeyData();
-        assertTrue(data != null && data.length() > 0);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/LocationExtensionsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/LocationExtensionsTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/LocationExtensionsTest.java
deleted file mode 100644
index 159c46d..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/LocationExtensionsTest.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class LocationExtensionsTest {
-
-    public static class ConcreteLocation extends AbstractLocation {
-        private static final long serialVersionUID = 2407231019435442876L;
-
-        public ConcreteLocation() {
-            super();
-        }
-    }
-
-    public interface MyExtension {
-    }
-    
-    public static class MyExtensionImpl implements MyExtension {
-    }
-    
-    private ManagementContext mgmt;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        mgmt = new LocalManagementContextForTests();
-    }
-    
-    @AfterMethod(alwaysRun = true)
-    public void tearDown(){
-        if (mgmt!=null) Entities.destroyAll(mgmt);
-    }
-
-    private ConcreteLocation createConcrete() {
-        return mgmt.getLocationManager().createLocation(LocationSpec.create(ConcreteLocation.class));
-    }
-    
-    @SuppressWarnings({ "unchecked", "rawtypes" })
-    private ConcreteLocation createConcrete(Class<?> extensionType, Object extension) {
-        // this cast is needed to make IntelliJ happy
-        return (ConcreteLocation) mgmt.getLocationManager().createLocation(LocationSpec.create(ConcreteLocation.class).extension((Class)extensionType, extension));
-    }
-    
-    @Test
-    public void testHasExtensionWhenMissing() {
-        Location loc = createConcrete();
-        assertFalse(loc.hasExtension(MyExtension.class));
-    }
-
-    @Test
-    public void testWhenExtensionPresent() {
-        MyExtension extension = new MyExtensionImpl();
-        ConcreteLocation loc = createConcrete();
-        loc.addExtension(MyExtension.class, extension);
-        
-        assertTrue(loc.hasExtension(MyExtension.class));
-        assertEquals(loc.getExtension(MyExtension.class), extension);
-    }
-
-    @Test
-    public void testAddExtensionThroughLocationSpec() {
-        MyExtension extension = new MyExtensionImpl();
-        Location loc = createConcrete(MyExtension.class, extension);
-        
-        assertTrue(loc.hasExtension(MyExtension.class));
-        assertEquals(loc.getExtension(MyExtension.class), extension);
-    }
-
-    @Test
-    public void testGetExtensionWhenMissing() {
-        Location loc = createConcrete();
-
-        try {
-            loc.getExtension(MyExtension.class);
-            fail();
-        } catch (IllegalArgumentException e) {
-            // success
-        }
-        
-        try {
-            loc.getExtension(null);
-            fail();
-        } catch (NullPointerException e) {
-            // success
-        }
-    }
-
-    @Test
-    public void testWhenExtensionDifferent() {
-        MyExtension extension = new MyExtensionImpl();
-        ConcreteLocation loc = createConcrete();
-        loc.addExtension(MyExtension.class, extension);
-        
-        assertFalse(loc.hasExtension(Object.class));
-        
-        try {
-            loc.getExtension(Object.class);
-            fail();
-        } catch (IllegalArgumentException e) {
-            // success
-        }
-    }
-
-    @Test
-    @SuppressWarnings({ "unchecked", "rawtypes" })
-    public void testAddExtensionIllegally() {
-        MyExtension extension = new MyExtensionImpl();
-        ConcreteLocation loc = createConcrete();
-        
-        try {
-            loc.addExtension((Class)MyExtension.class, "not an extension");
-            fail();
-        } catch (IllegalArgumentException e) {
-            // success
-        }
-        
-        try {
-            loc.addExtension(MyExtension.class, null);
-            fail();
-        } catch (NullPointerException e) {
-            // success
-        }
-        
-        try {
-            loc.addExtension(null, extension);
-            fail();
-        } catch (NullPointerException e) {
-            // success
-        }
-    }
-
-    @Test
-    public void testAddExtensionThroughLocationSpecIllegally() {
-        MyExtension extension = new MyExtensionImpl();
-        
-        try {
-            Location loc = createConcrete(MyExtension.class, "not an extension");
-            fail("loc="+loc);
-        } catch (IllegalArgumentException e) {
-            // success
-        }
-        
-        try {
-            Location loc = createConcrete(MyExtension.class, null);
-            fail("loc="+loc);
-        } catch (NullPointerException e) {
-            // success
-        }
-        
-        try {
-            Location loc = createConcrete(null, extension);
-            fail("loc="+loc);
-        } catch (NullPointerException e) {
-            // success
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/LocationManagementTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/LocationManagementTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/LocationManagementTest.java
deleted file mode 100644
index 9f53fbd..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/LocationManagementTest.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNull;
-import static org.testng.Assert.assertSame;
-import static org.testng.Assert.assertTrue;
-
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.LocationManager;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-
-public class LocationManagementTest extends BrooklynAppUnitTestSupport {
-
-    private LocationManager locationManager;
-
-    @BeforeMethod(alwaysRun=true)
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-        locationManager = mgmt.getLocationManager();
-    }
-    
-    @Test
-    public void testCreateLocationUsingSpec() {
-        SshMachineLocation loc = locationManager.createLocation(LocationSpec.create(SshMachineLocation.class)
-                .configure("address", "1.2.3.4"));
-        
-        assertEquals(loc.getAddress().getHostAddress(), "1.2.3.4");
-        assertSame(locationManager.getLocation(loc.getId()), loc);
-    }
-    
-    @Test
-    public void testCreateLocationUsingResolver() {
-        String spec = "byon:(hosts=\"1.1.1.1\")";
-        FixedListMachineProvisioningLocation<SshMachineLocation> loc = (FixedListMachineProvisioningLocation<SshMachineLocation>) mgmt.getLocationRegistry().resolve(spec);
-        SshMachineLocation machine = Iterables.getOnlyElement(loc.getAllMachines());
-        
-        assertSame(locationManager.getLocation(loc.getId()), loc);
-        assertSame(locationManager.getLocation(machine.getId()), machine);
-    }
-    
-    @Test
-    public void testChildrenOfManagedLocationAutoManaged() {
-        String spec = "byon:(hosts=\"1.1.1.1\")";
-        FixedListMachineProvisioningLocation<SshMachineLocation> loc = (FixedListMachineProvisioningLocation<SshMachineLocation>) mgmt.getLocationRegistry().resolve(spec);
-        SshMachineLocation machine = new SshMachineLocation(ImmutableMap.of("address", "1.2.3.4"));
-
-        loc.addChild(machine);
-        assertSame(locationManager.getLocation(machine.getId()), machine);
-        assertTrue(machine.isManaged());
-        
-        loc.removeChild(machine);
-        assertNull(locationManager.getLocation(machine.getId()));
-        assertFalse(machine.isManaged());
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/LocationPredicatesTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/LocationPredicatesTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/LocationPredicatesTest.java
deleted file mode 100644
index f3365bf..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/LocationPredicatesTest.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.entity.core.Entities;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class LocationPredicatesTest {
-
-    private LocalManagementContext managementContext;
-    private LocalhostMachineProvisioningLocation loc;
-    private SshMachineLocation childLoc;
-    private Location grandchildLoc;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        managementContext = LocalManagementContextForTests.newInstance();
-        loc = (LocalhostMachineProvisioningLocation) managementContext.getLocationRegistry().resolve("localhost:(name=mydisplayname)");
-        childLoc = loc.obtain();
-        grandchildLoc = managementContext.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class).parent(childLoc));
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (managementContext != null) Entities.destroyAll(managementContext);
-    }
-    
-    @Test
-    public void testIdEqualTo() throws Exception {
-        assertTrue(LocationPredicates.idEqualTo(loc.getId()).apply(loc));
-        assertFalse(LocationPredicates.idEqualTo("wrongid").apply(loc));
-    }
-    
-    @Test
-    public void testConfigEqualTo() throws Exception {
-        loc.setConfig(TestEntity.CONF_NAME, "myname");
-        assertTrue(LocationPredicates.configEqualTo(TestEntity.CONF_NAME, "myname").apply(loc));
-        assertFalse(LocationPredicates.configEqualTo(TestEntity.CONF_NAME, "wrongname").apply(loc));
-    }
-    
-    @Test
-    public void testDisplayNameEqualTo() throws Exception {
-        assertTrue(LocationPredicates.displayNameEqualTo("mydisplayname").apply(loc));
-        assertFalse(LocationPredicates.displayNameEqualTo("wrongname").apply(loc));
-    }
-    
-    @Test
-    public void testIsChildOf() throws Exception {
-        assertTrue(LocationPredicates.isChildOf(loc).apply(childLoc));
-        assertFalse(LocationPredicates.isChildOf(loc).apply(loc));
-        assertFalse(LocationPredicates.isChildOf(childLoc).apply(loc));
-    }
-    
-    @Test
-    public void testIsDescendantOf() throws Exception {
-        assertTrue(LocationPredicates.isDescendantOf(loc).apply(grandchildLoc));
-        assertTrue(LocationPredicates.isDescendantOf(loc).apply(childLoc));
-        assertFalse(LocationPredicates.isDescendantOf(loc).apply(loc));
-        assertFalse(LocationPredicates.isDescendantOf(childLoc).apply(loc));
-    }
-    
-    @Test
-    public void testManaged() throws Exception {
-        // TODO get exception in LocalhostMachineProvisioningLocation.removeChild because childLoc is "in use";
-        // this happens from the call to unmanage(loc), which first unmanaged the children.
-        loc.release(childLoc);
-        
-        assertTrue(LocationPredicates.managed().apply(loc));
-        Locations.unmanage(loc);
-        assertFalse(LocationPredicates.managed().apply(loc));
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/LocationPropertiesFromBrooklynPropertiesTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/LocationPropertiesFromBrooklynPropertiesTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/LocationPropertiesFromBrooklynPropertiesTest.java
deleted file mode 100644
index 8be1689..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/LocationPropertiesFromBrooklynPropertiesTest.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-
-import java.util.Map;
-
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.Maps;
-
-public class LocationPropertiesFromBrooklynPropertiesTest {
-
-    private LocationPropertiesFromBrooklynProperties parser;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        parser = new LocationPropertiesFromBrooklynProperties();
-    }
-    
-    @Test
-    public void testExtractProviderProperties() throws Exception {
-        String provider = "myprovider";
-        String namedLocation = null;
-        
-        Map<String, String> properties = Maps.newLinkedHashMap();
-        
-        // prefer those in "named" over everything else
-        properties.put("brooklyn.location.myprovider.privateKeyFile", "privateKeyFile-inProviderSpecific");
-        properties.put("brooklyn.location.privateKeyFile", "privateKeyFile-inLocationGeneric");
-
-        // prefer location-generic if nothing else
-        properties.put("brooklyn.location.publicKeyFile", "publicKeyFile-inLocationGeneric");
-        
-        Map<String, Object> conf = parser.getLocationProperties(provider, namedLocation, properties);
-        assertEquals(conf.get("privateKeyFile"), "privateKeyFile-inProviderSpecific");
-        assertEquals(conf.get("publicKeyFile"), "publicKeyFile-inLocationGeneric");
-    }
-
-    @Test
-    public void testExtractNamedLocationProperties() throws Exception {
-        String provider = "myprovider";
-        String namedLocation = "mynamed";
-        
-        Map<String, String> properties = Maps.newLinkedHashMap();
-        
-        properties.put("brooklyn.location.named.mynamed", "myprovider");
-        
-        // prefer those in "named" over everything else
-        properties.put("brooklyn.location.named.mynamed.privateKeyFile", "privateKeyFile-inNamed");
-        properties.put("brooklyn.location.myprovider.privateKeyFile", "privateKeyFile-inProviderSpecific");
-        properties.put("brooklyn.location.privateKeyFile", "privateKeyFile-inGeneric");
-
-        // prefer those in provider-specific over generic
-        properties.put("brooklyn.location.myprovider.publicKeyFile", "publicKeyFile-inProviderSpecific");
-        properties.put("brooklyn.location.publicKeyFile", "publicKeyFile-inGeneric");
-
-        // prefer location-generic if nothing else
-        properties.put("brooklyn.location.privateKeyData", "privateKeyData-inGeneric");
-
-        Map<String, Object> conf = parser.getLocationProperties(provider, namedLocation, properties);
-        assertEquals(conf.get("privateKeyFile"), "privateKeyFile-inNamed");
-        assertEquals(conf.get("publicKeyFile"), "publicKeyFile-inProviderSpecific");
-        assertEquals(conf.get("privateKeyData"), "privateKeyData-inGeneric");
-    }
-
-    @Test
-    public void testConvertsDeprecatedFormats() throws Exception {
-        String provider = "myprovider";
-        String namedLocation = "mynamed";
-        
-        Map<String, String> properties = Maps.newLinkedHashMap();
-        
-        properties.put("brooklyn.location.named.mynamed", "myprovider");
-        
-        // prefer those in "named" over everything else
-        properties.put("brooklyn.location.named.mynamed.private-key-file", "privateKeyFile-inNamed");
-        properties.put("brooklyn.location.myprovider.public-key-file", "publicKeyFile-inProviderSpecific");
-        properties.put("brooklyn.location.private-key-data", "privateKeyData-inGeneric");
-
-        Map<String, Object> conf = parser.getLocationProperties(provider, namedLocation, properties);
-        assertEquals(conf.get("privateKeyFile"), "privateKeyFile-inNamed");
-        assertEquals(conf.get("publicKeyFile"), "publicKeyFile-inProviderSpecific");
-        assertEquals(conf.get("privateKeyData"), "privateKeyData-inGeneric");
-    }
-    
-
-    @Test
-    public void testThrowsIfProviderDoesNotMatchNamed() throws Exception {
-        String provider = "myprovider";
-        String namedLocation = "mynamed";
-        
-        Map<String, String> properties = Maps.newLinkedHashMap();
-        
-        properties.put("brooklyn.location.named.mynamed", "completelydifferent");
-
-        try {
-            Map<String, Object> conf = parser.getLocationProperties(provider, namedLocation, properties);
-        } catch (IllegalStateException e) {
-            if (!e.toString().contains("Conflicting configuration")) throw e;
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/LocationRegistryTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/LocationRegistryTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/LocationRegistryTest.java
deleted file mode 100644
index 16c6e1a..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/LocationRegistryTest.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationDefinition;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.Test;
-
-public class LocationRegistryTest {
-    
-    private static final Logger log = LoggerFactory.getLogger(LocationRegistryTest.class);
-    
-    private LocalManagementContext mgmt;
-    private LocationDefinition locdef;
-
-    @AfterMethod(alwaysRun = true)
-    public void tearDown(){
-        if (mgmt != null) Entities.destroyAll(mgmt);
-    }
-
-    @Test
-    public void testNamedLocationsPropertyDefinedLocations() {
-        BrooklynProperties properties = BrooklynProperties.Factory.newEmpty();
-        properties.put("brooklyn.location.named.foo", "byon:(hosts=\"root@192.168.1.{1,2,3,4}\")");
-        properties.put("brooklyn.location.named.foo.privateKeyFile", "~/.ssh/foo.id_rsa");
-        mgmt = LocalManagementContextForTests.newInstance(properties);
-        log.info("foo properties gave defined locations: "+mgmt.getLocationRegistry().getDefinedLocations());
-        locdef = mgmt.getLocationRegistry().getDefinedLocationByName("foo");
-        Assert.assertNotNull(locdef, "Expected 'foo' location; but had "+mgmt.getLocationRegistry().getDefinedLocations());
-        Assert.assertEquals(locdef.getConfig().get("privateKeyFile"), "~/.ssh/foo.id_rsa");
-    }
-    
-    @Test(dependsOnMethods="testNamedLocationsPropertyDefinedLocations")
-    public void testResolvesByNamedAndId() {
-        BrooklynProperties properties = BrooklynProperties.Factory.newEmpty();
-        properties.put("brooklyn.location.named.foo", "byon:(hosts=\"root@192.168.1.{1,2,3,4}\")");
-        properties.put("brooklyn.location.named.foo.privateKeyFile", "~/.ssh/foo.id_rsa");
-        mgmt = LocalManagementContextForTests.newInstance(properties);
-
-        locdef = mgmt.getLocationRegistry().getDefinedLocationByName("foo");
-        log.info("testResovlesBy has defined locations: "+mgmt.getLocationRegistry().getDefinedLocations());
-        
-        Location l = mgmt.getLocationRegistry().resolve("named:foo");
-        Assert.assertNotNull(l);
-        Assert.assertEquals(l.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE), "~/.ssh/foo.id_rsa");
-        
-        l = mgmt.getLocationRegistry().resolve("foo");
-        Assert.assertNotNull(l);
-        Assert.assertEquals(l.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE), "~/.ssh/foo.id_rsa");
-        
-        l = mgmt.getLocationRegistry().resolve("id:"+locdef.getId());
-        Assert.assertNotNull(l);
-        Assert.assertEquals(l.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE), "~/.ssh/foo.id_rsa");
-        
-        l = mgmt.getLocationRegistry().resolve(locdef.getId());
-        Assert.assertNotNull(l);
-        Assert.assertEquals(l.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE), "~/.ssh/foo.id_rsa");
-    }
-
-    @Test
-    public void testLocationGetsDisplayName() {
-        BrooklynProperties properties = BrooklynProperties.Factory.newEmpty();
-        properties.put("brooklyn.location.named.foo", "byon:(hosts=\"root@192.168.1.{1,2,3,4}\")");
-        properties.put("brooklyn.location.named.foo.displayName", "My Foo");
-        mgmt = LocalManagementContextForTests.newInstance(properties);
-        Location l = mgmt.getLocationRegistry().resolve("foo");
-        Assert.assertEquals(l.getDisplayName(), "My Foo");
-    }
-    
-    @Test
-    public void testLocationGetsDefaultDisplayName() {
-        BrooklynProperties properties = BrooklynProperties.Factory.newEmpty();
-        properties.put("brooklyn.location.named.foo", "byon:(hosts=\"root@192.168.1.{1,2,3,4}\")");
-        mgmt = LocalManagementContextForTests.newInstance(properties);
-        Location l = mgmt.getLocationRegistry().resolve("foo");
-        Assert.assertNotNull(l.getDisplayName());
-        Assert.assertTrue(l.getDisplayName().startsWith(FixedListMachineProvisioningLocation.class.getSimpleName()), "name="+l.getDisplayName());
-        // TODO currently it gives default name; it would be nice to use 'foo', 
-        // or at least to have access to the spec (and use it e.g. in places such as DynamicFabric)
-        // Assert.assertEquals(l.getDisplayName(), "foo");
-    }
-    
-    @Test
-    public void testSetupForTesting() {
-        mgmt = LocalManagementContextForTests.newInstance();
-        BasicLocationRegistry.setupLocationRegistryForTesting(mgmt);
-        Assert.assertNotNull(mgmt.getLocationRegistry().getDefinedLocationByName("localhost"));
-    }
-
-    @Test
-    public void testCircularReference() {
-        BrooklynProperties properties = BrooklynProperties.Factory.newEmpty();
-        properties.put("brooklyn.location.named.bar", "named:bar");
-        mgmt = LocalManagementContextForTests.newInstance(properties);
-        log.info("bar properties gave defined locations: "+mgmt.getLocationRegistry().getDefinedLocations());
-        boolean resolved = false;
-        try {
-            mgmt.getLocationRegistry().resolve("bar");
-            resolved = true;
-        } catch (IllegalStateException e) {
-            //expected
-            log.info("bar properties correctly caught circular reference: "+e);
-        }
-        if (resolved)
-            // probably won't happen, if test fails will loop endlessly above
-            Assert.fail("Circular reference resolved location");
-    }
-
-    protected boolean findLocationMatching(String regex) {
-        for (LocationDefinition d: mgmt.getLocationRegistry().getDefinedLocations().values()) {
-            if (d.getName()!=null && d.getName().matches(regex)) return true;
-        }
-        return false;
-    }
-    
-    @Test
-    public void testLocalhostEnabled() {
-        BrooklynProperties properties = BrooklynProperties.Factory.newEmpty();
-        properties.put("brooklyn.location.localhost.enabled", true);
-        mgmt = LocalManagementContextForTests.newInstance(properties);
-        Assert.assertTrue( findLocationMatching("localhost") );
-    }
-
-    @Test
-    public void testLocalhostDisabled() {
-        BrooklynProperties properties = BrooklynProperties.Factory.newEmpty();
-        properties.put("brooklyn.location.localhost.enabled", false);
-        mgmt = LocalManagementContextForTests.newInstance(properties);
-        log.info("RESOLVERS: "+mgmt.getLocationRegistry().getDefinedLocations());
-        log.info("DEFINED LOCATIONS: "+mgmt.getLocationRegistry().getDefinedLocations());
-        Assert.assertFalse( findLocationMatching("localhost") );
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/MachineDetailsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/MachineDetailsTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/MachineDetailsTest.java
deleted file mode 100644
index 04955d4..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/MachineDetailsTest.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNotNull;
-
-import java.util.Arrays;
-
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineDetails;
-import org.apache.brooklyn.api.location.OsDetails;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class MachineDetailsTest {
-
-    private static final Logger LOG = LoggerFactory.getLogger(SshMachineLocationTest.class);
-
-    TestApplication app;
-    ManagementContext mgmt;
-    SshMachineLocation host;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setup() throws Exception {
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        mgmt = app.getManagementContext();
-
-        LocalhostMachineProvisioningLocation localhost = mgmt.getLocationManager().createLocation(
-                LocationSpec.create(LocalhostMachineProvisioningLocation.class));
-        host = localhost.obtain();
-        app.start(Arrays.asList(host));
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (mgmt != null) Entities.destroyAll(mgmt);
-        mgmt = null;
-    }
-
-    @Test(groups = "Integration")
-    public void testGetMachineDetails() {
-        Task<BasicMachineDetails> detailsTask = app.getExecutionContext().submit(
-                BasicMachineDetails.taskForSshMachineLocation(host));
-        MachineDetails machine = detailsTask.getUnchecked();
-        LOG.info("Found the following on localhost: {}", machine);
-        assertNotNull(machine);
-        OsDetails details = machine.getOsDetails();
-        assertNotNull(details);
-        assertNotNull(details.getArch());
-        assertNotNull(details.getName());
-        assertNotNull(details.getVersion());
-        assertFalse(details.getArch().startsWith("architecture:"), "architecture prefix not removed from details");
-        assertFalse(details.getName().startsWith("name:"), "name prefix not removed from details");
-        assertFalse(details.getVersion().startsWith("version:"), "version prefix not removed from details");
-    }
-}


[55/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/localhost/LocalhostMachineProvisioningLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/localhost/LocalhostMachineProvisioningLocation.java b/core/src/main/java/org/apache/brooklyn/location/localhost/LocalhostMachineProvisioningLocation.java
new file mode 100644
index 0000000..9f85901
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/localhost/LocalhostMachineProvisioningLocation.java
@@ -0,0 +1,352 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.localhost;
+
+import static org.apache.brooklyn.util.GroovyJavaMethods.elvis;
+import static org.apache.brooklyn.util.GroovyJavaMethods.truth;
+
+import java.io.File;
+import java.net.InetAddress;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.brooklyn.api.location.AddressableLocation;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.location.OsDetails;
+import org.apache.brooklyn.api.location.PortRange;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.config.ConfigKey.HasConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.mgmt.persist.FileBasedObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.LocationWithObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.core.BasicOsDetails;
+import org.apache.brooklyn.location.core.HasSubnetHostname;
+import org.apache.brooklyn.location.geo.HostGeoInfo;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.BrooklynNetworkUtils;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+import org.apache.brooklyn.util.core.internal.ssh.process.ProcessTool;
+import org.apache.brooklyn.util.core.mutex.MutexSupport;
+import org.apache.brooklyn.util.core.mutex.WithMutexes;
+import org.apache.brooklyn.util.net.Networking;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.ssh.BashCommands;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+
+/**
+ * An implementation of {@link MachineProvisioningLocation} that can provision a {@link SshMachineLocation} for the
+ * local host.
+ *
+ * By default you can only obtain a single SshMachineLocation for the localhost. Optionally, you can "overload"
+ * and choose to allow localhost to be provisioned multiple times, which may be useful in some testing scenarios.
+ */
+public class LocalhostMachineProvisioningLocation extends FixedListMachineProvisioningLocation<SshMachineLocation> implements AddressableLocation, LocationWithObjectStore {
+
+    private static final long serialVersionUID = -7791239672433897762L;
+
+    public static final Logger LOG = LoggerFactory.getLogger(LocalhostMachineProvisioningLocation.class);
+    
+    public static final ConfigKey<Boolean> SKIP_ON_BOX_BASE_DIR_RESOLUTION = ConfigKeys.newConfigKeyWithDefault(
+            BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, 
+            true);
+    
+    @SetFromFlag("count")
+    int initialCount;
+
+    @SetFromFlag
+    Boolean canProvisionMore;
+    
+    @SetFromFlag
+    InetAddress address;
+
+    private static Set<Integer> portsInUse = Sets.newLinkedHashSet();
+
+    private static HostGeoInfo cachedHostGeoInfo;
+    
+    @VisibleForTesting
+    public static void clearStaticData() {
+        portsInUse.clear();
+        cachedHostGeoInfo = null;
+    }
+        
+    /**
+     * Construct a new instance.
+     *
+     * The constructor recognises the following properties:
+     * <ul>
+     * <li>count - number of localhost machines to make available
+     * </ul>
+     */
+    public LocalhostMachineProvisioningLocation() {
+        this(Maps.newLinkedHashMap());
+    }
+    /**
+     * @param properties the properties of the new instance.
+     * @deprecated since 0.6
+     * @see #LocalhostMachineProvisioningLocation()
+     */
+    public LocalhostMachineProvisioningLocation(Map properties) {
+        super(properties);
+    }
+    public LocalhostMachineProvisioningLocation(String name) {
+        this(name, 0);
+    }
+    public LocalhostMachineProvisioningLocation(String name, int count) {
+        this(MutableMap.of("name", name, "count", count));
+    }
+    
+    public static LocationSpec<LocalhostMachineProvisioningLocation> spec() {
+        return LocationSpec.create(LocalhostMachineProvisioningLocation.class);
+    }
+    
+    public LocalhostMachineProvisioningLocation configure(Map<?,?> flags) {
+        super.configure(flags);
+        
+        if (!truth(getDisplayName())) { setDisplayName("localhost"); }
+        if (!truth(address)) address = getLocalhostInetAddress();
+        // TODO should try to confirm this machine is accessible on the given address ... but there's no 
+        // immediate convenience in java so early-trapping of that particular error is deferred
+        
+        if (canProvisionMore==null) {
+            if (initialCount>0) canProvisionMore = false;
+            else canProvisionMore = true;
+        }
+        if (getHostGeoInfo()==null) {
+            if (cachedHostGeoInfo==null)
+                cachedHostGeoInfo = HostGeoInfo.fromLocation(this);
+            setHostGeoInfo(cachedHostGeoInfo);
+        }
+        if (initialCount > getMachines().size()) {
+            provisionMore(initialCount - getMachines().size());
+        }
+        
+        if (getConfig(BrooklynConfigKeys.ONBOX_BASE_DIR)==null && (getManagementContext()==null || getManagementContext().getConfig().getConfig(BrooklynConfigKeys.ONBOX_BASE_DIR)==null)) {
+            setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, "/tmp/brooklyn-"+Os.user());
+        }
+        
+        return this;
+    }
+    
+    public static InetAddress getLocalhostInetAddress() {
+        return BrooklynNetworkUtils.getLocalhostInetAddress();
+    }
+
+    @Override
+    public InetAddress getAddress() {
+        return address;
+    }
+    
+    @Override
+    public boolean canProvisionMore() {
+        return canProvisionMore;
+    }
+    
+    @Override
+    protected void provisionMore(int size, Map<?,?> flags) {
+        for (int i=0; i<size; i++) {
+            Map<Object,Object> flags2 = MutableMap.<Object,Object>builder()
+                    .putAll(flags)
+                    .put("address", elvis(address, Networking.getLocalHost()))
+                    .put("mutexSupport", LocalhostMachine.mutexSupport)
+                    .build();
+            
+            // copy inherited keys for ssh; 
+            // shouldn't be necessary but not sure that all contexts traverse the hierarchy
+            // NOTE: changed Nov 2013 to copy only those ssh config keys actually set, rather than all of them
+            // TODO should take the plunge and try removing this altogether!
+            // (or alternatively switch to copying all ancestor keys)
+            for (HasConfigKey<?> k: SshMachineLocation.ALL_SSH_CONFIG_KEYS) {
+                if (config().getRaw(k).isPresent())
+                    flags2.put(k, getConfig(k));
+            }
+            
+            if (isManaged()) {
+                addChild(LocationSpec.create(LocalhostMachine.class).configure(flags2));
+            } else {
+                addChild(new LocalhostMachine(flags2)); // TODO legacy way
+            }
+       }
+    }
+
+    public static synchronized boolean obtainSpecificPort(InetAddress localAddress, int portNumber) {
+        if (portsInUse.contains(portNumber)) {
+            return false;
+        } else {
+            //see if it is available?
+            if (!checkPortAvailable(localAddress, portNumber)) {
+                return false;
+            }
+            portsInUse.add(portNumber);
+            return true;
+        }
+    }
+    /** checks the actual availability of the port on localhost, ie by binding to it; cf {@link Networking#isPortAvailable(int)} */
+    public static boolean checkPortAvailable(InetAddress localAddress, int portNumber) {
+        if (portNumber<1024) {
+            if (LOG.isDebugEnabled()) LOG.debug("Skipping system availability check for privileged localhost port "+portNumber);
+            return true;
+        }
+        return Networking.isPortAvailable(localAddress, portNumber);
+    }
+    public static int obtainPort(PortRange range) {
+        return obtainPort(getLocalhostInetAddress(), range);
+    }
+    public static int obtainPort(InetAddress localAddress, PortRange range) {
+        for (int p: range)
+            if (obtainSpecificPort(localAddress, p)) return p;
+        if (LOG.isDebugEnabled()) LOG.debug("unable to find port in {} on {}; returning -1", range, localAddress);
+        return -1;
+    }
+
+    public static synchronized void releasePort(InetAddress localAddress, int portNumber) {
+        portsInUse.remove((Object) portNumber);
+    }
+
+    public void release(SshMachineLocation machine) {
+        LocalhostMachine localMachine = (LocalhostMachine) machine;
+        Set<Integer> portsObtained = Sets.newLinkedHashSet();
+        synchronized (localMachine.portsObtained) {
+            portsObtained.addAll(localMachine.portsObtained);
+        }
+        
+        super.release(machine);
+        
+        for (int p: portsObtained)
+            releasePort(null, p);
+    }
+    
+    public static class LocalhostMachine extends SshMachineLocation implements HasSubnetHostname {
+        // declaring this here (as well as on LocalhostMachineProvisioningLocation) because:
+        //  1. machine.getConfig(key) will not inherit default value of machine.getParent()'s key
+        //  2. things might instantiate a `LocalhostMachine` without going through LocalhostMachineProvisioningLocation
+        //     so not sufficient for LocalhostMachineProvisioningLocation to just push its config value into
+        //     the LocalhostMachine instance.
+        public static final ConfigKey<Boolean> SKIP_ON_BOX_BASE_DIR_RESOLUTION = ConfigKeys.newConfigKeyWithDefault(
+                BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, 
+                true);
+
+        private static final WithMutexes mutexSupport = new MutexSupport();
+        
+        private final Set<Integer> portsObtained = Sets.newLinkedHashSet();
+
+        public LocalhostMachine() {
+            super();
+        }
+        /** @deprecated since 0.6.0 use no-arg constructor (and spec) then configure */
+        public LocalhostMachine(Map properties) {
+            super(MutableMap.builder().putAll(properties).put("mutexSupport", mutexSupport).build());
+        }
+        
+        @Override
+        protected WithMutexes getMutexSupport() {
+            return mutexSupport;
+        }
+        
+        public boolean obtainSpecificPort(int portNumber) {
+            if (!isSudoAllowed() && portNumber <= 1024)
+                return false;
+            return LocalhostMachineProvisioningLocation.obtainSpecificPort(getAddress(), portNumber);
+        }
+        
+        public int obtainPort(PortRange range) {
+            int r = LocalhostMachineProvisioningLocation.obtainPort(getAddress(), range);
+            synchronized (portsObtained) {
+                if (r>0) portsObtained.add(r);
+            }
+            LOG.debug("localhost.obtainPort("+range+"), returning "+r);
+            return r;
+        }
+        
+        @Override
+        public void releasePort(int portNumber) {
+            synchronized (portsObtained) {
+                portsObtained.remove((Object)portNumber);
+            }
+            LocalhostMachineProvisioningLocation.releasePort(getAddress(), portNumber);
+        }
+        
+        @Override
+        public OsDetails getOsDetails() {
+            return BasicOsDetails.Factory.newLocalhostInstance();
+        }
+        
+        @Override
+        public LocalhostMachine configure(Map<?,?> properties) {
+            if (address==null || !properties.containsKey("address"))
+                address = Networking.getLocalHost();
+            super.configure(properties);
+            return this;
+        }
+        @Override
+        public String getSubnetHostname() {
+           return Networking.getLocalHost().getHostName();
+        }
+        @Override
+        public String getSubnetIp() {
+            return Networking.getLocalHost().getHostAddress();
+        }
+    }
+
+    private static class SudoChecker {
+        static volatile long lastSudoCheckTime = -1;
+        static boolean lastSudoResult = false;
+        public static boolean isSudoAllowed() {
+            if (Time.hasElapsedSince(lastSudoCheckTime, Duration.FIVE_MINUTES))
+                checkIfNeeded();                    
+            return lastSudoResult;
+        }
+        private static synchronized void checkIfNeeded() {
+            if (Time.hasElapsedSince(lastSudoCheckTime, Duration.FIVE_MINUTES)) {
+                try {
+                    lastSudoResult = new ProcessTool().execCommands(MutableMap.<String,Object>of(), Arrays.asList(
+                            BashCommands.sudo("date"))) == 0;
+                } catch (Exception e) {
+                    lastSudoResult = false;
+                    LOG.debug("Error checking sudo at localhost: "+e, e);
+                }
+                lastSudoCheckTime = System.currentTimeMillis();
+            }
+        }
+    }
+
+    public static boolean isSudoAllowed() {
+        return SudoChecker.isSudoAllowed();
+    }
+
+    @Override
+    public PersistenceObjectStore newPersistenceObjectStore(String container) {
+        File basedir = new File(container);
+        if (basedir.isFile()) throw new IllegalArgumentException("Destination directory must not be a file");
+        return new FileBasedObjectStore(basedir);
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/localhost/LocalhostPropertiesFromBrooklynProperties.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/localhost/LocalhostPropertiesFromBrooklynProperties.java b/core/src/main/java/org/apache/brooklyn/location/localhost/LocalhostPropertiesFromBrooklynProperties.java
new file mode 100644
index 0000000..bce0c65
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/localhost/LocalhostPropertiesFromBrooklynProperties.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.localhost;
+
+import java.util.Map;
+
+import org.apache.brooklyn.location.core.LocationPropertiesFromBrooklynProperties;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Strings;
+
+/**
+ * @author aledsage
+ **/
+public class LocalhostPropertiesFromBrooklynProperties extends LocationPropertiesFromBrooklynProperties {
+
+    // TODO Once delete support for deprecated "location.localhost.*" then can get rid of this class, and use
+    // LocationPropertiesFromBrooklynProperties directly
+    
+    @SuppressWarnings("unused")
+    private static final Logger LOG = LoggerFactory.getLogger(LocalhostPropertiesFromBrooklynProperties.class);
+
+    @Override
+    public Map<String, Object> getLocationProperties(String provider, String namedLocation, Map<String, ?> properties) {
+        if (Strings.isNullOrEmpty(namedLocation) && Strings.isNullOrEmpty(provider)) {
+            throw new IllegalArgumentException("Neither cloud provider/API nor location name have been specified correctly");
+        }
+
+        ConfigBag result = ConfigBag.newInstance();
+        
+        result.putAll(transformDeprecated(getGenericLocationSingleWordProperties(properties)));
+        result.putAll(transformDeprecated(getMatchingSingleWordProperties("brooklyn.location.", properties)));
+        result.putAll(transformDeprecated(getMatchingProperties("brooklyn.location.localhost.", "brooklyn.localhost.", properties)));
+        if (!Strings.isNullOrEmpty(namedLocation)) result.putAll(transformDeprecated(getNamedLocationProperties(namedLocation, properties)));
+        setLocalTempDir(properties, result);
+        
+        return result.getAllConfigRaw();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/ssh/SshMachineLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/ssh/SshMachineLocation.java b/core/src/main/java/org/apache/brooklyn/location/ssh/SshMachineLocation.java
new file mode 100644
index 0000000..1ed1f55
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/ssh/SshMachineLocation.java
@@ -0,0 +1,1037 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.ssh;
+
+import static org.apache.brooklyn.util.GroovyJavaMethods.truth;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.io.Reader;
+import java.io.StringReader;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.security.KeyPair;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.TimeUnit;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.api.location.MachineDetails;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.OsDetails;
+import org.apache.brooklyn.api.location.PortRange;
+import org.apache.brooklyn.api.location.PortSupplier;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.config.ConfigKey.HasConfigKey;
+import org.apache.brooklyn.core.BrooklynLogging;
+import org.apache.brooklyn.core.config.BasicConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.config.ConfigUtils;
+import org.apache.brooklyn.core.config.MapConfigKey;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Function;
+import com.google.common.base.Objects;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Predicate;
+import com.google.common.base.Supplier;
+import com.google.common.base.Throwables;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.cache.RemovalListener;
+import com.google.common.cache.RemovalNotification;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import com.google.common.net.HostAndPort;
+import com.google.common.reflect.TypeToken;
+
+import org.apache.brooklyn.location.access.PortForwardManager;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.location.core.BasicHardwareDetails;
+import org.apache.brooklyn.location.core.BasicMachineDetails;
+import org.apache.brooklyn.location.core.BasicOsDetails;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.ResourceUtils;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.crypto.SecureKeys;
+import org.apache.brooklyn.util.core.file.ArchiveUtils;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+import org.apache.brooklyn.util.core.flags.TypeCoercions;
+import org.apache.brooklyn.util.core.internal.ssh.ShellTool;
+import org.apache.brooklyn.util.core.internal.ssh.SshException;
+import org.apache.brooklyn.util.core.internal.ssh.SshTool;
+import org.apache.brooklyn.util.core.internal.ssh.sshj.SshjTool;
+import org.apache.brooklyn.util.core.mutex.MutexSupport;
+import org.apache.brooklyn.util.core.mutex.WithMutexes;
+import org.apache.brooklyn.util.core.task.ScheduledTask;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.core.task.system.internal.ExecWithLoggingHelpers;
+import org.apache.brooklyn.util.core.task.system.internal.ExecWithLoggingHelpers.ExecRunner;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.exceptions.RuntimeInterruptedException;
+import org.apache.brooklyn.util.guava.KeyTransformingLoadingCache.KeyTransformingSameTypeLoadingCache;
+import org.apache.brooklyn.util.net.Urls;
+import org.apache.brooklyn.util.pool.BasicPool;
+import org.apache.brooklyn.util.pool.Pool;
+import org.apache.brooklyn.util.ssh.BashCommands;
+import org.apache.brooklyn.util.stream.KnownSizeInputStream;
+import org.apache.brooklyn.util.stream.ReaderInputStream;
+import org.apache.brooklyn.util.stream.StreamGobbler;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.time.Duration;
+
+import groovy.lang.Closure;
+
+/**
+ * Operations on a machine that is accessible via ssh.
+ * <p>
+ * We expose two ways of running scripts.
+ * The execCommands method passes lines to bash and is lightweight but fragile.
+ * The execScript method creates a script on the remote machine. It is portable but heavier.
+ * <p>
+ * Additionally there are routines to copyTo, copyFrom; and installTo (which tries a curl, and falls back to copyTo
+ * in event the source is accessible by the caller only).
+ */
+public class SshMachineLocation extends AbstractLocation implements MachineLocation, PortSupplier, WithMutexes, Closeable {
+
+    /** @deprecated since 0.7.0 shouldn't be public */
+    public static final Logger LOG = LoggerFactory.getLogger(SshMachineLocation.class);
+    /** @deprecated since 0.7.0 shouldn't be public */
+    public static final Logger logSsh = LoggerFactory.getLogger(BrooklynLogging.SSH_IO);
+    
+    // Use a sane timeout when doing a connectivity test
+    private static final int SSHABLE_CONNECT_TIMEOUT = (int)Duration.minutes(2).toMilliseconds();
+
+    public static final ConfigKey<Duration> SSH_CACHE_EXPIRY_DURATION = ConfigKeys.newConfigKey(Duration.class,
+            "sshCacheExpiryDuration", "Expiry time for unused cached ssh connections", Duration.FIVE_MINUTES);
+
+    public static final ConfigKey<MachineDetails> MACHINE_DETAILS = ConfigKeys.newConfigKey(
+            MachineDetails.class,
+            "machineDetails");
+
+    public static final ConfigKey<Boolean> DETECT_MACHINE_DETAILS = ConfigKeys.newBooleanConfigKey("detectMachineDetails",
+            "Attempt to detect machine details automatically. Works with SSH-accessible Linux instances.", true);
+
+    public static final ConfigKey<Iterable<String>> PRIVATE_ADDRESSES = ConfigKeys.newConfigKey(
+            new TypeToken<Iterable<String>>() {},
+            "privateAddresses",
+            "Private addresses of this machine, e.g. those within the private network", 
+            null);
+
+    public static final ConfigKey<Map<Integer, String>> TCP_PORT_MAPPINGS = ConfigKeys.newConfigKey(
+            new TypeToken<Map<Integer, String>>() {},
+            "tcpPortMappings",
+            "NAT'ed ports, giving the mapping from private TCP port to a public host:port", 
+            null);
+
+    @SetFromFlag
+    protected String user;
+
+    @SetFromFlag(nullable = false)
+    protected InetAddress address;
+
+    // TODO should not allow this to be set from flag; it is not persisted so that will be lost
+    // (mainly used for localhost currently so not a big problem)
+    @Nullable  // lazily initialized; use getMutexSupport()
+    @SetFromFlag
+    private transient WithMutexes mutexSupport;
+
+    @SetFromFlag
+    private Set<Integer> usedPorts;
+
+    private volatile MachineDetails machineDetails;
+    private final Object machineDetailsLock = new Object();
+
+    public static final ConfigKey<String> SSH_HOST = BrooklynConfigKeys.SSH_CONFIG_HOST;
+    public static final ConfigKey<Integer> SSH_PORT = BrooklynConfigKeys.SSH_CONFIG_PORT;
+
+    public static final ConfigKey<String> SSH_EXECUTABLE = ConfigKeys.newStringConfigKey("sshExecutable",
+            "Allows an `ssh` executable file to be specified, to be used in place of the default (programmatic) java ssh client");
+    public static final ConfigKey<String> SCP_EXECUTABLE = ConfigKeys.newStringConfigKey("scpExecutable",
+            "Allows an `scp` executable file to be specified, to be used in place of the default (programmatic) java ssh client");
+
+    // TODO remove
+    public static final ConfigKey<String> PASSWORD = SshTool.PROP_PASSWORD;
+    public static final ConfigKey<String> PRIVATE_KEY_FILE = SshTool.PROP_PRIVATE_KEY_FILE;
+    public static final ConfigKey<String> PRIVATE_KEY_DATA = SshTool.PROP_PRIVATE_KEY_DATA;
+    public static final ConfigKey<String> PRIVATE_KEY_PASSPHRASE = SshTool.PROP_PRIVATE_KEY_PASSPHRASE;
+
+    public static final ConfigKey<String> SCRIPT_DIR = ConfigKeys.newStringConfigKey(
+            "scriptDir", "directory where scripts should be placed and executed on the SSH target machine");
+    public static final ConfigKey<Map<String,Object>> SSH_ENV_MAP = new MapConfigKey<Object>(
+            Object.class, "env", "environment variables to pass to the remote SSH shell session");
+
+    public static final ConfigKey<Boolean> ALLOCATE_PTY = SshTool.PROP_ALLOCATE_PTY;
+
+    public static final ConfigKey<OutputStream> STDOUT = new BasicConfigKey<OutputStream>(OutputStream.class, "out");
+    public static final ConfigKey<OutputStream> STDERR = new BasicConfigKey<OutputStream>(OutputStream.class, "err");
+    public static final ConfigKey<Boolean> NO_STDOUT_LOGGING = ConfigKeys.newBooleanConfigKey(
+            "noStdoutLogging", "whether to disable logging of stdout from SSH commands (e.g. for verbose commands)", false);
+    public static final ConfigKey<Boolean> NO_STDERR_LOGGING = ConfigKeys.newBooleanConfigKey(
+            "noStderrLogging", "whether to disable logging of stderr from SSH commands (e.g. for verbose commands)", false);
+    public static final ConfigKey<String> LOG_PREFIX = ConfigKeys.newStringConfigKey("logPrefix");
+
+    public static final ConfigKey<String> LOCAL_TEMP_DIR = SshTool.PROP_LOCAL_TEMP_DIR;
+
+    public static final ConfigKey<Boolean> CLOSE_CONNECTION = ConfigKeys.newBooleanConfigKey("close", "Close the SSH connection after use", false);
+    public static final ConfigKey<String> UNIQUE_ID = ConfigKeys.newStringConfigKey("unique", "Unique ID for the SSH connection");
+
+    /**
+     * Specifies config keys where a change in the value does not require a new SshTool instance,
+     * i.e. they can be specified per command on the tool
+     */
+    // TODO: Fully specify.
+    public static final Set<ConfigKey<?>> REUSABLE_SSH_PROPS = ImmutableSet.of(
+            STDOUT, STDERR, SCRIPT_DIR, CLOSE_CONNECTION,
+            SshTool.PROP_SCRIPT_HEADER, SshTool.PROP_PERMISSIONS, SshTool.PROP_LAST_MODIFICATION_DATE,
+            SshTool.PROP_LAST_ACCESS_DATE, SshTool.PROP_OWNER_UID, SshTool.PROP_SSH_RETRY_DELAY);
+
+    public static final Set<HasConfigKey<?>> ALL_SSH_CONFIG_KEYS =
+            ImmutableSet.<HasConfigKey<?>>builder()
+                    .addAll(ConfigUtils.getStaticKeysOnClass(SshMachineLocation.class))
+                    .addAll(ConfigUtils.getStaticKeysOnClass(SshTool.class))
+                    .build();
+
+    public static final Set<String> ALL_SSH_CONFIG_KEY_NAMES =
+            ImmutableSet.copyOf(Iterables.transform(ALL_SSH_CONFIG_KEYS, new Function<HasConfigKey<?>,String>() {
+                @Override
+                public String apply(HasConfigKey<?> input) {
+                    return input.getConfigKey().getName();
+                }
+            }));
+
+    /**
+     * The set of config keys on this location which become default values for properties when invoking an SSH
+     * operation.
+     */
+    @Beta
+    public static final Set<ConfigKey<?>> SSH_CONFIG_GIVEN_TO_PROPS = ImmutableSet.<ConfigKey<?>>of(
+            SCRIPT_DIR);
+
+    private Task<?> cleanupTask;
+    /** callers should use {@link #getSshPoolCache()} */
+    @Nullable 
+    private transient LoadingCache<Map<String, ?>, Pool<SshTool>> sshPoolCacheOrNull;
+
+    public SshMachineLocation() {
+        this(MutableMap.of());
+    }
+
+    public SshMachineLocation(Map properties) {
+        super(properties);
+        usedPorts = (usedPorts != null) ? Sets.newLinkedHashSet(usedPorts) : Sets.<Integer>newLinkedHashSet();
+    }
+
+    @Override
+    public void init() {
+        super.init();
+
+        // Register any pre-existing port-mappings with the PortForwardManager
+        Map<Integer, String> tcpPortMappings = getConfig(TCP_PORT_MAPPINGS);
+        if (tcpPortMappings != null) {
+            PortForwardManager pfm = (PortForwardManager) getManagementContext().getLocationRegistry().resolve("portForwardManager(scope=global)");
+            for (Map.Entry<Integer, String> entry : tcpPortMappings.entrySet()) {
+                int targetPort = entry.getKey();
+                HostAndPort publicEndpoint = HostAndPort.fromString(entry.getValue());
+                if (!publicEndpoint.hasPort()) {
+                    throw new IllegalArgumentException("Invalid portMapping ('"+entry.getValue()+"') for port "+targetPort+" in machine "+this);
+                }
+                pfm.associate(publicEndpoint.getHostText(), publicEndpoint, this, targetPort);
+            }
+        }
+    }
+    
+    private final transient Object poolCacheMutex = new Object();
+    @Nonnull
+    private LoadingCache<Map<String, ?>, Pool<SshTool>> getSshPoolCache() {
+        synchronized (poolCacheMutex) {
+            if (sshPoolCacheOrNull==null) {
+                sshPoolCacheOrNull = buildSshToolPoolCacheLoader();
+                addSshPoolCacheCleanupTask();
+            }
+        }
+        return sshPoolCacheOrNull;
+    }
+
+    private LoadingCache<Map<String, ?>, Pool<SshTool>> buildSshToolPoolCacheLoader() {
+        // TODO: Appropriate numbers for maximum size and expire after access
+        // At the moment every SshMachineLocation instance creates its own pool.
+        // It might make more sense to create one pool and inject it into all SshMachineLocations.
+        Duration expiryDuration = getConfig(SSH_CACHE_EXPIRY_DURATION);
+        
+        LoadingCache<Map<String, ?>, Pool<SshTool>> delegate = CacheBuilder.newBuilder()
+                .maximumSize(10)
+                .expireAfterAccess(expiryDuration.toMilliseconds(), TimeUnit.MILLISECONDS)
+                .recordStats()
+                .removalListener(new RemovalListener<Map<String, ?>, Pool<SshTool>>() {
+                    // TODO: Does it matter that this is synchronous? - Can closing pools cause long delays?
+                    @Override
+                    public void onRemoval(RemovalNotification<Map<String, ?>, Pool<SshTool>> notification) {
+                        Pool<SshTool> removed = notification.getValue();
+                        if (removed == null) {
+                            if (LOG.isDebugEnabled()) {
+                                LOG.debug("Pool evicted from SshTool cache is null so we can't call pool.close(). " +
+                                        "It's probably already been garbage collected. Eviction cause: {} ",
+                                        notification.getCause().name());
+                            }
+                        } else {
+                            if (LOG.isDebugEnabled()) {
+                                LOG.debug("{} evicted from SshTool cache. Eviction cause: {}",
+                                        removed, notification.getCause().name());
+                            }
+                            try {
+                                removed.close();
+                            } catch (IOException e) {
+                                if (LOG.isDebugEnabled()) {
+                                    LOG.debug("Exception closing "+removed, e);
+                                }
+                            }
+                        }
+                    }
+                })
+                .build(new CacheLoader<Map<String, ?>, Pool<SshTool>>() {
+                    public Pool<SshTool> load(Map<String, ?> properties) {
+                        if (LOG.isDebugEnabled()) {
+                            LOG.debug("{} building ssh pool for {} with properties: {}",
+                                    new Object[] {this, getSshHostAndPort(), properties});
+                        }
+                        return buildPool(properties);
+                    }
+                });
+
+        final Set<String> reusableSshProperties = ImmutableSet.copyOf(
+                Iterables.transform(REUSABLE_SSH_PROPS, new Function<ConfigKey<?>, String>() {
+                    @Override public String apply(ConfigKey<?> input) {
+                        return input.getName();
+                    }
+                }));
+        // Groovy-eclipse compiler refused to compile `KeyTransformingSameTypeLoadingCache.from(...)`
+        return new KeyTransformingSameTypeLoadingCache<Map<String, ?>, Pool<SshTool>>(
+                delegate,
+                new Function<Map<String, ?>, Map<String, ?>>() {
+                    @Override
+                    public Map<String, ?> apply(@Nullable Map<String, ?> input) {
+                        Map<String, Object> copy = new HashMap<String, Object>(input);
+                        copy.keySet().removeAll(reusableSshProperties);
+                        return copy;
+                    }
+                });
+    }
+
+    private BasicPool<SshTool> buildPool(final Map<String, ?> properties) {
+        return BasicPool.<SshTool>builder()
+                .name(getDisplayName()+"@"+address+":"+getPort()+
+                        (config().getRaw(SSH_HOST).isPresent() ? "("+getConfig(SSH_HOST)+":"+getConfig(SSH_PORT)+")" : "")+
+                        ":hash"+System.identityHashCode(this))
+                .supplier(new Supplier<SshTool>() {
+                        @Override public SshTool get() {
+                            return connectSsh(properties);
+                        }})
+                .viabilityChecker(new Predicate<SshTool>() {
+                        @Override public boolean apply(SshTool input) {
+                            return input != null && input.isConnected();
+                        }})
+                .closer(new Function<SshTool,Void>() {
+                        @Override public Void apply(SshTool input) {
+                            if (LOG.isDebugEnabled()) {
+                                LOG.debug("{} closing pool for {}", this, input);
+                            }
+                            try {
+                                input.disconnect();
+                            } catch (Exception e) {
+                                if (logSsh.isDebugEnabled()) logSsh.debug("On machine "+SshMachineLocation.this+", ssh-disconnect failed", e);
+                            }
+                            return null;
+                        }})
+                .build();
+    }
+
+    @Override
+    public SshMachineLocation configure(Map<?,?> properties) {
+        super.configure(properties);
+
+        // TODO Note that check for addresss!=null is done automatically in super-constructor, in FlagUtils.checkRequiredFields
+        // Yikes, dangerous code for accessing fields of sub-class in super-class' constructor! But getting away with it so far!
+
+        boolean deferConstructionChecks = (properties.containsKey("deferConstructionChecks") && TypeCoercions.coerce(properties.get("deferConstructionChecks"), Boolean.class));
+        if (!deferConstructionChecks) {
+            if (getDisplayName() == null) {
+                setDisplayName((truth(user) ? user+"@" : "") + address.getHostName());
+            }
+        }
+        return this;
+    }
+    
+    private transient final Object mutexSupportCreationLock = new Object();
+    protected WithMutexes getMutexSupport() {
+        synchronized (mutexSupportCreationLock) {
+            // create on demand so that it is not null after serialization
+            if (mutexSupport == null) {
+                mutexSupport = new MutexSupport();
+            }
+            return mutexSupport;
+        }
+    }
+    
+    protected void addSshPoolCacheCleanupTask() {
+        if (cleanupTask!=null && !cleanupTask.isDone()) {
+            return;
+        }
+        if (getManagementContext()==null || getManagementContext().getExecutionManager()==null) {
+            LOG.debug("No management context for "+this+"; ssh-pool cache will only be closed when machine is closed");
+            return;
+        }
+        
+        Callable<Task<?>> cleanupTaskFactory = new Callable<Task<?>>() {
+            @Override public Task<Void> call() {
+                return Tasks.<Void>builder().dynamic(false).tag(BrooklynTaskTags.TRANSIENT_TASK_TAG)
+                    .name("ssh-location cache cleaner").body(new Callable<Void>() {
+                    @Override public Void call() {
+                        try {
+                            if (sshPoolCacheOrNull != null) sshPoolCacheOrNull.cleanUp();
+                            if (!SshMachineLocation.this.isManaged()) {
+                                if (sshPoolCacheOrNull != null) sshPoolCacheOrNull.invalidateAll();
+                                cleanupTask.cancel(false);
+                                sshPoolCacheOrNull = null;
+                            }
+                            return null;
+                        } catch (Exception e) {
+                            // Don't rethrow: the behaviour of executionManager is different from a scheduledExecutorService,
+                            // if we throw an exception, then our task will never get executed again
+                            LOG.warn("Problem cleaning up ssh-pool-cache", e);
+                            return null;
+                        } catch (Throwable t) {
+                            LOG.warn("Problem cleaning up ssh-pool-cache (rethrowing)", t);
+                            throw Exceptions.propagate(t);
+                        }
+                    }}).build();
+            }
+        };
+        
+        Duration expiryDuration = getConfig(SSH_CACHE_EXPIRY_DURATION);
+        cleanupTask = getManagementContext().getExecutionManager().submit(new ScheduledTask(
+            MutableMap.of("displayName", "scheduled[ssh-location cache cleaner]"), cleanupTaskFactory).period(expiryDuration));
+    }
+    
+    // TODO close has been used for a long time to perform clean-up wanted on unmanagement, but that's not clear; 
+    // we should probably expose a mechanism such as that in Entity (or re-use Entity for locations!)
+    @Override
+    public void close() throws IOException {
+        if (sshPoolCacheOrNull != null) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("{} invalidating all entries in ssh pool cache. Final stats: {}", this, sshPoolCacheOrNull.stats());
+            }
+            sshPoolCacheOrNull.invalidateAll();
+        }
+        if (cleanupTask != null) {
+            cleanupTask.cancel(false);
+            cleanupTask = null;
+            sshPoolCacheOrNull = null;
+        }
+    }
+
+    // should not be necessary, and causes objects to be kept around a lot longer than desired
+//    @Override
+//    protected void finalize() throws Throwable {
+//        try {
+//            close();
+//        } finally {
+//            super.finalize();
+//        }
+//    }
+
+    @Override
+    public InetAddress getAddress() {
+        return address;
+    }
+
+    @Override
+    public String getHostname() {
+        String hostname = address.getHostName();
+        return (hostname == null || hostname.equals(address.getHostAddress())) ? null : hostname;
+    }
+    
+    @Override
+    public Set<String> getPublicAddresses() {
+        return ImmutableSet.of(address.getHostAddress());
+    }
+    
+    @Override
+    public Set<String> getPrivateAddresses() {
+        Iterable<String> result = getConfig(PRIVATE_ADDRESSES);
+        return (result == null) ? ImmutableSet.<String>of() : ImmutableSet.copyOf(result);
+    }
+
+    public HostAndPort getSshHostAndPort() {
+        String host = getConfig(SSH_HOST);
+        if (host == null || Strings.isEmpty(host))
+            host = address.getHostName();
+        Integer port = getConfig(SSH_PORT);
+        if (port == null || port == 0)
+            port = 22;
+        return HostAndPort.fromParts(host, port);
+    }
+
+    public String getUser() {
+        if (!truth(user)) {
+            if (config().getLocalRaw(SshTool.PROP_USER).isPresent()) {
+                LOG.warn("User configuration for "+this+" set after deployment; deprecated behaviour may not be supported in future versions");
+            }
+            return getConfig(SshTool.PROP_USER);
+        }
+        return user;
+    }
+
+    /** port for SSHing */
+    public int getPort() {
+        return getConfig(SshTool.PROP_PORT);
+    }
+
+    protected <T> T execSsh(final Map<String, ?> props, final Function<ShellTool, T> task) {
+        final LoadingCache<Map<String, ?>, Pool<SshTool>> sshPoolCache = getSshPoolCache();
+        Pool<SshTool> pool = sshPoolCache.getUnchecked(props);
+        if (LOG.isTraceEnabled()) {
+            LOG.trace("{} execSsh got pool: {}", this, pool);
+        }
+
+        if (truth(props.get(CLOSE_CONNECTION.getName()))) {
+            Function<SshTool, T> close = new Function<SshTool, T>() {
+                @Override
+                public T apply(SshTool input) {
+                    T result = task.apply(input);
+                    if (LOG.isDebugEnabled()) {
+                        LOG.debug("{} invalidating all sshPoolCache entries: {}", SshMachineLocation.this, sshPoolCache.stats().toString());
+                    }
+                    sshPoolCache.invalidateAll();
+                    sshPoolCache.cleanUp();
+                    return result;
+                }
+            };
+            return pool.exec(close);
+        } else {
+            return pool.exec(task);
+        }
+    }
+
+    protected SshTool connectSsh() {
+        return connectSsh(ImmutableMap.of());
+    }
+
+    protected boolean previouslyConnected = false;
+    protected SshTool connectSsh(Map props) {
+        try {
+            if (!truth(user)) {
+                String newUser = getUser();
+                if (LOG.isTraceEnabled()) LOG.trace("For "+this+", setting user in connectSsh: oldUser="+user+"; newUser="+newUser);
+                user = newUser;
+            }
+
+            ConfigBag args = new ConfigBag()
+                .configure(SshTool.PROP_USER, user)
+                // default value of host, overridden if SSH_HOST is supplied
+                .configure(SshTool.PROP_HOST, address.getHostName());
+
+            for (Map.Entry<String,Object> entry: config().getBag().getAllConfig().entrySet()) {
+                String key = entry.getKey();
+                if (key.startsWith(SshTool.BROOKLYN_CONFIG_KEY_PREFIX)) {
+                    key = Strings.removeFromStart(key, SshTool.BROOKLYN_CONFIG_KEY_PREFIX);
+                } else if (ALL_SSH_CONFIG_KEY_NAMES.contains(entry.getKey())) {
+                    // key should be included, and does not need to be changed
+
+                    // TODO make this config-setting mechanism more universal
+                    // currently e.g. it will not admit a tool-specific property.
+                    // thinking either we know about the tool here,
+                    // or we don't allow unadorned keys to be set
+                    // (require use of BROOKLYN_CONFIG_KEY_PREFIX)
+                } else {
+                    // this key is not applicable here; ignore it
+                    continue;
+                }
+                args.putStringKey(key, entry.getValue());
+            }
+
+            // Explicit props trump all.
+            args.putAll(props);
+
+            if (LOG.isTraceEnabled()) LOG.trace("creating ssh session for "+args);
+            if (!user.equals(args.get(SshTool.PROP_USER))) {
+                LOG.warn("User mismatch configuring ssh for "+this+": preferring user "+args.get(SshTool.PROP_USER)+" over "+user);
+                user = args.get(SshTool.PROP_USER);
+            }
+
+            // look up tool class
+            String sshToolClass = args.get(SshTool.PROP_TOOL_CLASS);
+            if (sshToolClass==null) sshToolClass = SshjTool.class.getName();
+            SshTool ssh = (SshTool) Class.forName(sshToolClass).getConstructor(Map.class).newInstance(args.getAllConfig());
+
+            if (LOG.isTraceEnabled()) LOG.trace("using ssh-tool {} (of type {}); props ", ssh, sshToolClass);
+
+            Tasks.setBlockingDetails("Opening ssh connection");
+            try { ssh.connect(); } finally { Tasks.setBlockingDetails(null); }
+            previouslyConnected = true;
+            return ssh;
+        } catch (Exception e) {
+            if (previouslyConnected) throw Throwables.propagate(e);
+            // subsequence connection (above) most likely network failure, our remarks below won't help
+            // on first connection include additional information if we can't connect, to help with debugging
+            String rootCause = Throwables.getRootCause(e).getMessage();
+            throw new IllegalStateException("Cannot establish ssh connection to "+user+" @ "+this+
+                    (rootCause!=null && !rootCause.isEmpty() ? " ("+rootCause+")" : "")+". \n"+
+                    "Ensure that passwordless and passphraseless ssh access is enabled using standard keys from ~/.ssh or " +
+                    "as configured in brooklyn.properties. " +
+                    "Check that the target host is accessible, " +
+                    "that credentials are correct (location and permissions if using a key), " +
+                    "that the SFTP subsystem is available on the remote side, " +
+                    "and that there is sufficient random noise in /dev/random on both ends. " +
+                    "To debug less common causes, see the original error in the trace or log, and/or enable 'net.schmizz' (sshj) logging."
+                    , e);
+        }
+    }
+
+    // TODO submitCommands and submitScript which submit objects we can subsequently poll (cf JcloudsSshMachineLocation.submitRunScript)
+
+    /**
+     * Executes a set of commands, directly on the target machine (no wrapping in script).
+     * Joined using {@literal ;} by default.
+     * <p>
+     * Stdout and stderr will be logged automatically to brooklyn.SSH logger, unless the
+     * flags 'noStdoutLogging' and 'noStderrLogging' are set. To set a logging prefix, use
+     * the flag 'logPrefix'.
+     * <p>
+     * Currently runs the commands in an interactive/login shell
+     * by passing each as a line to bash. To terminate early, use:
+     * <pre>
+     * foo || exit 1
+     * </pre>
+     * It may be desirable instead, in some situations, to wrap as:
+     * <pre>
+     * { line1 ; } && { line2 ; } ...
+     * </pre>
+     * and run as a single command (possibly not as an interacitve/login
+     * shell) causing the script to exit on the first command which fails.
+     * <p>
+     * Currently this has to be done by the caller.
+     * (If desired we can add a flag {@code exitIfAnyNonZero} to support this mode,
+     * and/or {@code commandPrepend} and {@code commandAppend} similar to
+     * (currently supported in SshjTool) {@code separator}.)
+     */
+    public int execCommands(String summaryForLogging, List<String> commands) {
+        return execCommands(MutableMap.<String,Object>of(), summaryForLogging, commands, MutableMap.<String,Object>of());
+    }
+    public int execCommands(Map<String,?> props, String summaryForLogging, List<String> commands) {
+        return execCommands(props, summaryForLogging, commands, MutableMap.<String,Object>of());
+    }
+    public int execCommands(String summaryForLogging, List<String> commands, Map<String,?> env) {
+        return execCommands(MutableMap.<String,Object>of(), summaryForLogging, commands, env);
+    }
+    public int execCommands(Map<String,?> props, String summaryForLogging, List<String> commands, Map<String,?> env) {
+        return newExecWithLoggingHelpers().execCommands(augmentPropertiesWithSshConfigGivenToProps(props), summaryForLogging, commands, env);
+    }
+
+    /**
+     * Executes a set of commands, wrapped as a script sent to the remote machine.
+     * <p>
+     * Stdout and stderr will be logged automatically to brooklyn.SSH logger, unless the
+     * flags 'noStdoutLogging' and 'noStderrLogging' are set. To set a logging prefix, use
+     * the flag 'logPrefix'.
+     */
+    public int execScript(String summaryForLogging, List<String> commands) {
+        return execScript(MutableMap.<String,Object>of(), summaryForLogging, commands, MutableMap.<String,Object>of());
+    }
+    public int execScript(Map<String,?> props, String summaryForLogging, List<String> commands) {
+        return execScript(props, summaryForLogging, commands, MutableMap.<String,Object>of());
+    }
+    public int execScript(String summaryForLogging, List<String> commands, Map<String,?> env) {
+        return execScript(MutableMap.<String,Object>of(), summaryForLogging, commands, env);
+    }
+    public int execScript(Map<String,?> props, String summaryForLogging, List<String> commands, Map<String,?> env) {
+        return newExecWithLoggingHelpers().execScript(augmentPropertiesWithSshConfigGivenToProps(props), summaryForLogging, commands, env);
+    }
+
+    private Map<String, Object> augmentPropertiesWithSshConfigGivenToProps(Map<String, ?> props) {
+        Map<String,Object> augmentedProps = Maps.newHashMap(props);
+        for (ConfigKey<?> config : SSH_CONFIG_GIVEN_TO_PROPS) {
+            if (!augmentedProps.containsKey(config.getName()) && hasConfig(config, true))
+                augmentedProps.put(config.getName(), getConfig(config));
+        }
+        return augmentedProps;
+    }
+
+    protected ExecWithLoggingHelpers newExecWithLoggingHelpers() {
+        return new ExecWithLoggingHelpers("SSH") {
+            @Override
+            protected <T> T execWithTool(MutableMap<String, Object> props, Function<ShellTool, T> function) {
+                return execSsh(props, function);
+            }
+            @Override
+            protected void preExecChecks() {
+                Preconditions.checkNotNull(address, "host address must be specified for ssh");
+            }
+            @Override
+            protected String constructDefaultLoggingPrefix(ConfigBag execFlags) {
+                String hostname = getAddress().getHostName();
+                Integer port = execFlags.peek(SshTool.PROP_PORT);
+                if (port == null) port = getConfig(ConfigUtils.prefixedKey(SshTool.BROOKLYN_CONFIG_KEY_PREFIX, SshTool.PROP_PORT));
+                return (user != null ? user+"@" : "") + hostname + (port != null ? ":"+port : "");
+            }
+            @Override
+            protected String getTargetName() {
+                return ""+SshMachineLocation.this;
+            }
+        }.logger(logSsh);
+    }
+
+    /**
+     * @deprecated since 0.7.0; use {@link #execCommands(Map, String, List, Map), and rely on that calling the execWithLogging
+     */
+    @SuppressWarnings({"rawtypes", "unchecked"})
+    @Deprecated
+    protected int execWithLogging(Map<String,?> props, String summaryForLogging, List<String> commands, Map env, final Closure<Integer> execCommand) {
+        return newExecWithLoggingHelpers().execWithLogging(props, summaryForLogging, commands, env, new ExecRunner() {
+                @Override public int exec(ShellTool ssh, Map<String, ?> flags, List<String> cmds, Map<String, ?> env) {
+                    return execCommand.call(ssh, flags, cmds, env);
+                }});
+    }
+
+    public int copyTo(File src, File destination) {
+        return copyTo(MutableMap.<String,Object>of(), src, destination);
+    }
+    public int copyTo(Map<String,?> props, File src, File destination) {
+        return copyTo(props, src, destination.getPath());
+    }
+
+    public int copyTo(File src, String destination) {
+        return copyTo(MutableMap.<String,Object>of(), src, destination);
+    }
+    public int copyTo(Map<String,?> props, File src, String destination) {
+        Preconditions.checkNotNull(address, "Host address must be specified for scp");
+        Preconditions.checkArgument(src.exists(), "File %s must exist for scp", src.getPath());
+        try {
+            return copyTo(props, new FileInputStream(src), src.length(), destination);
+        } catch (FileNotFoundException e) {
+            throw Throwables.propagate(e);
+        }
+    }
+    public int copyTo(Reader src, String destination) {
+        return copyTo(MutableMap.<String,Object>of(), src, destination);
+    }
+    public int copyTo(Map<String,?> props, Reader src, String destination) {
+        return copyTo(props, new ReaderInputStream(src), destination);
+    }
+    public int copyTo(InputStream src, String destination) {
+        return copyTo(MutableMap.<String,Object>of(), src, destination);
+    }
+    public int copyTo(InputStream src, long filesize, String destination) {
+        return copyTo(MutableMap.<String,Object>of(), src, filesize, destination);
+    }
+    // FIXME the return code is not a reliable indicator of success or failure
+    public int copyTo(final Map<String,?> props, final InputStream src, final long filesize, final String destination) {
+        if (filesize == -1) {
+            return copyTo(props, src, destination);
+        } else {
+            return execSsh(props, new Function<ShellTool,Integer>() {
+                public Integer apply(ShellTool ssh) {
+                    return ((SshTool) ssh).copyToServer(props, new KnownSizeInputStream(src, filesize), destination);
+                }});
+        }
+    }
+    // FIXME the return code is not a reliable indicator of success or failure
+    // Closes input stream before returning
+    public int copyTo(final Map<String,?> props, final InputStream src, final String destination) {
+        return execSsh(props, new Function<ShellTool,Integer>() {
+            public Integer apply(ShellTool ssh) {
+                return ((SshTool)ssh).copyToServer(props, src, destination);
+            }});
+    }
+
+    // FIXME the return code is not a reliable indicator of success or failure
+    public int copyFrom(String remote, String local) {
+        return copyFrom(MutableMap.<String,Object>of(), remote, local);
+    }
+    public int copyFrom(final Map<String,?> props, final String remote, final String local) {
+        return execSsh(props, new Function<ShellTool,Integer>() {
+            public Integer apply(ShellTool ssh) {
+                return ((SshTool)ssh).copyFromServer(props, remote, new File(local));
+            }});
+    }
+
+    public int installTo(String url, String destPath) {
+        return installTo(MutableMap.<String, Object>of(), url, destPath);
+    }
+
+    public int installTo(Map<String,?> props, String url, String destPath) {
+        return installTo(ResourceUtils.create(this), props, url, destPath);
+    }
+
+    public int installTo(ResourceUtils loader, String url, String destPath) {
+        return installTo(loader, MutableMap.<String, Object>of(), url, destPath);
+    }
+
+    /**
+     * Installs the given URL at the indicated destination path.
+     * <p>
+     * Attempts to curl the source URL on the remote machine,
+     * then if that fails, loads locally (from classpath or file) and transfers.
+     * <p>
+     * Use {@link ArchiveUtils} to handle directories and their contents properly.
+     *
+     * TODO allow s3://bucket/file URIs for AWS S3 resources
+     * TODO use PAX-URL style URIs for maven artifacts
+     * TODO use subtasks here for greater visibility?; deprecate in favour of SshTasks.installFromUrl?
+     *
+     * @param utils A {@link ResourceUtils} that can resolve the source URLs
+     * @param url The source URL to be installed
+     * @param destPath The file to be created on the destination
+     *
+     * @see ArchiveUtils#deploy(String, SshMachineLocation, String)
+     * @see ArchiveUtils#deploy(String, SshMachineLocation, String, String)
+     * @see ResourceUtils#getResourceFromUrl(String)
+     */
+    public int installTo(ResourceUtils utils, Map<String,?> props, String url, String destPath) {
+        LOG.debug("installing {} to {} on {}, attempting remote curl", new Object[] { url, destPath, this });
+
+        try {
+            PipedInputStream insO = new PipedInputStream(); OutputStream outO = new PipedOutputStream(insO);
+            PipedInputStream insE = new PipedInputStream(); OutputStream outE = new PipedOutputStream(insE);
+            StreamGobbler sgsO = new StreamGobbler(insO, null, LOG); sgsO.setLogPrefix("[curl @ "+address+":stdout] ").start();
+            StreamGobbler sgsE = new StreamGobbler(insE, null, LOG); sgsE.setLogPrefix("[curl @ "+address+":stdout] ").start();
+            Map<String, ?> sshProps = MutableMap.<String, Object>builder().putAll(props).put("out", outO).put("err", outE).build();
+            int result = execScript(sshProps, "copying remote resource "+url+" to server",  ImmutableList.of(
+                    BashCommands.INSTALL_CURL, // TODO should hold the 'installing' mutex
+                    "mkdir -p `dirname '"+destPath+"'`",
+                    "curl "+url+" -L --silent --insecure --show-error --fail --connect-timeout 60 --max-time 600 --retry 5 -o '"+destPath+"'"));
+            sgsO.close();
+            sgsE.close();
+            if (result != 0) {
+                LOG.debug("installing {} to {} on {}, curl failed, attempting local fetch and copy", new Object[] { url, destPath, this });
+                try {
+                    Tasks.setBlockingDetails("retrieving resource "+url+" for copying across");
+                    InputStream stream = utils.getResourceFromUrl(url);
+                    Tasks.setBlockingDetails("copying resource "+url+" to server");
+                    result = copyTo(props, stream, destPath);
+                } finally {
+                    Tasks.setBlockingDetails(null);
+                }
+            }
+            if (result == 0) {
+                LOG.debug("installing {} complete; {} on {}", new Object[] { url, destPath, this });
+            } else {
+                LOG.warn("installing {} failed; {} on {}: {}", new Object[] { url, destPath, this, result });
+            }
+            return result;
+        } catch (IOException e) {
+            throw Throwables.propagate(e);
+        }
+    }
+
+    @Override
+    public String toString() {
+        return "SshMachineLocation["+getDisplayName()+":"+address+":"+getPort()+"@"+getId()+"]";
+    }
+
+    @Override
+    public String toVerboseString() {
+        return Objects.toStringHelper(this).omitNullValues()
+                .add("id", getId()).add("name", getDisplayName())
+                .add("user", getUser()).add("address", getAddress()).add("port", getPort())
+                .add("parentLocation", getParent())
+                .toString();
+    }
+
+    /**
+     * @see #obtainPort(PortRange)
+     * @see PortRanges#ANY_HIGH_PORT
+     */
+    @Override
+    public boolean obtainSpecificPort(int portNumber) {
+        synchronized (usedPorts) {
+            // TODO Does not yet check if the port really is free on this machine
+            if (usedPorts.contains(portNumber)) {
+                return false;
+            } else {
+                usedPorts.add(portNumber);
+                return true;
+            }
+        }
+    }
+
+    @Override
+    public int obtainPort(PortRange range) {
+        synchronized (usedPorts) {
+            for (int p: range)
+                if (obtainSpecificPort(p)) return p;
+            if (LOG.isDebugEnabled()) LOG.debug("unable to find port in {} on {}; returning -1", range, this);
+            return -1;
+        }
+    }
+
+    @Override
+    public void releasePort(int portNumber) {
+        synchronized (usedPorts) {
+            usedPorts.remove((Object) portNumber);
+        }
+    }
+
+    public boolean isSshable() {
+        String cmd = "date";
+        try {
+            try {
+                Socket s = new Socket();
+                s.connect(new InetSocketAddress(getAddress(), getPort()), SSHABLE_CONNECT_TIMEOUT);
+                s.close();
+            } catch (IOException e) {
+                if (LOG.isDebugEnabled()) LOG.debug(""+this+" not [yet] reachable (socket "+getAddress()+":"+getPort()+"): "+e);
+                return false;
+            }
+            // this should do execCommands because sftp subsystem might not be available (or sometimes seems to take a while for it to become so?)
+            int result = execCommands(MutableMap.<String,Object>of(), "isSshable", ImmutableList.of(cmd));
+            if (result == 0) {
+                return true;
+            } else {
+                if (LOG.isDebugEnabled()) LOG.debug("Not reachable: {}, executing `{}`, exit code {}", new Object[] {this, cmd, result});
+                return false;
+            }
+        } catch (SshException e) {
+            if (LOG.isDebugEnabled()) LOG.debug("Exception checking if "+this+" is reachable; assuming not", e);
+            return false;
+        } catch (IllegalStateException e) {
+            if (LOG.isDebugEnabled()) LOG.debug("Exception checking if "+this+" is reachable; assuming not", e);
+            return false;
+        } catch (RuntimeException e) {
+            if (Exceptions.getFirstThrowableOfType(e, IOException.class) != null) {
+                if (LOG.isDebugEnabled()) LOG.debug("Exception checking if "+this+" is reachable; assuming not", e);
+                return false;
+            } else {
+                throw e;
+            }
+        }
+    }
+
+    @Override
+    public OsDetails getOsDetails() {
+        return getMachineDetails().getOsDetails();
+    }
+
+    @Override
+    public MachineDetails getMachineDetails() {
+        synchronized (machineDetailsLock) {
+            if (machineDetails == null) {
+                machineDetails = getConfig(MACHINE_DETAILS);
+            }
+            if (machineDetails == null) {
+                machineDetails = inferMachineDetails();
+            }
+        }
+        return machineDetails;
+    }
+
+    protected MachineDetails inferMachineDetails() {
+        boolean detectionEnabled = getConfig(DETECT_MACHINE_DETAILS);
+        if (!detectionEnabled)
+            return new BasicMachineDetails(new BasicHardwareDetails(-1, -1), new BasicOsDetails("UNKNOWN", "UNKNOWN", "UNKNOWN"));
+
+        Tasks.setBlockingDetails("Waiting for machine details");
+        try {
+            return BasicMachineDetails.forSshMachineLocationLive(this);
+        } finally {
+            Tasks.resetBlockingDetails();
+        }
+    }
+
+    @Override
+    public void acquireMutex(String mutexId, String description) throws RuntimeInterruptedException {
+        try {
+            getMutexSupport().acquireMutex(mutexId, description);
+        } catch (InterruptedException ie) {
+            throw new RuntimeInterruptedException("Interrupted waiting for mutex: " + mutexId, ie);
+        }
+    }
+
+    @Override
+    public boolean tryAcquireMutex(String mutexId, String description) {
+        return getMutexSupport().tryAcquireMutex(mutexId, description);
+    }
+
+    @Override
+    public void releaseMutex(String mutexId) {
+        getMutexSupport().releaseMutex(mutexId);
+    }
+
+    @Override
+    public boolean hasMutex(String mutexId) {
+        return getMutexSupport().hasMutex(mutexId);
+    }
+
+    //We want the SshMachineLocation to be serializable and therefore the pool needs to be dealt with correctly.
+    //In this case we are not serializing the pool (we made the field transient) and create a new pool when deserialized.
+    //This fix is currently needed for experiments, but isn't used in normal Brooklyn usage.
+    private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
+        in.defaultReadObject();
+        getSshPoolCache();
+    }
+
+    /** returns the un-passphrased key-pair info if a key is being used, or else null */
+    public KeyPair findKeyPair() {
+        String fn = getConfig(SshTool.PROP_PRIVATE_KEY_FILE);
+        ResourceUtils r = ResourceUtils.create(this);
+        if (fn!=null) return SecureKeys.readPem(r.getResourceFromUrl(fn), getConfig(SshTool.PROP_PRIVATE_KEY_PASSPHRASE));
+        String data = getConfig(SshTool.PROP_PRIVATE_KEY_DATA);
+        if (data!=null) return SecureKeys.readPem(new ReaderInputStream(new StringReader(data)), getConfig(SshTool.PROP_PRIVATE_KEY_PASSPHRASE));
+        if (findPassword()!=null)
+            // if above not specified, and password is, use password
+            return null;
+        // fall back to id_rsa and id_dsa
+        if (new File( Urls.mergePaths(System.getProperty("user.home"), ".ssh/id_rsa") ).exists() )
+            return SecureKeys.readPem(r.getResourceFromUrl("~/.ssh/id_rsa"), getConfig(SshTool.PROP_PRIVATE_KEY_PASSPHRASE));
+        if (new File( Urls.mergePaths(System.getProperty("user.home"), ".ssh/id_dsa") ).exists() )
+            return SecureKeys.readPem(r.getResourceFromUrl("~/.ssh/id_dsa"), getConfig(SshTool.PROP_PRIVATE_KEY_PASSPHRASE));
+        LOG.warn("Unable to extract any key or passphrase data in request to findKeyPair for "+this);
+        return null;
+    }
+
+    /** returns the password being used to log in, if a password is being used, or else null */
+    public String findPassword() {
+        return getConfig(SshTool.PROP_PASSWORD);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/winrm/AdvertiseWinrmLoginPolicy.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/winrm/AdvertiseWinrmLoginPolicy.java b/core/src/main/java/org/apache/brooklyn/location/winrm/AdvertiseWinrmLoginPolicy.java
new file mode 100644
index 0000000..549d45a
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/winrm/AdvertiseWinrmLoginPolicy.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.winrm;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.api.sensor.SensorEvent;
+import org.apache.brooklyn.api.sensor.SensorEventListener;
+import org.apache.brooklyn.entity.core.AbstractEntity;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.policy.core.AbstractPolicy;
+import org.apache.brooklyn.sensor.core.Sensors;
+
+import com.google.common.annotations.Beta;
+
+/**
+ * When attached to an entity, this will monitor for when an {@link WinRmMachineLocation} is added to that entity
+ * (e.g. when a VM has been provisioned for it).
+ * 
+ * The policy will then add a sensor that advertises the Administrator login details.
+ * 
+ * A preferred mechanism would be for an external key-management tool to provide access to the credentials.
+ */
+@Beta
+public class AdvertiseWinrmLoginPolicy extends AbstractPolicy implements SensorEventListener<Location> {
+
+    // TODO Would like support user-creation over WinRM
+    
+    private static final Logger LOG = LoggerFactory.getLogger(AdvertiseWinrmLoginPolicy.class);
+
+    public static final AttributeSensor<String> VM_USER_CREDENTIALS = Sensors.newStringSensor(
+            "vm.user.credentials",
+            "The \"<user> : <password> @ <hostname>:<port>\"");
+
+    public void setEntity(EntityLocal entity) {
+        super.setEntity(entity);
+        subscribe(entity, AbstractEntity.LOCATION_ADDED, this);
+    }
+
+    @Override
+    public void onEvent(SensorEvent<Location> event) {
+        final Entity entity = event.getSource();
+        final Location loc = event.getValue();
+        if (loc instanceof WinRmMachineLocation) {
+            advertiseUserAsync(entity, (WinRmMachineLocation)loc);
+        }
+    }
+
+    protected void advertiseUserAsync(final Entity entity, final WinRmMachineLocation machine) {
+        String user = machine.getUser();
+        String hostname = machine.getHostname();
+        int port = machine.config().get(WinRmMachineLocation.WINRM_PORT);
+        String password = machine.config().get(WinRmMachineLocation.PASSWORD);
+        
+        String creds = user + " : " + password + " @ " +hostname + ":" + port;
+        
+        LOG.info("Advertising user "+user+" @ "+hostname+":"+port);
+        
+        ((EntityLocal)entity).setAttribute(VM_USER_CREDENTIALS, creds);
+    }
+}


[25/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefConfigs.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefConfigs.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefConfigs.java
new file mode 100644
index 0000000..f572b1f
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefConfigs.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.MapConfigKey.MapModifications;
+import org.apache.brooklyn.core.config.SetConfigKey.SetModifications;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.apache.brooklyn.util.git.GithubUrls;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Preconditions;
+
+/** Conveniences for configuring brooklyn Chef entities 
+ * @since 0.6.0 */
+@Beta
+public class ChefConfigs {
+
+    public static void addToLaunchRunList(EntitySpec<?> entity, String ...recipes) {
+        for (String recipe: recipes)
+            entity.configure(ChefConfig.CHEF_LAUNCH_RUN_LIST, SetModifications.addItem(recipe));
+    }
+
+    public static void addToLaunchRunList(EntityInternal entity, String ...recipes) {
+        for (String recipe: recipes)
+            entity.setConfig(ChefConfig.CHEF_LAUNCH_RUN_LIST, SetModifications.addItem(recipe));
+    }
+
+    public static void addToCookbooksFromGithub(EntitySpec<?> entity, String ...cookbookNames) {
+        for (String cookbookName: cookbookNames)
+            addToCookbooksFromGithub(entity, cookbookName, getGithubOpscodeRepo(cookbookName)); 
+    }
+    
+    public static void addToCookbooksFromGithub(EntityInternal entity, String ...cookbookNames) {
+        for (String cookbookName: cookbookNames)
+            addToCookbooksFromGithub(entity, cookbookName, getGithubOpscodeRepo(cookbookName)); 
+    }
+
+    public static String getGithubOpscodeRepo(String cookbookName) {
+        return getGithubOpscodeRepo(cookbookName, "master");
+    }
+    public static String getGithubOpscodeRepo(String cookbookName, String tag) {
+        return GithubUrls.tgz("opscode-cookbooks", cookbookName, tag);
+    }
+    
+    public static void addToCookbooksFromGithub(EntitySpec<?> entity, String cookbookName, String cookbookUrl) {
+        entity.configure(ChefConfig.CHEF_COOKBOOK_URLS.subKey(cookbookName), cookbookUrl);
+    }
+
+    public static void addToCookbooksFromGithub(EntityInternal entity, String cookbookName, String cookbookUrl) {
+        entity.setConfig(ChefConfig.CHEF_COOKBOOK_URLS.subKey(cookbookName), cookbookUrl);
+    }
+
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public static void addLaunchAttributes(EntitySpec<?> entity, Map<? extends Object,? extends Object> attributesMap) {
+        entity.configure(ChefConfig.CHEF_LAUNCH_ATTRIBUTES, MapModifications.add((Map)attributesMap));
+    }
+    
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public static void addLaunchAttributes(EntityInternal entity, Map<? extends Object,? extends Object> attributesMap) {
+        entity.setConfig(ChefConfig.CHEF_LAUNCH_ATTRIBUTES, MapModifications.add((Map)attributesMap));
+    }
+    
+    /** replaces the attributes underneath the rootAttribute parameter with the given value;
+     * see {@link #addLaunchAttributesMap(EntitySpec, Map)} for richer functionality */
+    public static void setLaunchAttribute(EntitySpec<?> entity, String rootAttribute, Object value) {
+        entity.configure(ChefConfig.CHEF_LAUNCH_ATTRIBUTES.subKey(rootAttribute), value);
+    }
+    
+    /** replaces the attributes underneath the rootAttribute parameter with the given value;
+     * see {@link #addLaunchAttributesMap(EntitySpec, Map)} for richer functionality */
+    public static void setLaunchAttribute(EntityInternal entity, String rootAttribute, Object value) {
+        entity.setConfig(ChefConfig.CHEF_LAUNCH_ATTRIBUTES.subKey(rootAttribute), value);
+    }
+
+    public static <T> T getRequiredConfig(Entity entity, ConfigKey<T> key) {
+        return Preconditions.checkNotNull(
+                Preconditions.checkNotNull(entity, "Entity must be supplied").getConfig(key), 
+                "Key "+key+" is required on "+entity);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefEntity.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefEntity.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefEntity.java
new file mode 100644
index 0000000..1b1f866
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefEntity.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+
+@ImplementedBy(ChefEntityImpl.class)
+public interface ChefEntity extends SoftwareProcess, ChefConfig {
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefEntityImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefEntityImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefEntityImpl.java
new file mode 100644
index 0000000..911b546
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefEntityImpl.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+import org.apache.brooklyn.entity.stock.EffectorStartableImpl;
+import org.apache.brooklyn.util.text.Strings;
+
+public class ChefEntityImpl extends EffectorStartableImpl implements ChefEntity {
+
+    public void init() {
+        String primaryName = getConfig(CHEF_COOKBOOK_PRIMARY_NAME);
+        if (!Strings.isBlank(primaryName)) setDefaultDisplayName(primaryName+" (chef)");
+        
+        super.init();
+        new ChefLifecycleEffectorTasks().attachLifecycleEffectors(this);
+    }
+
+    @Override
+    public void populateServiceNotUpDiagnostics() {
+        // TODO no-op currently; should check ssh'able etc
+    }    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefLifecycleEffectorTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefLifecycleEffectorTasks.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefLifecycleEffectorTasks.java
new file mode 100644
index 0000000..e4cbf1c
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefLifecycleEffectorTasks.java
@@ -0,0 +1,360 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+import java.util.Collection;
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.lifecycle.MachineLifecycleEffectorTasks;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.location.basic.Machines;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
+import org.apache.brooklyn.util.collections.Jsonya;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.collections.Jsonya.Navigator;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.TaskTags;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.net.Urls;
+import org.apache.brooklyn.util.ssh.BashCommands;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Supplier;
+import com.google.common.collect.ImmutableList;
+
+/** 
+ * Creates effectors to start, restart, and stop processes using Chef.
+ * <p>
+ * Instances of this should use the {@link ChefConfig} config attributes to configure startup,
+ * and invoke {@link #usePidFile(String)} or {@link #useService(String)} to determine check-running and stop behaviour.
+ * Alternatively this can be subclassed and {@link #postStartCustom()} and {@link #stopProcessesAtMachine()} overridden.
+ * 
+ * @since 0.6.0
+ **/
+@Beta
+public class ChefLifecycleEffectorTasks extends MachineLifecycleEffectorTasks implements ChefConfig {
+
+    private static final Logger log = LoggerFactory.getLogger(ChefLifecycleEffectorTasks.class);
+    
+    protected String _pidFile, _serviceName, _windowsServiceName;
+    
+    public ChefLifecycleEffectorTasks() {
+    }
+    
+    public ChefLifecycleEffectorTasks usePidFile(String pidFile) {
+        this._pidFile = pidFile;
+        return this;
+    }
+    public ChefLifecycleEffectorTasks useService(String serviceName) {
+        this._serviceName = serviceName;
+        return this;
+    }
+    public ChefLifecycleEffectorTasks useWindowsService(String serviceName) {
+        this._windowsServiceName = serviceName;
+        return this;
+    }
+    
+    public String getPidFile() {
+        if (_pidFile!=null) return _pidFile;
+        return _pidFile = entity().getConfig(ChefConfig.PID_FILE);
+    }
+
+    public String getServiceName() {
+        if (_serviceName!=null) return _serviceName;
+        return _serviceName = entity().getConfig(ChefConfig.SERVICE_NAME);
+    }
+
+    protected String getNodeName() {
+        // (node name is needed so we can node delete it)
+        
+        // TODO would be better if CHEF_NODE_NAME were a freemarker template, could access entity.id, or hostname, etc,
+        // in addition to supporting hard-coded node names (which is all we support so far).
+        
+        String nodeName = entity().getConfig(ChefConfig.CHEF_NODE_NAME);
+        if (Strings.isNonBlank(nodeName)) return Strings.makeValidFilename(nodeName);
+        // node name is taken from ID of this entity, if not specified
+        return entity().getId();
+    }
+
+    public String getWindowsServiceName() {
+        if (_windowsServiceName!=null) return _windowsServiceName;
+        return _windowsServiceName = entity().getConfig(ChefConfig.WINDOWS_SERVICE_NAME);
+    }
+
+    @Override
+    public void attachLifecycleEffectors(Entity entity) {
+        if (getPidFile()==null && getServiceName()==null && getClass().equals(ChefLifecycleEffectorTasks.class)) {
+            // warn on incorrect usage
+            log.warn("Uses of "+getClass()+" must define a PID file or a service name (or subclass and override {start,stop} methods as per javadoc) " +
+                    "in order for check-running and stop to work");
+        }
+            
+        super.attachLifecycleEffectors(entity);
+    }
+
+    public static ChefModes detectChefMode(Entity entity) {
+        ChefModes mode = entity.getConfig(ChefConfig.CHEF_MODE);
+        if (mode == ChefModes.AUTODETECT) {
+            // TODO server via API
+            ProcessTaskWrapper<Boolean> installCheck = DynamicTasks.queue(
+                    ChefServerTasks.isKnifeInstalled());
+            mode = installCheck.get() ? ChefModes.KNIFE : ChefModes.SOLO;
+            log.debug("Using Chef in "+mode+" mode due to autodetect exit code "+installCheck.getExitCode());
+        }
+        Preconditions.checkNotNull(mode, "Non-null "+ChefConfig.CHEF_MODE+" required for "+entity);
+        return mode;
+    }
+    
+    @Override
+    protected String startProcessesAtMachine(Supplier<MachineLocation> machineS) {
+        ChefModes mode = detectChefMode(entity());
+        switch (mode) {
+        case KNIFE:
+            startWithKnifeAsync();
+            break;
+            
+        case SOLO:
+            startWithChefSoloAsync();
+            break;
+            
+        default:
+            throw new IllegalStateException("Unknown Chef mode "+mode+" when starting processes for "+entity());
+        }
+        
+        return "chef start tasks submitted ("+mode+")";
+    }
+
+    protected String getPrimaryCookbook() {
+        return entity().getConfig(CHEF_COOKBOOK_PRIMARY_NAME);
+    }
+    
+    @SuppressWarnings({ "unchecked", "deprecation" })
+    protected void startWithChefSoloAsync() {
+        String baseDir = MachineLifecycleEffectorTasks.resolveOnBoxDir(entity(), Machines.findUniqueSshMachineLocation(entity().getLocations()).get());
+        String installDir = Urls.mergePaths(baseDir, "installs/chef");
+        
+        @SuppressWarnings("rawtypes")
+        Map<String, String> cookbooks = (Map) 
+            ConfigBag.newInstance( entity().getConfig(CHEF_COOKBOOK_URLS) )
+            .putIfAbsent( entity().getConfig(CHEF_COOKBOOKS) )
+            .getAllConfig();
+        if (cookbooks.isEmpty())
+            log.warn("No cookbook_urls set for "+entity()+"; launch will likely fail subsequently");
+        DynamicTasks.queue(
+                ChefSoloTasks.installChef(installDir, false), 
+                ChefSoloTasks.installCookbooks(installDir, cookbooks, false));
+
+        // TODO chef for and run a prestart recipe if necessary
+        // TODO open ports
+
+        String primary = getPrimaryCookbook();
+        
+        // put all config under brooklyn/cookbook/config
+        Navigator<MutableMap<Object, Object>> attrs = Jsonya.newInstancePrimitive().at("brooklyn");
+        if (Strings.isNonBlank(primary)) attrs.at(primary);
+        attrs.at("config");
+        attrs.put( entity().getAllConfigBag().getAllConfig() );
+        // and put launch attrs at root
+        try {
+            attrs.root().put((Map<?,?>)Tasks.resolveDeepValue(entity().getConfig(CHEF_LAUNCH_ATTRIBUTES), Object.class, entity().getExecutionContext()));
+        } catch (Exception e) { Exceptions.propagate(e); }
+        
+        Collection<? extends String> runList = entity().getConfig(CHEF_LAUNCH_RUN_LIST);
+        if (runList==null) runList = entity().getConfig(CHEF_RUN_LIST);
+        if (runList==null) {
+            if (Strings.isNonBlank(primary)) runList = ImmutableList.of(primary+"::"+"start");
+            else throw new IllegalStateException("Require a primary cookbook or a run_list to effect "+"start"+" on "+entity());
+        }
+        
+        String runDir = Urls.mergePaths(baseDir,  
+            "apps/"+entity().getApplicationId()+"/chef/entities/"+entity().getEntityType().getSimpleName()+"_"+entity().getId());
+        
+        DynamicTasks.queue(ChefSoloTasks.buildChefFile(runDir, installDir, "launch", 
+                runList, (Map<String, Object>) attrs.root().get()));
+        
+        DynamicTasks.queue(ChefSoloTasks.runChef(runDir, "launch", entity().getConfig(CHEF_RUN_CONVERGE_TWICE)));
+    }
+    
+    @SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
+    protected void startWithKnifeAsync() {
+        // TODO prestart, ports (as above); also, note, some aspects of this are untested as we need a chef server
+        
+        String primary = getPrimaryCookbook();
+
+        // put all config under brooklyn/cookbook/config
+        Navigator<MutableMap<Object, Object>> attrs = Jsonya.newInstancePrimitive().at("brooklyn");
+        if (Strings.isNonBlank(primary)) attrs.at(primary);
+        attrs.at("config");
+        attrs.put( entity().getAllConfigBag().getAllConfig() );
+        // and put launch attrs at root
+        try {
+            attrs.root().put((Map<?,?>)Tasks.resolveDeepValue(entity().getConfig(CHEF_LAUNCH_ATTRIBUTES), Object.class, entity().getExecutionContext()));
+        } catch (Exception e) { Exceptions.propagate(e); }
+
+        Collection<? extends String> runList = entity().getConfig(CHEF_LAUNCH_RUN_LIST);
+        if (runList==null) runList = entity().getConfig(CHEF_RUN_LIST);
+        if (runList==null) {
+            if (Strings.isNonBlank(primary)) runList = ImmutableList.of(primary+"::"+"start");
+            else throw new IllegalStateException("Require a primary cookbook or a run_list to effect "+"start"+" on "+entity());
+        }
+
+        DynamicTasks.queue(
+                ChefServerTasks.knifeConvergeTask()
+                    .knifeNodeName(getNodeName())
+                    .knifeRunList(Strings.join(runList, ","))
+                    .knifeAddAttributes((Map<? extends Object, ? extends Object>)(Map) attrs.root().get())
+                    .knifeRunTwice(entity().getConfig(CHEF_RUN_CONVERGE_TWICE)) );
+    }
+
+    protected void postStartCustom() {
+        boolean result = false;
+        result |= tryCheckStartPid();
+        result |= tryCheckStartService();
+        result |= tryCheckStartWindowsService();
+        if (!result) {
+            log.warn("No way to check whether "+entity()+" is running; assuming yes");
+        }
+        entity().setAttribute(SoftwareProcess.SERVICE_UP, true);
+    }
+    
+    protected boolean tryCheckStartPid() {
+        if (getPidFile()==null) return false;
+        
+        // if it's still up after 5s assume we are good (default behaviour)
+        Time.sleep(Duration.FIVE_SECONDS);
+        if (!DynamicTasks.queue(SshEffectorTasks.isPidFromFileRunning(getPidFile()).runAsRoot()).get()) {
+            throw new IllegalStateException("The process for "+entity()+" appears not to be running (pid file "+getPidFile()+")");
+        }
+
+        // and set the PID
+        entity().setAttribute(Attributes.PID, 
+                Integer.parseInt(DynamicTasks.queue(SshEffectorTasks.ssh("cat "+getPidFile()).runAsRoot()).block().getStdout().trim()));
+        return true;
+    }
+
+    protected boolean tryCheckStartService() {
+        if (getServiceName()==null) return false;
+        
+        // if it's still up after 5s assume we are good (default behaviour)
+        Time.sleep(Duration.FIVE_SECONDS);
+        if (!((Integer)0).equals(DynamicTasks.queue(SshEffectorTasks.ssh("/etc/init.d/"+getServiceName()+" status").runAsRoot()).get())) {
+            throw new IllegalStateException("The process for "+entity()+" appears not to be running (service "+getServiceName()+")");
+        }
+
+        return true;
+    }
+
+    protected boolean tryCheckStartWindowsService() {
+        if (getWindowsServiceName()==null) return false;
+        
+        // if it's still up after 5s assume we are good (default behaviour)
+        Time.sleep(Duration.FIVE_SECONDS);
+        if (!((Integer)0).equals(DynamicTasks.queue(SshEffectorTasks.ssh("sc query \""+getWindowsServiceName()+"\" | find \"RUNNING\"").runAsCommand()).get())) {
+            throw new IllegalStateException("The process for "+entity()+" appears not to be running (windowsService "+getWindowsServiceName()+")");
+        }
+
+        return true;
+    }
+
+    @Override
+    protected String stopProcessesAtMachine() {
+        boolean result = false;
+        result |= tryStopService();
+        result |= tryStopWindowsService();
+        result |= tryStopPid();
+        if (!result) {
+            throw new IllegalStateException("The process for "+entity()+" could not be stopped (no impl!)");
+        }
+        return "stopped";
+    }
+    
+    @Override
+    protected StopMachineDetails<Integer> stopAnyProvisionedMachines() {
+        if (detectChefMode(entity())==ChefModes.KNIFE) {
+            DynamicTasks.queue(
+                // if this task fails show it as failed but don't block subsequent routines
+                // (ie allow us to actually decommission the machine)
+                // TODO args could be a List<String> config key ?
+                TaskTags.markInessential(
+                new KnifeTaskFactory<String>("delete node and client registration at chef server")
+                    .add("knife node delete "+getNodeName()+" -y")
+                    .add("knife client delete "+getNodeName()+" -y")
+                    .requiringZeroAndReturningStdout()
+                    .newTask() ));
+        }
+
+        return super.stopAnyProvisionedMachines();
+    }
+    
+    protected boolean tryStopService() {
+        if (getServiceName()==null) return false;
+        int result = DynamicTasks.queue(SshEffectorTasks.ssh("/etc/init.d/"+getServiceName()+" stop").runAsRoot()).get();
+        if (0==result) return true;
+        if (entity().getAttribute(Attributes.SERVICE_STATE_ACTUAL)!=Lifecycle.RUNNING)
+            return true;
+        
+        throw new IllegalStateException("The process for "+entity()+" appears could not be stopped (exit code "+result+" to service stop)");
+    }
+
+    protected boolean tryStopWindowsService() {
+        if (getWindowsServiceName()==null) return false;
+                int result = DynamicTasks.queue(SshEffectorTasks.ssh("sc query \""+getWindowsServiceName()+"\"").runAsCommand()).get();
+        if (0==result) return true;
+        if (entity().getAttribute(Attributes.SERVICE_STATE_ACTUAL)!=Lifecycle.RUNNING)
+            return true;
+
+        throw new IllegalStateException("The process for "+entity()+" appears could not be stopped (exit code "+result+" to service stop)");
+    }
+
+    protected boolean tryStopPid() {
+        Integer pid = entity().getAttribute(Attributes.PID);
+        if (pid==null) {
+            if (entity().getAttribute(Attributes.SERVICE_STATE_ACTUAL)==Lifecycle.RUNNING && getPidFile()==null)
+                log.warn("No PID recorded for "+entity()+" when running, with PID file "+getPidFile()+"; skipping kill in "+Tasks.current());
+            else 
+                if (log.isDebugEnabled())
+                    log.debug("No PID recorded for "+entity()+"; skipping ("+entity().getAttribute(Attributes.SERVICE_STATE_ACTUAL)+" / "+getPidFile()+")");
+            return false;
+        }
+        
+        // allow non-zero exit as process may have already been killed
+        DynamicTasks.queue(SshEffectorTasks.ssh(
+                "kill "+pid, "sleep 5", BashCommands.ok("kill -9 "+pid)).allowingNonZeroExitCode().runAsRoot()).block();
+        
+        if (DynamicTasks.queue(SshEffectorTasks.isPidRunning(pid).runAsRoot()).get()) {
+            throw new IllegalStateException("Process for "+entity()+" in "+pid+" still running after kill");
+        }
+        entity().setAttribute(Attributes.PID, null);
+        return true;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefServerTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefServerTasks.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefServerTasks.java
new file mode 100644
index 0000000..d8132be
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefServerTasks.java
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.security.KeyPair;
+
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.util.core.crypto.SecureKeys;
+
+import com.google.common.base.Throwables;
+import com.google.common.io.Files;
+
+public class ChefServerTasks {
+
+    private static File chefKeyDir;
+    
+    private synchronized static File getExtractedKeysDir() {
+        if (chefKeyDir==null) {
+            chefKeyDir = Files.createTempDir();
+            chefKeyDir.deleteOnExit();
+        }
+        return chefKeyDir;
+    }
+    
+    /** extract key to a temp file, but one per machine, scheduled for deletion afterwards;
+     * we extract the key because chef has no way to accept passphrases at present */
+    synchronized static File extractKeyFile(SshMachineLocation machine) {
+        File f = new File(getExtractedKeysDir(), machine.getAddress().getHostName()+".pem");
+        if (f.exists()) return f;
+        KeyPair data = machine.findKeyPair();
+        if (data==null) return null;
+        try {
+            f.deleteOnExit();
+            Files.write(SecureKeys.stringPem(data), f, Charset.defaultCharset());
+            return f;
+        } catch (IOException e) {
+            throw Throwables.propagate(e);
+        }
+    }
+    
+    public static KnifeTaskFactory<Boolean> isKnifeInstalled() {
+        return new KnifeTaskFactory<Boolean>("knife install check")
+                .knifeAddParameters("node list")
+                .notThrowingOnCommonKnifeErrors()
+                .returningIsExitCodeZero();
+    }
+
+    /** plain knife converge task - run list must be set, other arguments are optional */
+    public static KnifeConvergeTaskFactory<String> knifeConvergeTask() {
+        return new KnifeConvergeTaskFactory<String>("knife converge")
+                .requiringZeroAndReturningStdout();
+    }
+    /** knife converge task configured for this run list (and sudo) */
+    public static KnifeConvergeTaskFactory<String> knifeConvergeRunList(String runList) {
+        return knifeConvergeTask()
+                .knifeRunList(runList)
+                .knifeSudo(true);
+    }
+    
+    /** knife converge task configured for this run list on windows (ssh) */
+    public static KnifeConvergeTaskFactory<String> knifeConvergeRunListWindowsSsh(String runList) {
+        return knifeConvergeTask()
+                .knifeRunList(runList)
+                .knifeSudo(false)
+                .knifeAddExtraBootstrapParameters("windows ssh");
+    }
+    
+    /** knife converge task configured for this run list on windows (winrm) */
+    public static KnifeConvergeTaskFactory<String> knifeConvergeRunListWindowsWinrm(String runList) {
+        return knifeConvergeTask()
+                .knifeRunList(runList)
+                .knifeSudo(false)
+                .knifeAddExtraBootstrapParameters("windows winrm")
+                .knifePortUseKnifeDefault();
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefSoloDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefSoloDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefSoloDriver.java
new file mode 100644
index 0000000..0f4dd40
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefSoloDriver.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.mgmt.TaskAdaptable;
+import org.apache.brooklyn.api.mgmt.TaskFactory;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+
+import com.google.common.annotations.Beta;
+import com.google.common.reflect.TypeToken;
+
+/** Driver class to facilitate use of Chef */
+@Beta
+@Deprecated /** @deprecated since 0.7.0 use ChefEntity or ChefLifecycleEffectorTasks */
+public class ChefSoloDriver extends AbstractSoftwareProcessSshDriver implements ChefConfig {
+
+    @SuppressWarnings("serial")
+    public static final ConfigKey<TaskFactory<? extends TaskAdaptable<Boolean>>> IS_RUNNING_TASK = ConfigKeys.newConfigKey(
+            new TypeToken<TaskFactory<? extends TaskAdaptable<Boolean>>>() {}, 
+            "brooklyn.chef.task.driver.isRunningTask");
+    
+    @SuppressWarnings("serial")
+    public static final ConfigKey<TaskFactory<?>> STOP_TASK = ConfigKeys.newConfigKey(
+            new TypeToken<TaskFactory<?>>() {}, 
+            "brooklyn.chef.task.driver.stopTask");
+    
+    public ChefSoloDriver(EntityLocal entity, SshMachineLocation location) {
+        super(entity, location);
+    }
+
+    @Override
+    public void install() {
+        // TODO flag to force reinstallation
+        DynamicTasks.queue(
+                ChefSoloTasks.installChef(getInstallDir(), false), 
+                ChefSoloTasks.installCookbooks(getInstallDir(), getRequiredConfig(CHEF_COOKBOOKS), false));
+    }
+
+    @Override
+    public void customize() {
+        DynamicTasks.queue(ChefSoloTasks.buildChefFile(getRunDir(), getInstallDir(), "launch", getRequiredConfig(CHEF_RUN_LIST),
+                getEntity().getConfig(CHEF_LAUNCH_ATTRIBUTES)));
+    }
+
+    @Override
+    public void launch() {
+        DynamicTasks.queue(ChefSoloTasks.runChef(getRunDir(), "launch", getEntity().getConfig(CHEF_RUN_CONVERGE_TWICE)));
+    }
+
+    @Override
+    public boolean isRunning() {
+        return DynamicTasks.queue(getRequiredConfig(IS_RUNNING_TASK)).asTask().getUnchecked();
+    }
+
+    @Override
+    public void stop() {
+        DynamicTasks.queue(getRequiredConfig(STOP_TASK));
+    }
+
+    protected <T> T getRequiredConfig(ConfigKey<T> key) {
+        return ChefConfigs.getRequiredConfig(getEntity(), key);
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefSoloTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefSoloTasks.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefSoloTasks.java
new file mode 100644
index 0000000..64a27a4
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefSoloTasks.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.mgmt.TaskFactory;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
+import org.apache.brooklyn.util.ssh.BashCommands;
+
+import com.google.common.annotations.Beta;
+
+@Beta
+public class ChefSoloTasks {
+
+    public static TaskFactory<?> installChef(String chefDirectory, boolean force) {
+        // TODO check on entity whether it is chef _server_
+        String installCmd = cdAndRun(chefDirectory, ChefBashCommands.INSTALL_FROM_OPSCODE);
+        if (!force) installCmd = BashCommands.alternatives("which chef-solo", installCmd);
+        return SshEffectorTasks.ssh(installCmd).summary("install chef");
+    }
+
+    public static TaskFactory<?> installCookbooks(final String chefDirectory, final Map<String,String> cookbooksAndUrls, final boolean force) {
+        return ChefTasks.installCookbooks(chefDirectory, cookbooksAndUrls, force);
+    }
+
+    public static TaskFactory<?> installCookbook(String chefDirectory, String cookbookName, String cookbookArchiveUrl, boolean force) {
+        return ChefTasks.installCookbook(chefDirectory, cookbookName, cookbookArchiveUrl, force);
+    }
+
+    protected static String cdAndRun(String targetDirectory, String command) {
+        return BashCommands.chain("mkdir -p "+targetDirectory,
+                "cd "+targetDirectory,
+                command);
+    }
+
+    public static TaskFactory<?> buildChefFile(String runDirectory, String chefDirectory, String phase, Iterable<? extends String> runList,
+            Map<String, Object> optionalAttributes) {
+        return ChefTasks.buildChefFile(runDirectory, chefDirectory, phase, runList, optionalAttributes);
+    }
+
+    public static TaskFactory<?> runChef(String runDir, String phase) {
+        return runChef(runDir, phase, false);
+    }
+    /** see {@link ChefConfig#CHEF_RUN_CONVERGE_TWICE} for background on why 'twice' is available */
+    public static TaskFactory<?> runChef(String runDir, String phase, Boolean twice) {
+        String cmd = "sudo chef-solo -c "+phase+".rb -j "+phase+".json -ldebug";
+        if (twice!=null && twice) cmd = BashCommands.alternatives(cmd, cmd);
+
+        return SshEffectorTasks.ssh(cdAndRun(runDir, cmd)).
+                summary("run chef for "+phase).requiringExitCodeZero();
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefTasks.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefTasks.java
new file mode 100644
index 0000000..0f359d5
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefTasks.java
@@ -0,0 +1,153 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.mgmt.TaskAdaptable;
+import org.apache.brooklyn.api.mgmt.TaskFactory;
+import org.apache.brooklyn.effector.core.EffectorTasks;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.file.ArchiveTasks;
+import org.apache.brooklyn.util.core.file.ArchiveUtils.ArchiveType;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.TaskBuilder;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.net.Urls;
+import org.apache.brooklyn.util.ssh.BashCommands;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.apache.brooklyn.util.text.Strings;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.annotations.Beta;
+import com.google.common.collect.ImmutableList;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+@Beta
+public class ChefTasks {
+
+    private static final Logger log = LoggerFactory.getLogger(ChefTasks.class);
+    
+    public static TaskFactory<?> installChef(String chefDirectory, boolean force) {
+        // TODO check on entity whether it is chef _server_
+        String installCmd = cdAndRun(chefDirectory, ChefBashCommands.INSTALL_FROM_OPSCODE);
+        if (!force) installCmd = BashCommands.alternatives("which chef-solo", installCmd);
+        return SshEffectorTasks.ssh(installCmd).summary("install chef");
+    }
+
+    public static TaskFactory<?> installCookbooks(final String chefDirectory, final Map<String,String> cookbooksAndUrls, final boolean force) {
+        return Tasks.<Void>builder().name("install "+(cookbooksAndUrls==null ? "0" : cookbooksAndUrls.size())+" cookbook"+Strings.s(cookbooksAndUrls)).body(
+                new Runnable() {
+                    public void run() {
+                        Entity e = EffectorTasks.findEntity();
+                        if (cookbooksAndUrls==null)
+                            throw new IllegalStateException("No cookbooks defined to install at "+e);
+                        for (String cookbook: cookbooksAndUrls.keySet())
+                            DynamicTasks.queue(installCookbook(chefDirectory, cookbook, cookbooksAndUrls.get(cookbook), force));
+                    }
+                }).buildFactory();
+    }
+
+    public static TaskFactory<?> installCookbook(final String chefDirectory, final String cookbookName, final String cookbookArchiveUrl, final boolean force) {
+        return new TaskFactory<TaskAdaptable<?>>() {
+            @Override
+            public TaskAdaptable<?> newTask() {
+                TaskBuilder<Void> tb = Tasks.<Void>builder().name("install cookbook "+cookbookName);
+                
+                String cookbookDir = Urls.mergePaths(chefDirectory, cookbookName);
+                String privateTmpDirContainingUnpackedCookbook = 
+                    Urls.mergePaths(chefDirectory, "tmp-"+Strings.makeValidFilename(cookbookName)+"-"+Identifiers.makeRandomId(4));
+
+                // TODO - skip the install earlier if it exists and isn't forced
+//                if (!force) {
+//                    // in builder.body, check 
+//                    // "ls "+cookbookDir
+//                    // and stop if it's zero
+//                    // remove reference to 'force' below
+//                }
+                
+                String destName = null;
+                if (ArchiveType.of(cookbookArchiveUrl)==ArchiveType.UNKNOWN) {
+                    destName = cookbookName + ".tgz";
+                    log.debug("Assuming TGZ type for chef cookbook url "+cookbookArchiveUrl+"; it will be downloaded as "+destName);
+                }
+                tb.add(ArchiveTasks.deploy(null, null, cookbookArchiveUrl, EffectorTasks.findSshMachine(), privateTmpDirContainingUnpackedCookbook,
+                    false, null, destName).newTask());
+                
+                String installCmd = BashCommands.chain(
+                    "cd "+privateTmpDirContainingUnpackedCookbook,  
+                    "COOKBOOK_EXPANDED_DIR=`ls`",
+                    BashCommands.requireTest("`ls | wc -w` -eq 1", 
+                            "The deployed archive "+cookbookArchiveUrl+" must contain exactly one directory"),
+                    "mv $COOKBOOK_EXPANDED_DIR '../"+cookbookName+"'",
+                    "cd ..",
+                    "rm -rf '"+privateTmpDirContainingUnpackedCookbook+"'");
+                
+                installCmd = force ? BashCommands.alternatives("rm -rf "+cookbookDir, installCmd) : BashCommands.alternatives("ls "+cookbookDir+" > /dev/null 2> /dev/null", installCmd);
+                tb.add(SshEffectorTasks.ssh(installCmd).summary("renaming cookbook dir").requiringExitCodeZero().newTask());
+                
+                return tb.build();
+            }
+        };
+    }
+
+    protected static String cdAndRun(String targetDirectory, String command) {
+        return BashCommands.chain("mkdir -p '"+targetDirectory+"'",
+                "cd '"+targetDirectory+"'",
+                command);
+    }
+
+    public static TaskFactory<?> buildChefFile(String runDirectory, String chefDirectory, String phase, Iterable<? extends String> runList,
+            Map<String, Object> optionalAttributes) {
+        // TODO if it's server, try knife first
+        // TODO configure add'l properties
+        String phaseRb = 
+            "root = "
+            + "'"+runDirectory+"'" 
+            // recommended alternate to runDir is the following, but it is not available in some rubies
+            //+ File.absolute_path(File.dirname(__FILE__))"+
+            + "\n"+
+            "file_cache_path root\n"+
+//            "cookbook_path root + '/cookbooks'\n";
+            "cookbook_path '"+chefDirectory+"'\n";
+
+        Map<String,Object> phaseJsonMap = MutableMap.of();
+        if (optionalAttributes!=null)
+            phaseJsonMap.putAll(optionalAttributes);
+        if (runList!=null)
+            phaseJsonMap.put("run_list", ImmutableList.copyOf(runList));
+        Gson json = new GsonBuilder().create();
+        String phaseJson = json.toJson(phaseJsonMap);
+
+        return Tasks.sequential("build chef files for "+phase,
+                    SshEffectorTasks.put(Urls.mergePaths(runDirectory)+"/"+phase+".rb").contents(phaseRb).createDirectory(),
+                    SshEffectorTasks.put(Urls.mergePaths(runDirectory)+"/"+phase+".json").contents(phaseJson));
+    }
+
+    public static TaskFactory<?> runChef(String runDir, String phase) {
+        // TODO chef server
+        return SshEffectorTasks.ssh(cdAndRun(runDir, "sudo chef-solo -c "+phase+".rb -j "+phase+".json -ldebug")).
+                summary("run chef for "+phase).requiringExitCodeZero();
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/chef/KnifeConvergeTaskFactory.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/KnifeConvergeTaskFactory.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/KnifeConvergeTaskFactory.java
new file mode 100644
index 0000000..39e31b8
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/KnifeConvergeTaskFactory.java
@@ -0,0 +1,246 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.apache.brooklyn.util.text.StringEscapes.BashStringEscapes.wrapBash;
+
+import java.io.File;
+import java.util.List;
+import java.util.Map;
+
+import com.google.common.base.Strings;
+import com.google.common.net.HostAndPort;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.effector.core.EffectorTasks;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.util.collections.Jsonya;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.apache.brooklyn.util.ssh.BashCommands;
+
+import com.google.common.base.Function;
+import com.google.common.base.Functions;
+import com.google.gson.GsonBuilder;
+
+public class KnifeConvergeTaskFactory<RET> extends KnifeTaskFactory<RET> {
+
+    private static final Logger log = LoggerFactory.getLogger(KnifeConvergeTaskFactory.class);
+    
+    protected Function<? super Entity,String> runList;
+    protected Map<Object, Object> knifeAttributes = new MutableMap<Object, Object>();
+    protected List<String> extraBootstrapParameters = MutableList.of();
+    protected Boolean sudo;
+    protected Boolean runTwice;
+    protected String nodeName;
+    protected Integer port;
+    /** null means nothing specified, use user supplied or machine default;
+     * false means use machine default (disallow user supplied);
+     * true means use knife default (omit the argument and disallow user supplied)
+     */
+    protected Boolean portOmittedToUseKnifeDefault;
+
+    public KnifeConvergeTaskFactory(String taskName) {
+        super(taskName);
+    }
+    
+    @Override
+    protected KnifeConvergeTaskFactory<RET> self() {
+        return this;
+    }
+    
+    /** construct the knife command, based on the settings on other methods
+     * (called when instantiating the script, after all parameters sent)
+     */
+    protected List<String> initialKnifeParameters() {
+        // runs inside the task so can detect entity/machine at runtime
+        MutableList<String> result = new MutableList<String>();
+        SshMachineLocation machine = EffectorTasks.findSshMachine();
+        
+        result.add("bootstrap");
+        result.addAll(extraBootstrapParameters);
+
+        HostAndPort hostAndPort = machine.getSshHostAndPort();
+        result.add(wrapBash(hostAndPort.getHostText()));
+        Integer whichPort = knifeWhichPort(hostAndPort);
+        if (whichPort!=null)
+            result.add("-p "+whichPort);
+
+        result.add("-x "+wrapBash(checkNotNull(machine.getUser(), "user")));
+        
+        File keyfile = ChefServerTasks.extractKeyFile(machine);
+        if (keyfile!=null) result.add("-i "+keyfile.getPath());
+        else result.add("-P "+checkNotNull(machine.findPassword(), "No password or private key data for "+machine));
+        
+        result.add("--no-host-key-verify");
+        
+        if (sudo != Boolean.FALSE) result.add("--sudo");
+
+        if (!Strings.isNullOrEmpty(nodeName)) {
+            result.add("--node-name");
+            result.add(nodeName);
+        }
+
+        result.add("-r "+wrapBash(runList.apply(entity())));
+        
+        if (!knifeAttributes.isEmpty())
+            result.add("-j "+wrapBash(new GsonBuilder().create()
+                    .toJson(knifeAttributes)));
+
+        return result;
+    }
+    
+    /** whether knife should attempt to run twice;
+     * see {@link ChefConfig#CHEF_RUN_CONVERGE_TWICE} */
+    public KnifeConvergeTaskFactory<RET> knifeRunTwice(boolean runTwice) {
+        this.runTwice = runTwice;
+        return self();
+    }
+    
+    /** whether to pass --sudo to knife; default true */
+    public KnifeConvergeTaskFactory<RET> knifeSudo(boolean sudo) {
+        this.sudo = sudo;
+        return self();
+    }
+
+    /** what node name to pass to knife; default = null, meaning chef-client will pick the node name */
+    public KnifeConvergeTaskFactory<RET> knifeNodeName(String nodeName) {
+        this.nodeName = nodeName;
+        return self();
+    }
+
+    /** tell knife to use an explicit port */
+    public KnifeConvergeTaskFactory<RET> knifePort(int port) {
+        if (portOmittedToUseKnifeDefault!=null) {
+            log.warn("Port "+port+" specified to "+this+" for when already explicitly told to use a default (overriding previous); see subsequent warning for more details");
+        }
+        this.port = port;
+        return self();
+    }
+
+    /** omit the port parameter altogether (let knife use its default) */
+    public KnifeConvergeTaskFactory<RET> knifePortUseKnifeDefault() {
+        if (port!=null) {
+            log.warn("knifePortUseKnifeDefault specified to "+this+" when already told to use "+port+" explicitly (overriding previous); see subsequent warning for more details");
+            port = -1;
+        }
+        portOmittedToUseKnifeDefault = true;
+        return self();
+    }
+    
+    /** use the default port known to brooklyn for the target machine for ssh */
+    public KnifeConvergeTaskFactory<RET> knifePortUseMachineSshPort() {
+        if (port!=null) {
+            log.warn("knifePortUseMachineSshPort specified to "+this+" when already told to use "+port+" explicitly (overriding previous); see subsequent warning for more details");
+            port = -1;
+        }
+        portOmittedToUseKnifeDefault = false;
+        return self();
+    }
+    
+    protected Integer knifeWhichPort(HostAndPort hostAndPort) {
+        if (port==null) {
+            if (Boolean.TRUE.equals(portOmittedToUseKnifeDefault))
+                // user has explicitly said to use knife default, omitting port here
+                return null;
+            // default is to use the machine port
+            return hostAndPort.getPort();
+        }
+        if (port==-1) {
+            // port was supplied by user, then portDefault (true or false)
+            port = null;
+            Integer whichPort = knifeWhichPort(hostAndPort);
+            log.warn("knife port conflicting instructions for "+this+" at entity "+entity()+" on "+hostAndPort+"; using default ("+whichPort+")");
+            return whichPort;
+        }
+        if (portOmittedToUseKnifeDefault!=null) {
+            // portDefault was specified (true or false), then overridden with a port
+            log.warn("knife port conflicting instructions for "+this+" at entity "+entity()+" on "+hostAndPort+"; using supplied port "+port);
+        }
+        // port was supplied by user, use that
+        return port;
+    }
+    
+    /** parameters to pass to knife after the bootstrap command */
+    public KnifeConvergeTaskFactory<RET> knifeAddExtraBootstrapParameters(String extraBootstrapParameter1, String ...extraBootstrapParameters) {
+        this.extraBootstrapParameters.add(extraBootstrapParameter1);
+        for (String p: extraBootstrapParameters)
+            this.extraBootstrapParameters.add(p);
+        return self();
+    }
+    
+    /** function supplying the run list to be passed to knife, evaluated at the last moment */
+    public KnifeConvergeTaskFactory<RET> knifeRunList(Function<? super Entity, String> runList) {
+        this.runList = runList;
+        return self();
+    }
+    public KnifeConvergeTaskFactory<RET> knifeRunList(String runList) {
+        this.runList = Functions.constant(runList);
+        return self();
+    }
+    
+    /** includes the given attributes in the attributes to be passed to chef; 
+     * when combining with other attributes, this uses {@link Jsonya} semantics to add 
+     * (a deep add, combining lists and maps) */
+    public KnifeConvergeTaskFactory<RET> knifeAddAttributes(Map<? extends Object, ? extends Object> attributes) {
+        if (attributes!=null && !attributes.isEmpty()) {
+            Jsonya.of(knifeAttributes).add(attributes);
+        }
+        return self();
+    }
+    
+    protected String buildKnifeCommand(int knifeCommandIndex) {
+        String result = super.buildKnifeCommand(knifeCommandIndex);
+        if (Boolean.TRUE.equals(runTwice))
+            result = BashCommands.alternatives(result, result);
+        return result;
+    }
+
+    @Override
+    public <T2> KnifeConvergeTaskFactory<T2> returning(ScriptReturnType type) {
+        return (KnifeConvergeTaskFactory<T2>) super.<T2>returning(type);
+    }
+
+    @Override
+    public <RET2> KnifeConvergeTaskFactory<RET2> returning(Function<ProcessTaskWrapper<?>, RET2> resultTransformation) {
+        return (KnifeConvergeTaskFactory<RET2>) super.returning(resultTransformation);
+    }
+    
+    @Override
+    public KnifeConvergeTaskFactory<Boolean> returningIsExitCodeZero() {
+        return (KnifeConvergeTaskFactory<Boolean>) super.returningIsExitCodeZero();
+    }
+    
+    @Override
+    public KnifeConvergeTaskFactory<String> requiringZeroAndReturningStdout() {
+        return (KnifeConvergeTaskFactory<String>) super.requiringZeroAndReturningStdout();
+    }
+
+    public KnifeConvergeTaskFactory<RET> knifeAddParameters(String word1, String ...words) {
+        super.knifeAddParameters(word1, words);
+        return self();
+    }
+
+    // TODO other methods from KnifeTaskFactory will return KTF class not KCTF;
+    // should make it generic so it returns the right type...
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/chef/KnifeTaskFactory.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/KnifeTaskFactory.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/KnifeTaskFactory.java
new file mode 100644
index 0000000..5d1af9d
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/KnifeTaskFactory.java
@@ -0,0 +1,240 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.core.internal.ssh.process.ProcessTool;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskFactory;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.apache.brooklyn.util.core.task.system.internal.SystemProcessTaskFactory;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.text.StringEscapes.BashStringEscapes;
+
+import com.google.common.base.Function;
+
+/** A factory which acts like {@link ProcessTaskFactory} with special options for knife.
+ * Typical usage is to {@link #addKnifeParameters(String)}s for the knife command to be run.
+ * You can also {@link #add(String...)} commands as needed; these will run *before* knife,
+ * unless you addKnifeCommandHere().
+ * <p>
+ * This impl will use sensible defaults, including {@link ConfigKey}s on the context entity,
+ * for general knife config but not specific commands etc. It supports:
+ * <li> {@link ChefConfig#KNIFE_EXECUTABLE}
+ * <li> {@link ChefConfig#KNIFE_CONFIG_FILE}
+ * <p>
+ * (Other fields will typically be used by methods calling to this factory.) 
+ *  */
+// see e.g. http://docs.opscode.com/knife_bootstrap.html
+public class KnifeTaskFactory<RET> extends SystemProcessTaskFactory<KnifeTaskFactory<RET>, RET>{
+    
+    private static String KNIFE_PLACEHOLDER = "<knife command goes here 1234>";
+    public final String taskName;
+    protected String knifeExecutable;
+    protected List<String> knifeParameters = new ArrayList<String>();
+    protected String knifeConfigFile;
+    protected String knifeSetupCommands;
+    protected Boolean throwOnCommonKnifeErrors;
+    
+    public KnifeTaskFactory(String taskName) {
+        this.taskName = taskName;
+        summary(taskName);
+        // knife setup usually requires a login shell
+        config.put(ProcessTool.PROP_LOGIN_SHELL, true);
+    }
+    
+    @Override
+    public List<Function<ProcessTaskWrapper<?>, Void>> getCompletionListeners() {
+        MutableList<Function<ProcessTaskWrapper<?>, Void>> result = MutableList.copyOf(super.getCompletionListeners());
+        if (throwOnCommonKnifeErrors != Boolean.FALSE)
+            insertKnifeCompletionListenerIntoCompletionListenersList(result);
+        return result.asUnmodifiable();
+    }
+    
+    public KnifeTaskFactory<RET> notThrowingOnCommonKnifeErrors() {
+        throwOnCommonKnifeErrors = false;
+        return self();
+    }
+
+    protected void insertKnifeCompletionListenerIntoCompletionListenersList(List<Function<ProcessTaskWrapper<?>, Void>> listeners) {
+        // give a nice warning if chef/knife not set up correctly
+        Function<ProcessTaskWrapper<?>, Void> propagateIfKnifeConfigFileMissing = new Function<ProcessTaskWrapper<?>, Void>() {
+            public Void apply(@Nullable ProcessTaskWrapper<?> input) {
+                if (input.getExitCode()!=0 && input.getStderr().indexOf("WARNING: No knife configuration file found")>=0) {
+                    String myConfig = knifeConfigFileOption();
+                    if (Strings.isEmpty(myConfig))
+                        throw new IllegalStateException("Config file for Chef knife must be specified in "+ChefConfig.KNIFE_CONFIG_FILE+" (or valid knife default set up)");
+                    else
+                        throw new IllegalStateException("Error reading config file for Chef knife ("+myConfig+") -- does it exist?");
+                }
+                return null;
+            }
+        };
+        listeners.add(propagateIfKnifeConfigFileMissing);
+    }
+
+    
+    @Override
+    public ProcessTaskWrapper<RET> newTask() {
+        return new SystemProcessTaskWrapper("Knife");
+    }
+
+    /** Inserts the knife command at the current place in the list.
+     * Can be run multiple times. The knife command added at the end of the list
+     * if this is not invoked (and it is the only command if nothing is {@link #add(String...)}ed.
+     */
+    public KnifeTaskFactory<RET> addKnifeCommandToScript() {
+        add(KNIFE_PLACEHOLDER);
+        return self();
+    }
+    
+    @Override
+    public List<String> getCommands() {
+        MutableList<String> result = new MutableList<String>();
+        String setupCommands = knifeSetupCommands();
+        if (setupCommands != null && Strings.isNonBlank(setupCommands))
+            result.add(setupCommands);
+        int numKnifes = 0;
+        for (String c: super.getCommands()) {
+            if (c==KNIFE_PLACEHOLDER)
+                result.add(buildKnifeCommand(numKnifes++));
+            else
+                result.add(c);
+        }
+        if (numKnifes==0)
+            result.add(buildKnifeCommand(numKnifes++));
+        return result.asUnmodifiable();
+    }
+    
+    /** creates the command for running knife.
+     * in some cases knife may be added multiple times,
+     * and in that case the parameter here tells which time it is being added, 
+     * on a single run. */
+    protected String buildKnifeCommand(int knifeCommandIndex) {
+        MutableList<String> words = new MutableList<String>();
+        words.add(knifeExecutable());
+        words.addAll(initialKnifeParameters());
+        words.addAll(knifeParameters());
+        String x = knifeConfigFileOption();
+        if (Strings.isNonBlank(x)) words.add(knifeConfigFileOption());
+        return Strings.join(words, " ");
+    }
+    
+    /** allows a way for subclasses to build up parameters at the start */
+    protected List<String> initialKnifeParameters() {
+        return new MutableList<String>();
+    }
+    
+    @Nullable /** callers should allow this to be null so task can be used outside of an entity */
+    protected Entity entity() {
+        return BrooklynTaskTags.getTargetOrContextEntity(Tasks.current());
+    }
+    protected <T> T entityConfig(ConfigKey<T> key) {
+        Entity entity = entity();
+        if (entity!=null)
+            return entity.getConfig(key);
+        return null;
+    }
+    
+    public KnifeTaskFactory<RET> knifeExecutable(String knifeExecutable) {
+        this.knifeExecutable = knifeExecutable;
+        return this;
+    }
+    
+    protected String knifeExecutable() {
+        if (knifeExecutable!=null) return knifeExecutable;
+        
+        String knifeExecFromConfig = entityConfig(ChefConfig.KNIFE_EXECUTABLE);
+        if (knifeExecFromConfig!=null) return BashStringEscapes.wrapBash(knifeExecFromConfig);
+        
+        // assume on the path, if executable not set
+        return "knife";
+    }
+    
+    protected List<String> knifeParameters() {
+        return knifeParameters;
+    }
+    
+    public KnifeTaskFactory<RET> knifeAddParameters(String word1, String ...words) {
+        knifeParameters.add(word1);
+        for (String w: words)
+            knifeParameters.add(w);
+        return self();
+    }
+
+    public KnifeTaskFactory<RET> knifeConfigFile(String knifeConfigFile) {
+        this.knifeConfigFile = knifeConfigFile;
+        return self();
+    }
+    
+    @Nullable
+    protected String knifeConfigFileOption() {
+        if (knifeConfigFile!=null) return "-c "+knifeConfigFile;
+
+        String knifeConfigFileFromConfig = entityConfig(ChefConfig.KNIFE_CONFIG_FILE);
+        if (knifeConfigFileFromConfig!=null) return "-c "+BashStringEscapes.wrapBash(knifeConfigFileFromConfig);
+
+        // if not supplied will use global config
+        return null;
+    }
+
+    public KnifeTaskFactory<RET> knifeSetupCommands(String knifeSetupCommands) {
+        this.knifeSetupCommands = knifeSetupCommands;
+        return self();
+    }
+    
+    @Nullable
+    protected String knifeSetupCommands() {
+        if (knifeSetupCommands!=null) return knifeSetupCommands;
+        
+        String knifeSetupCommandsFromConfig = entityConfig(ChefConfig.KNIFE_SETUP_COMMANDS);
+        if (knifeSetupCommandsFromConfig!=null) return knifeSetupCommandsFromConfig;
+        
+        // if not supplied will use global config
+        return null;
+    }
+    
+    @Override
+    public <T2> KnifeTaskFactory<T2> returning(ScriptReturnType type) {
+        return (KnifeTaskFactory<T2>) super.<T2>returning(type);
+    }
+
+    @Override
+    public <RET2> KnifeTaskFactory<RET2> returning(Function<ProcessTaskWrapper<?>, RET2> resultTransformation) {
+        return (KnifeTaskFactory<RET2>) super.returning(resultTransformation);
+    }
+    
+    @Override
+    public KnifeTaskFactory<Boolean> returningIsExitCodeZero() {
+        return (KnifeTaskFactory<Boolean>) super.returningIsExitCodeZero();
+    }
+    
+    @Override
+    public KnifeTaskFactory<String> requiringZeroAndReturningStdout() {
+        return (KnifeTaskFactory<String>) super.requiringZeroAndReturningStdout();
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaAppUtils.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaAppUtils.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaAppUtils.java
new file mode 100644
index 0000000..81811fb
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaAppUtils.java
@@ -0,0 +1,263 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import static org.apache.brooklyn.util.JavaGroovyEquivalents.groovyTruth;
+
+import java.lang.management.ManagementFactory;
+import java.lang.management.MemoryUsage;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import javax.management.openmbean.CompositeData;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.core.config.render.RendererHints;
+import org.apache.brooklyn.policy.enricher.RollingTimeWindowMeanEnricher;
+import org.apache.brooklyn.policy.enricher.TimeFractionDeltaEnricher;
+import org.apache.brooklyn.sensor.feed.http.HttpValueFunctions;
+import org.apache.brooklyn.sensor.feed.jmx.JmxAttributePollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
+import org.apache.brooklyn.util.math.MathFunctions;
+import org.apache.brooklyn.util.text.ByteSizeStrings;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+
+import com.google.common.base.Function;
+
+public class JavaAppUtils {
+
+    public static boolean isEntityMxBeanStatsEnabled(Entity entity) {
+        return groovyTruth(entity.getConfig(UsesJavaMXBeans.MXBEAN_STATS_ENABLED));
+    }
+
+    /**
+     * @see #connectJavaAppServerPolicies(EntityLocal, Duration)
+     * @see #getMxBeanSensorsBuilder(EntityLocal)
+     */
+    @Nullable
+    public static JmxFeed connectMXBeanSensors(EntityLocal entity) {
+        if (isEntityMxBeanStatsEnabled(entity)) {
+            return getMxBeanSensorsBuilder(entity).build();
+        } else {
+            return null;
+        }
+    }
+
+    /** @see #connectJavaAppServerPolicies(EntityLocal, Duration) */
+    @Nullable
+    public static JmxFeed connectMXBeanSensors(EntityLocal entity, long jmxPollPeriodMs) {
+        if (isEntityMxBeanStatsEnabled(entity)) {
+            return getMxBeanSensorsBuilder(entity, jmxPollPeriodMs).build();
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * @param entity The entity at which to poll
+     * @param jmxPollPeriod How often to poll
+     * @return A {@link JmxFeed} configured to poll the given entity at the given period,
+     *         or null if the entity is not configured for MXBEAN_STATS
+     * @see org.apache.brooklyn.entity.java.UsesJavaMXBeans#MXBEAN_STATS_ENABLED
+     */
+    @Nullable
+    public static JmxFeed connectMXBeanSensors(EntityLocal entity, Duration jmxPollPeriod) {
+        if (isEntityMxBeanStatsEnabled(entity)) {
+            return getMxBeanSensorsBuilder(entity, jmxPollPeriod).build();
+        } else {
+            return null;
+        }
+    }
+    
+    public static void connectJavaAppServerPolicies(EntityLocal entity) {
+        connectJavaAppServerPolicies(entity, Duration.TEN_SECONDS);
+    }
+
+    public static void connectJavaAppServerPolicies(EntityLocal entity, Duration windowPeriod) {
+        entity.addEnricher(new TimeFractionDeltaEnricher<Double>(entity, UsesJavaMXBeans.PROCESS_CPU_TIME, 
+                UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_LAST, TimeUnit.MILLISECONDS));
+
+        entity.addEnricher(new RollingTimeWindowMeanEnricher<Double>(entity,
+                UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_LAST, UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_IN_WINDOW,
+                windowPeriod));
+    }
+
+    /**
+     * @param entity The entity at which to poll
+     * @return A {@link JmxFeed.Builder} configured to poll entity every ten seconds
+     * @see #getMxBeanSensorsBuilder(EntityLocal, Duration)
+     */
+    @Nonnull
+    public static JmxFeed.Builder getMxBeanSensorsBuilder(EntityLocal entity) {
+        return getMxBeanSensorsBuilder(entity, Duration.TEN_SECONDS);
+    }
+
+    /** @see #getMxBeanSensorsBuilder(EntityLocal, Duration) */
+    @Nonnull
+    public static JmxFeed.Builder getMxBeanSensorsBuilder(EntityLocal entity, long jmxPollPeriod) {
+        return getMxBeanSensorsBuilder(entity, Duration.millis(jmxPollPeriod));
+    }
+
+    /**
+     * @param entity The entity at which to poll
+     * @param jmxPollPeriod How often to poll
+     * @return A {@link JmxFeed.Builder} configured to poll many interesting MXBeans
+     *         at the given entity and to repeat according to the given poll period.
+     *         <p/>
+     *         If an entity does not have MXBean stats enabled (i.e. {@link UsesJavaMXBeans#MXBEAN_STATS_ENABLED} is
+     *         configured to false) then returns a builder configured with entity and duration but no polls.
+     *         <p/>
+     *         Use {@link #connectMXBeanSensors(EntityLocal, Duration)} to create and build in one step.
+     */
+    @Nonnull
+    @SuppressWarnings({"unchecked"})
+    public static JmxFeed.Builder getMxBeanSensorsBuilder(EntityLocal entity, Duration jmxPollPeriod) {
+        JmxFeed.Builder builder = JmxFeed.builder()
+                .entity(entity)
+                .period(jmxPollPeriod);
+        if (isEntityMxBeanStatsEnabled(entity)) {
+            // TODO Could we reuse the result of compositeDataToMemoryUsage?
+            builder
+                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.USED_HEAP_MEMORY)
+                        .objectName(ManagementFactory.MEMORY_MXBEAN_NAME)
+                        .attributeName("HeapMemoryUsage")
+                        .onSuccess((Function) HttpValueFunctions.chain(compositeDataToMemoryUsage(), new Function<MemoryUsage, Long>() {
+                            @Override public Long apply(MemoryUsage input) {
+                                return (input == null) ? null : input.getUsed();
+                            }})))
+                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.INIT_HEAP_MEMORY)
+                        .objectName(ManagementFactory.MEMORY_MXBEAN_NAME)
+                        .attributeName("HeapMemoryUsage")
+                        .onSuccess((Function) HttpValueFunctions.chain(compositeDataToMemoryUsage(), new Function<MemoryUsage, Long>() {
+                            @Override public Long apply(MemoryUsage input) {
+                                return (input == null) ? null : input.getInit();
+                            }})))
+                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.COMMITTED_HEAP_MEMORY)
+                        .objectName(ManagementFactory.MEMORY_MXBEAN_NAME)
+                        .attributeName("HeapMemoryUsage")
+                        .onSuccess((Function) HttpValueFunctions.chain(compositeDataToMemoryUsage(), new Function<MemoryUsage, Long>() {
+                            @Override public Long apply(MemoryUsage input) {
+                                return (input == null) ? null : input.getCommitted();
+                            }})))
+                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.MAX_HEAP_MEMORY)
+                        .objectName(ManagementFactory.MEMORY_MXBEAN_NAME)
+                        .attributeName("HeapMemoryUsage")
+                        .onSuccess((Function) HttpValueFunctions.chain(compositeDataToMemoryUsage(), new Function<MemoryUsage, Long>() {
+                            @Override public Long apply(MemoryUsage input) {
+                                return (input == null) ? null : input.getMax();
+                            }})))
+                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.NON_HEAP_MEMORY_USAGE)
+                        .objectName(ManagementFactory.MEMORY_MXBEAN_NAME)
+                        .attributeName("NonHeapMemoryUsage")
+                        .onSuccess((Function) HttpValueFunctions.chain(compositeDataToMemoryUsage(), new Function<MemoryUsage, Long>() {
+                            @Override public Long apply(MemoryUsage input) {
+                                return (input == null) ? null : input.getUsed();
+                            }})))
+
+                .pollAttribute(new JmxAttributePollConfig<Integer>(UsesJavaMXBeans.CURRENT_THREAD_COUNT)
+                        .objectName(ManagementFactory.THREAD_MXBEAN_NAME)
+                        .attributeName("ThreadCount"))
+                .pollAttribute(new JmxAttributePollConfig<Integer>(UsesJavaMXBeans.PEAK_THREAD_COUNT)
+                        .objectName(ManagementFactory.THREAD_MXBEAN_NAME)
+                        .attributeName("PeakThreadCount"))
+
+                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.START_TIME)
+                        .objectName(ManagementFactory.RUNTIME_MXBEAN_NAME)
+                        .period(60, TimeUnit.SECONDS)
+                        .attributeName("StartTime"))
+                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.UP_TIME)
+                        .objectName(ManagementFactory.RUNTIME_MXBEAN_NAME)
+                        .period(60, TimeUnit.SECONDS)
+                        .attributeName("Uptime"))
+
+                .pollAttribute(new JmxAttributePollConfig<Double>(UsesJavaMXBeans.PROCESS_CPU_TIME)
+                        .objectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME)
+                        .attributeName("ProcessCpuTime")
+                        .onSuccess((Function) MathFunctions.times(0.001*0.001)))   // nanos to millis
+                .pollAttribute(new JmxAttributePollConfig<Double>(UsesJavaMXBeans.SYSTEM_LOAD_AVERAGE)
+                        .objectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME)
+                        .attributeName("SystemLoadAverage"))
+                .pollAttribute(new JmxAttributePollConfig<Integer>(UsesJavaMXBeans.AVAILABLE_PROCESSORS)
+                        .objectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME)
+                        .period(60, TimeUnit.SECONDS)
+                        .attributeName("AvailableProcessors"))
+                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.TOTAL_PHYSICAL_MEMORY_SIZE)
+                        .objectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME)
+                        .period(60, TimeUnit.SECONDS)
+                        .attributeName("TotalPhysicalMemorySize"))
+                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.FREE_PHYSICAL_MEMORY_SIZE)
+                        .objectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME)
+                        .period(60, TimeUnit.SECONDS)
+                        .attributeName("FreePhysicalMemorySize"));
+         //FIXME: need a new type of adapter that maps multiple objectNames to a mapping
+         // jmxAdapter.objectName(ManagementFactory.GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",*").with {
+         //     attribute("SystemLoadAverage").subscribe(UsesJavaMXBeans.GARBAGE_COLLECTION_TIME, { def m -> log.info("XXXXXXX $m") });
+         // }
+        }
+        return builder;
+    }
+
+    /** @deprecated Since 0.7.0. Use {@link org.apache.brooklyn.util.math.MathFunctions#times(double)} instead */
+    @Deprecated
+    public static Function<Number, Double> times(final double x) {
+        return MathFunctions.times(x);
+    }
+
+    public static Function<CompositeData, MemoryUsage> compositeDataToMemoryUsage() {
+        return new Function<CompositeData, MemoryUsage>() {
+            @Override public MemoryUsage apply(CompositeData input) {
+                return (input == null) ? null : MemoryUsage.from(input);
+            }
+        };
+    }
+
+    private static final AtomicBoolean initialized = new AtomicBoolean(false);
+
+    /** Setup renderer hints for the MXBean attributes. */
+    public static void init() {
+        if (initialized.get()) return;
+        synchronized (initialized) {
+            if (initialized.get()) return;
+
+            RendererHints.register(UsesJavaMXBeans.USED_HEAP_MEMORY, RendererHints.displayValue(ByteSizeStrings.metric()));
+            RendererHints.register(UsesJavaMXBeans.INIT_HEAP_MEMORY, RendererHints.displayValue(ByteSizeStrings.metric()));
+            RendererHints.register(UsesJavaMXBeans.MAX_HEAP_MEMORY, RendererHints.displayValue(ByteSizeStrings.metric()));
+            RendererHints.register(UsesJavaMXBeans.COMMITTED_HEAP_MEMORY, RendererHints.displayValue(ByteSizeStrings.metric()));
+            RendererHints.register(UsesJavaMXBeans.NON_HEAP_MEMORY_USAGE, RendererHints.displayValue(ByteSizeStrings.metric()));
+            RendererHints.register(UsesJavaMXBeans.TOTAL_PHYSICAL_MEMORY_SIZE, RendererHints.displayValue(ByteSizeStrings.metric()));
+            RendererHints.register(UsesJavaMXBeans.FREE_PHYSICAL_MEMORY_SIZE, RendererHints.displayValue(ByteSizeStrings.metric()));
+
+            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(MathFunctions.percent(4)));
+            RendererHints.register(UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_IN_WINDOW, RendererHints.displayValue(MathFunctions.percent(4)));
+
+            initialized.set(true);
+        }
+    }
+
+    static {
+        init();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaEntityMethods.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaEntityMethods.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaEntityMethods.java
new file mode 100644
index 0000000..44afc8d
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaEntityMethods.java
@@ -0,0 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import org.apache.brooklyn.config.ConfigKey;
+
+/** DSL conveniences for Java entities. Also see {@link JavaAppUtils} for methods useful within Java classes. */
+public class JavaEntityMethods {
+
+    public static ConfigKey<String> javaSysProp(String propertyName) { return UsesJava.JAVA_SYSPROPS.subKey(propertyName); }
+    
+    // TODO javaMaxHeap javaInitialHeap javaMaxPermGen should all be supplied as ListConfigs on JAVA_OPTIONS
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessDriver.java
new file mode 100644
index 0000000..627a5d2
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessDriver.java
@@ -0,0 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
+
+/**
+ * A {@link SoftwareProcessDriver} for Java processes.
+ */
+public interface JavaSoftwareProcessDriver extends SoftwareProcessDriver {
+
+    public boolean isJmxEnabled();
+        
+}


[08/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareEffectorTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareEffectorTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareEffectorTest.java
new file mode 100644
index 0000000..b341b6e
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareEffectorTest.java
@@ -0,0 +1,141 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import java.util.Arrays;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks.SshEffectorBody;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+import com.google.common.base.Throwables;
+
+public class SoftwareEffectorTest {
+
+    private static final Logger log = LoggerFactory.getLogger(SoftwareEffectorTest.class);
+                
+    TestApplication app;
+    ManagementContext mgmt;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setup() throws Exception {
+        app = TestApplication.Factory.newManagedInstanceForTests();
+        mgmt = app.getManagementContext();
+        
+        LocalhostMachineProvisioningLocation lhc = mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class));
+        SshMachineLocation lh = lhc.obtain();
+        app.start(Arrays.asList(lh));
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (mgmt != null) Entities.destroyAll(mgmt);
+        mgmt = null;
+    }
+
+    public static final Effector<String> GET_REMOTE_DATE_1 = Effectors.effector(String.class, "getRemoteDate")
+            .description("retrieves the date from the remote machine")
+            .impl(new SshEffectorBody<String>() {
+                public String call(ConfigBag parameters) {
+                    queue( ssh("date").requiringZeroAndReturningStdout() );
+                    return last(String.class);
+                }
+            })
+            .build();
+
+    public static final Effector<String> GET_REMOTE_DATE_2 = Effectors.effector(GET_REMOTE_DATE_1)
+            // Just get year to confirm implementation is different
+            .description("retrieves the year from the remote machine")
+            .impl(SshEffectorTasks.ssh("date +%Y").requiringZeroAndReturningStdout())
+            .build();
+
+    // TODO revisit next two tests before end 2019 ;)
+
+    @Test(groups="Integration")
+    public void testSshDateEffector1() {
+        Task<String> call = Entities.invokeEffector(app, app, GET_REMOTE_DATE_1);
+        log.info("ssh date 1 gives: "+call.getUnchecked());
+        Assert.assertTrue(call.getUnchecked().indexOf("201") > 0);
+    }
+
+    @Test(groups="Integration")
+    public void testSshDateEffector2() {
+        Task<String> call = Entities.invokeEffector(app, app, GET_REMOTE_DATE_2);
+        log.info("ssh date 2 gives: "+call.getUnchecked());
+        Assert.assertTrue(call.getUnchecked().indexOf("201") == 0);
+    }
+
+    public static final String COMMAND_THAT_DOES_NOT_EXIST = "blah_blah_blah_command_DOES_NOT_EXIST";
+    
+    @Test(groups="Integration")
+    public void testBadExitCodeCaught() {
+        Task<Void> call = Entities.invokeEffector(app, app, Effectors.effector(Void.class, "badExitCode")
+                .impl(new SshEffectorBody<Void>() {
+                    public Void call(ConfigBag parameters) {
+                        queue( ssh(COMMAND_THAT_DOES_NOT_EXIST).requiringZeroAndReturningStdout() );
+                        return null;
+                    }
+                }).build() );
+        try {
+            Object result = call.getUnchecked();
+            Assert.fail("ERROR: should have failed earlier in this test, instead got successful task result "+result+" from "+call);
+        } catch (Exception e) {
+            Throwable root = Throwables.getRootCause(e);
+            if (!(root instanceof IllegalStateException)) Assert.fail("Should have failed with IAE, but got: "+root);
+            if (root.getMessage()==null || root.getMessage().indexOf("exit code")<=0) 
+                Assert.fail("Should have failed with 'exit code' message, but got: "+root);
+            // test passed
+            return;
+        }
+    }
+        
+    @Test(groups="Integration")
+    public void testBadExitCodeCaughtAndStdErrAvailable() {
+        final ProcessTaskWrapper<?>[] sshTasks = new ProcessTaskWrapper[1];
+        
+        Task<Void> call = Entities.invokeEffector(app, app, Effectors.effector(Void.class, "badExitCode")
+                .impl(new SshEffectorBody<Void>() {
+                    public Void call(ConfigBag parameters) {
+                        sshTasks[0] = queue( ssh(COMMAND_THAT_DOES_NOT_EXIST).requiringExitCodeZero() );
+                        return null;
+                    }
+                }).build() );
+        call.blockUntilEnded();
+        Assert.assertTrue(call.isError());
+        log.info("stderr gives: "+new String(sshTasks[0].getStderr()));
+        Assert.assertTrue(new String(sshTasks[0].getStderr()).indexOf(COMMAND_THAT_DOES_NOT_EXIST) >= 0);
+    }
+        
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityLatchTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityLatchTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityLatchTest.java
new file mode 100644
index 0000000..e743b24
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityLatchTest.java
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
+import java.util.List;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessEntityTest.MyService;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessEntityTest.SimulatedDriver;
+import org.apache.brooklyn.entity.stock.BasicEntity;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.sensor.core.DependentConfiguration;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.core.task.TaskInternal;
+import org.apache.brooklyn.util.time.Duration;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+
+
+public class SoftwareProcessEntityLatchTest extends BrooklynAppUnitTestSupport {
+
+    // NB: These tests don't actually require ssh to localhost -- only that 'localhost' resolves.
+
+    @SuppressWarnings("unused")
+    private static final Logger LOG = LoggerFactory.getLogger(SoftwareProcessEntityLatchTest.class);
+
+    private SshMachineLocation machine;
+    private FixedListMachineProvisioningLocation<SshMachineLocation> loc;
+    
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        loc = getLocation();
+    }
+
+    @SuppressWarnings("unchecked")
+    private FixedListMachineProvisioningLocation<SshMachineLocation> getLocation() {
+        FixedListMachineProvisioningLocation<SshMachineLocation> loc = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class));
+        machine = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure("address", "localhost"));
+        loc.addMachine(machine);
+        return loc;
+    }
+
+    @Test
+    public void testStartLatchBlocks() throws Exception {
+        runTestLatchBlocks(SoftwareProcess.START_LATCH, ImmutableList.<String>of());
+    }
+
+    @Test
+    public void testSetupLatchBlocks() throws Exception {
+        runTestLatchBlocks(SoftwareProcess.SETUP_LATCH, ImmutableList.<String>of());
+    }
+
+    @Test
+    public void testIntallResourcesLatchBlocks() throws Exception {
+        runTestLatchBlocks(SoftwareProcess.INSTALL_RESOURCES_LATCH, ImmutableList.of("setup"));
+    }
+
+    @Test
+    public void testInstallLatchBlocks() throws Exception {
+        runTestLatchBlocks(SoftwareProcess.INSTALL_LATCH, ImmutableList.of("setup", "copyInstallResources"));
+    }
+
+    @Test
+    public void testCustomizeLatchBlocks() throws Exception {
+        runTestLatchBlocks(SoftwareProcess.CUSTOMIZE_LATCH, ImmutableList.of("setup", "copyInstallResources", "install"));
+    }
+
+    @Test
+    public void testRuntimeResourcesLatchBlocks() throws Exception {
+        runTestLatchBlocks(SoftwareProcess.RUNTIME_RESOURCES_LATCH, ImmutableList.of("setup", "copyInstallResources", "install", "customize"));
+    }
+
+    @Test
+    public void testLaunchLatchBlocks() throws Exception {
+        runTestLatchBlocks(SoftwareProcess.LAUNCH_LATCH, ImmutableList.of("setup", "copyInstallResources", "install", "customize", "copyRuntimeResources"));
+    }
+
+    protected void runTestLatchBlocks(final ConfigKey<Boolean> latch, List<String> preLatchEvents) throws Exception {
+        final BasicEntity triggerEntity = app.createAndManageChild(EntitySpec.create(BasicEntity.class));
+        final MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)
+                .configure(latch, DependentConfiguration.attributeWhenReady(triggerEntity, Attributes.SERVICE_UP)));
+        
+        final Task<Void> task = Entities.invokeEffector(app, app, MyService.START, ImmutableMap.of("locations", ImmutableList.of(loc)));
+        
+        assertEffectorBlockingDetailsEventually(entity, "Waiting for config "+latch.getName());
+        assertDriverEventsEquals(entity, preLatchEvents);
+
+        assertFalse(task.isDone());
+        ((EntityLocal)triggerEntity).setAttribute(Attributes.SERVICE_UP, true);
+        task.get(Duration.THIRTY_SECONDS);
+        assertDriverEventsEquals(entity, ImmutableList.of("setup", "copyInstallResources", "install", "customize", "copyRuntimeResources", "launch"));
+    }
+
+    private void assertDriverEventsEquals(MyService entity, List<String> expectedEvents) {
+        List<String> events = ((SimulatedDriver)entity.getDriver()).events;
+        assertEquals(events, expectedEvents, "events="+events);
+    }
+
+    private void assertEffectorBlockingDetailsEventually(final Entity entity, final String blockingDetailsSnippet) {
+        Asserts.succeedsEventually(new Runnable() {
+            @Override public void run() {
+                Task<?> entityTask = Iterables.getOnlyElement(mgmt.getExecutionManager().getTasksWithAllTags(ImmutableList.of(BrooklynTaskTags.EFFECTOR_TAG, BrooklynTaskTags.tagForContextEntity(entity))));
+                String blockingDetails = getBlockingDetails(entityTask);
+                assertTrue(blockingDetails.contains(blockingDetailsSnippet));
+            }});
+    }
+    
+    private String getBlockingDetails(Task<?> task) {
+        List<TaskInternal<?>> taskChain = Lists.newArrayList();
+        TaskInternal<?> taskI = (TaskInternal<?>) task;
+        while (taskI != null) {
+            taskChain.add(taskI);
+            if (taskI.getBlockingDetails() != null) {
+                return taskI.getBlockingDetails();
+            }
+            taskI = (TaskInternal<?>) taskI.getBlockingTask();
+        }
+        throw new IllegalStateException("No blocking details for "+task+" (walked task chain "+taskChain+")");
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityRebindTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityRebindTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityRebindTest.java
new file mode 100644
index 0000000..475cb09
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityRebindTest.java
@@ -0,0 +1,179 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertTrue;
+
+import java.io.File;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic.ServiceProblemsLogic;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessEntityTest.MyService;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.AbstractLocation;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.io.Files;
+
+public class SoftwareProcessEntityRebindTest extends BrooklynAppUnitTestSupport {
+
+    private ClassLoader classLoader = getClass().getClassLoader();
+    private TestApplication newApp;
+    private ManagementContext newManagementContext;
+    private MyService origE;
+    private File mementoDir;
+    
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        mementoDir = Files.createTempDir();
+        mgmt = RebindTestUtils.newPersistingManagementContext(mementoDir, classLoader);
+        super.setUp();
+    }
+
+    @AfterMethod(alwaysRun=true)
+    @Override
+    public void tearDown() throws Exception {
+        super.tearDown();
+        if (newApp != null) Entities.destroyAll(newApp.getManagementContext());
+        if (newManagementContext != null) Entities.destroyAll(newManagementContext);
+        if (mementoDir != null) RebindTestUtils.deleteMementoDir(mementoDir);
+    }
+    
+    @Test
+    public void testReleasesLocationOnStopAfterRebinding() throws Exception {
+        origE = app.createAndManageChild(EntitySpec.create(MyService.class));
+        
+        MyProvisioningLocation origLoc = mgmt.getLocationManager().createLocation(LocationSpec.create(MyProvisioningLocation.class)
+                .displayName("mylocname"));
+        app.start(ImmutableList.of(origLoc));
+        assertEquals(origLoc.inUseCount.get(), 1);
+        
+        newApp = (TestApplication) rebind();
+        MyProvisioningLocation newLoc = (MyProvisioningLocation) Iterables.getOnlyElement(newApp.getLocations());
+        assertEquals(newLoc.inUseCount.get(), 1);
+        
+        newApp.stop();
+        assertEquals(newLoc.inUseCount.get(), 0);
+    }
+
+    @Test
+    public void testCreatesDriverAfterRebind() throws Exception {
+        origE = app.createAndManageChild(EntitySpec.create(MyService.class));
+        //the entity skips enricher initialization, do it explicitly
+        origE.addEnricher(ServiceStateLogic.newEnricherForServiceStateFromProblemsAndUp());
+
+        MyProvisioningLocation origLoc = mgmt.getLocationManager().createLocation(LocationSpec.create(MyProvisioningLocation.class)
+                .displayName("mylocname"));
+        app.start(ImmutableList.of(origLoc));
+        assertEquals(origE.getAttribute(Attributes.SERVICE_STATE_EXPECTED).getState(), Lifecycle.RUNNING);
+        EntityTestUtils.assertAttributeEqualsEventually(origE, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
+
+        ServiceProblemsLogic.updateProblemsIndicator((EntityLocal)origE, "test", "fire");
+        EntityTestUtils.assertAttributeEqualsEventually(origE, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);
+
+        newApp = (TestApplication) rebind();
+        MyService newE = (MyService) Iterables.getOnlyElement(newApp.getChildren());
+        assertTrue(newE.getDriver() != null, "driver should be initialized");
+    }
+
+    @Test
+    public void testDoesNotCreateDriverAfterRebind() throws Exception {
+        origE = app.createAndManageChild(EntitySpec.create(MyService.class));
+        //the entity skips enricher initialization, do it explicitly
+        origE.addEnricher(ServiceStateLogic.newEnricherForServiceStateFromProblemsAndUp());
+        
+        MyProvisioningLocation origLoc = mgmt.getLocationManager().createLocation(LocationSpec.create(MyProvisioningLocation.class)
+                .displayName("mylocname"));
+        app.start(ImmutableList.of(origLoc));
+        assertEquals(origE.getAttribute(Attributes.SERVICE_STATE_EXPECTED).getState(), Lifecycle.RUNNING);
+        EntityTestUtils.assertAttributeEqualsEventually(origE, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
+
+        ServiceStateLogic.setExpectedState(origE, Lifecycle.ON_FIRE);
+        EntityTestUtils.assertAttributeEqualsEventually(origE, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);
+
+        newApp = (TestApplication) rebind();
+        MyService newE = (MyService) Iterables.getOnlyElement(newApp.getChildren());
+        assertNull(newE.getDriver(), "driver should not be initialized because entity is in a permanent failure");
+    }
+
+    private TestApplication rebind() throws Exception {
+        RebindTestUtils.waitForPersisted(app);
+        TestApplication result = (TestApplication) RebindTestUtils.rebind(mementoDir, getClass().getClassLoader());
+        newManagementContext = result.getManagementContext();
+        return result;
+    }
+    
+    public static class MyProvisioningLocation extends AbstractLocation implements MachineProvisioningLocation<SshMachineLocation> {
+        private static final long serialVersionUID = 1L;
+        
+        @SetFromFlag(defaultVal="0")
+        AtomicInteger inUseCount;
+
+        public MyProvisioningLocation() {
+        }
+        
+        @Override
+        public MachineProvisioningLocation<SshMachineLocation> newSubLocation(Map<?, ?> newFlags) {
+            throw new UnsupportedOperationException();
+        }
+        
+        @Override
+        public SshMachineLocation obtain(Map flags) throws NoMachinesAvailableException {
+            inUseCount.incrementAndGet();
+            return getManagementContext().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                    .parent(this)
+                    .configure("address","localhost"));
+        }
+
+        @Override
+        public void release(SshMachineLocation machine) {
+            inUseCount.decrementAndGet();
+        }
+
+        @Override
+        public Map getProvisioningFlags(Collection tags) {
+            return Collections.emptyMap();
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityTest.java
new file mode 100644
index 0000000..0a6bd26
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityTest.java
@@ -0,0 +1,798 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.mgmt.EntityManager;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.api.mgmt.TaskAdaptable;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.apache.brooklyn.entity.drivers.BasicEntityDriverManager;
+import org.apache.brooklyn.entity.drivers.ReflectiveEntityDriverFactory;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcessImpl;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.RestartSoftwareParameters;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.StopSoftwareParameters;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.RestartSoftwareParameters.RestartMachineMode;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.StopSoftwareParameters.StopMode;
+import org.apache.brooklyn.entity.trait.Startable;
+import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.exceptions.PropagatedRuntimeException;
+import org.apache.brooklyn.util.net.UserAndHostAndPort;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.time.Duration;
+import org.jclouds.util.Throwables2;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+
+import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.basic.Locations;
+import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+
+public class SoftwareProcessEntityTest extends BrooklynAppUnitTestSupport {
+
+    // NB: These tests don't actually require ssh to localhost -- only that 'localhost' resolves.
+
+    private static final Logger LOG = LoggerFactory.getLogger(SoftwareProcessEntityTest.class);
+
+    private SshMachineLocation machine;
+    private FixedListMachineProvisioningLocation<SshMachineLocation> loc;
+    
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        loc = getLocation();
+    }
+
+    @SuppressWarnings("unchecked")
+    private FixedListMachineProvisioningLocation<SshMachineLocation> getLocation() {
+        FixedListMachineProvisioningLocation<SshMachineLocation> loc = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class));
+        machine = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure("address", "localhost"));
+        loc.addMachine(machine);
+        return loc;
+    }
+
+    @Test
+    public void testSetsMachineAttributes() throws Exception {
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
+        entity.start(ImmutableList.of(loc));
+        
+        assertEquals(entity.getAttribute(SoftwareProcess.HOSTNAME), machine.getAddress().getHostName());
+        assertEquals(entity.getAttribute(SoftwareProcess.ADDRESS), machine.getAddress().getHostAddress());
+        assertEquals(entity.getAttribute(Attributes.SSH_ADDRESS), UserAndHostAndPort.fromParts(machine.getUser(), machine.getAddress().getHostName(), machine.getPort()));
+        assertEquals(entity.getAttribute(SoftwareProcess.PROVISIONING_LOCATION), loc);
+    }
+
+    @Test
+    public void testProcessTemplateWithExtraSubstitutions() throws Exception {
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
+        entity.start(ImmutableList.of(loc));
+        SimulatedDriver driver = (SimulatedDriver) entity.getDriver();
+        Map<String,String> substitutions = MutableMap.of("myname","peter");
+        String result = driver.processTemplate("/org/apache/brooklyn/entity/software/base/template_with_extra_substitutions.txt",substitutions);
+        Assert.assertTrue(result.contains("peter"));
+    }
+
+    @Test
+    public void testInstallDirAndRunDir() throws Exception {
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)
+            .configure(BrooklynConfigKeys.ONBOX_BASE_DIR, "/tmp/brooklyn-foo"));
+
+        entity.start(ImmutableList.of(loc));
+
+        Assert.assertEquals(entity.getAttribute(SoftwareProcess.INSTALL_DIR), "/tmp/brooklyn-foo/installs/MyService");
+        Assert.assertEquals(entity.getAttribute(SoftwareProcess.RUN_DIR), "/tmp/brooklyn-foo/apps/"+entity.getApplicationId()+"/entities/MyService_"+entity.getId());
+    }
+
+    @Test
+    public void testInstallDirAndRunDirUsingTilde() throws Exception {
+        String dataDirName = ".brooklyn-foo"+Strings.makeRandomId(4);
+        String dataDir = "~/"+dataDirName;
+        String resolvedDataDir = Os.mergePaths(Os.home(), dataDirName);
+        
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)
+            .configure(BrooklynConfigKeys.ONBOX_BASE_DIR, dataDir));
+
+        entity.start(ImmutableList.of(loc));
+
+        Assert.assertEquals(Os.nativePath(entity.getAttribute(SoftwareProcess.INSTALL_DIR)),
+                            Os.nativePath(Os.mergePaths(resolvedDataDir, "installs/MyService")));
+        Assert.assertEquals(Os.nativePath(entity.getAttribute(SoftwareProcess.RUN_DIR)),
+                            Os.nativePath(Os.mergePaths(resolvedDataDir, "apps/"+entity.getApplicationId()+"/entities/MyService_"+entity.getId())));
+    }
+
+    protected <T extends MyService> void doStartAndCheckVersion(Class<T> type, String expectedLabel, ConfigBag config) {
+        MyService entity = app.createAndManageChild(EntitySpec.create(type)
+            .configure(BrooklynConfigKeys.ONBOX_BASE_DIR, "/tmp/brooklyn-foo")
+            .configure(config.getAllConfigAsConfigKeyMap()));
+        entity.start(ImmutableList.of(loc));
+        Assert.assertEquals(entity.getAttribute(SoftwareProcess.INSTALL_DIR), "/tmp/brooklyn-foo/installs/"
+            + expectedLabel);
+    }
+    
+    @Test
+    public void testCustomInstallDir0() throws Exception {
+        doStartAndCheckVersion(MyService.class, "MyService", ConfigBag.newInstance());
+    }
+    @Test
+    public void testCustomInstallDir1() throws Exception {
+        doStartAndCheckVersion(MyService.class, "MyService_9.9.8", ConfigBag.newInstance()
+            .configure(SoftwareProcess.SUGGESTED_VERSION, "9.9.8"));
+    }
+    @Test
+    public void testCustomInstallDir2() throws Exception {
+        doStartAndCheckVersion(MyService.class, "MySvc_998", ConfigBag.newInstance()
+            .configure(SoftwareProcess.INSTALL_UNIQUE_LABEL, "MySvc_998"));
+    }
+    @Test
+    public void testCustomInstallDir3() throws Exception {
+        doStartAndCheckVersion(MyServiceWithVersion.class, "MyServiceWithVersion_9.9.9", ConfigBag.newInstance());
+    }
+    @Test
+    public void testCustomInstallDir4() throws Exception {
+        doStartAndCheckVersion(MyServiceWithVersion.class, "MyServiceWithVersion_9.9.7", ConfigBag.newInstance()
+            .configure(SoftwareProcess.SUGGESTED_VERSION, "9.9.7"));
+    }
+    @Test
+    public void testCustomInstallDir5() throws Exception {
+        doStartAndCheckVersion(MyServiceWithVersion.class, "MyServiceWithVersion_9.9.9_NaCl", ConfigBag.newInstance()
+            .configure(ConfigKeys.newStringConfigKey("salt"), "NaCl"));
+    }
+
+    @Test
+    public void testBasicSoftwareProcessEntityLifecycle() throws Exception {
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
+        entity.start(ImmutableList.of(loc));
+        SimulatedDriver d = (SimulatedDriver) entity.getDriver();
+        Assert.assertTrue(d.isRunning());
+        entity.stop();
+        Assert.assertEquals(d.events, ImmutableList.of("setup", "copyInstallResources", "install", "customize", "copyRuntimeResources", "launch", "stop"));
+        assertFalse(d.isRunning());
+    }
+    
+    @Test
+    public void testBasicSoftwareProcessRestarts() throws Exception {
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
+        entity.start(ImmutableList.of(loc));
+        SimulatedDriver d = (SimulatedDriver) entity.getDriver();
+        Assert.assertTrue(d.isRunning());
+        
+        // this will cause restart to fail if it attempts to replace the machine
+        loc.removeMachine(Locations.findUniqueSshMachineLocation(entity.getLocations()).get());
+        
+        // with defaults, it won't reboot machine
+        d.events.clear();
+        entity.restart();
+        assertEquals(d.events, ImmutableList.of("stop", "launch"));
+
+        // but here, it will try to reboot, and fail because there is no machine available
+        TaskAdaptable<Void> t1 = Entities.submit(entity, Effectors.invocation(entity, Startable.RESTART, 
+                ConfigBag.newInstance().configure(RestartSoftwareParameters.RESTART_MACHINE_TYPED, RestartMachineMode.TRUE)));
+        t1.asTask().blockUntilEnded(Duration.TEN_SECONDS);
+        if (!t1.asTask().isError()) {
+            Assert.fail("Should have thrown error during "+t1+" because no more machines available at "+loc);
+        }
+
+        // now it has a machine, so reboot should succeed
+        SshMachineLocation machine2 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+            .configure("address", "localhost"));
+        loc.addMachine(machine2);
+        TaskAdaptable<Void> t2 = Entities.submit(entity, Effectors.invocation(entity, Startable.RESTART, 
+            ConfigBag.newInstance().configure(RestartSoftwareParameters.RESTART_MACHINE_TYPED, RestartMachineMode.TRUE)));
+        t2.asTask().get();
+        
+        assertFalse(d.isRunning());
+    }
+
+    @Test
+    public void testBasicSoftwareProcessStopsEverything() throws Exception {
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
+        entity.start(ImmutableList.of(loc));
+        SimulatedDriver d = (SimulatedDriver) entity.getDriver();
+        Location machine = Iterables.getOnlyElement(entity.getLocations());
+
+        d.events.clear();
+        entity.stop();
+        assertEquals(d.events, ImmutableList.of("stop"));
+        assertEquals(entity.getLocations().size(), 0);
+        assertTrue(loc.getAvailable().contains(machine));
+    }
+
+    @Test
+    public void testBasicSoftwareProcessStopEverythingExplicitly() throws Exception {
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
+        entity.start(ImmutableList.of(loc));
+        SimulatedDriver d = (SimulatedDriver) entity.getDriver();
+        Location machine = Iterables.getOnlyElement(entity.getLocations());
+        d.events.clear();
+
+        TaskAdaptable<Void> t1 = Entities.submit(entity, Effectors.invocation(entity, Startable.STOP,
+                ConfigBag.newInstance().configure(StopSoftwareParameters.STOP_MACHINE_MODE, StopSoftwareParameters.StopMode.IF_NOT_STOPPED)));
+        t1.asTask().get();
+
+        assertEquals(d.events, ImmutableList.of("stop"));
+        assertEquals(entity.getLocations().size(), 0);
+        assertTrue(loc.getAvailable().contains(machine));
+    }
+
+    @Test
+    public void testBasicSoftwareProcessStopsProcess() throws Exception {
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
+        entity.start(ImmutableList.of(loc));
+        SimulatedDriver d = (SimulatedDriver) entity.getDriver();
+        Location machine = Iterables.getOnlyElement(entity.getLocations());
+        d.events.clear();
+
+        TaskAdaptable<Void> t1 = Entities.submit(entity, Effectors.invocation(entity, Startable.STOP,
+                ConfigBag.newInstance().configure(StopSoftwareParameters.STOP_MACHINE_MODE, StopSoftwareParameters.StopMode.NEVER)));
+        t1.asTask().get(10, TimeUnit.SECONDS);
+
+        assertEquals(d.events, ImmutableList.of("stop"));
+        assertEquals(ImmutableList.copyOf(entity.getLocations()), ImmutableList.of(machine));
+        assertFalse(loc.getAvailable().contains(machine));
+    }
+    
+    @Test(groups = "Integration")
+    public void testBasicSoftwareProcessStopAllModes() throws Exception {
+        for (boolean isEntityStopped : new boolean[] {true, false}) {
+            for (StopMode stopProcessMode : StopMode.values()) {
+                for (StopMode stopMachineMode : StopMode.values()) {
+                    try {
+                        testBasicSoftwareProcessStopModes(stopProcessMode, stopMachineMode, isEntityStopped);
+                    } catch (Exception e) {
+                        String msg = "stopProcessMode: " + stopProcessMode + ", stopMachineMode: " + stopMachineMode + ", isEntityStopped: " + isEntityStopped;
+                        throw new PropagatedRuntimeException(msg, e);
+                    }
+                }
+            }
+        }
+    }
+    
+    @Test
+    public void testBasicSoftwareProcessStopSomeModes() throws Exception {
+        for (boolean isEntityStopped : new boolean[] {true, false}) {
+            StopMode stopProcessMode = StopMode.IF_NOT_STOPPED;
+            StopMode stopMachineMode = StopMode.IF_NOT_STOPPED;
+            try {
+                testBasicSoftwareProcessStopModes(stopProcessMode, stopMachineMode, isEntityStopped);
+            } catch (Exception e) {
+                String msg = "stopProcessMode: " + stopProcessMode + ", stopMachineMode: " + stopMachineMode + ", isEntityStopped: " + isEntityStopped;
+                throw new PropagatedRuntimeException(msg, e);
+            }
+        }
+    }
+    
+    private void testBasicSoftwareProcessStopModes(StopMode stopProcessMode, StopMode stopMachineMode, boolean isEntityStopped) throws Exception {
+        FixedListMachineProvisioningLocation<SshMachineLocation> l = getLocation();
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
+        entity.start(ImmutableList.of(l));
+        SimulatedDriver d = (SimulatedDriver) entity.getDriver();
+        Location machine = Iterables.getOnlyElement(entity.getLocations());
+        d.events.clear();
+
+        if (isEntityStopped) {
+            ((EntityInternal)entity).setAttribute(ServiceStateLogic.SERVICE_STATE_ACTUAL, Lifecycle.STOPPED);
+        }
+
+        TaskAdaptable<Void> t1 = Entities.submit(entity, Effectors.invocation(entity, Startable.STOP,
+                ConfigBag.newInstance()
+                    .configure(StopSoftwareParameters.STOP_PROCESS_MODE, stopProcessMode)
+                    .configure(StopSoftwareParameters.STOP_MACHINE_MODE, stopMachineMode)));
+        t1.asTask().get(10, TimeUnit.SECONDS);
+
+        if (MachineLifecycleEffectorTasksTest.canStop(stopProcessMode, isEntityStopped)) {
+            assertEquals(d.events, ImmutableList.of("stop"));
+        } else {
+            assertTrue(d.events.isEmpty());
+        }
+        if (MachineLifecycleEffectorTasksTest.canStop(stopMachineMode, machine == null)) {
+            assertTrue(entity.getLocations().isEmpty());
+            assertTrue(l.getAvailable().contains(machine));
+        } else {
+            assertEquals(ImmutableList.copyOf(entity.getLocations()), ImmutableList.of(machine));
+            assertFalse(l.getAvailable().contains(machine));
+        }
+    }
+
+    @Test
+    public void testShutdownIsIdempotent() throws Exception {
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
+        entity.start(ImmutableList.of(loc));
+        entity.stop();
+        
+        entity.stop();
+    }
+    
+    @Test
+    public void testReleaseEvenIfErrorDuringStart() throws Exception {
+        MyServiceImpl entity = new MyServiceImpl(app) {
+            @Override public Class<?> getDriverInterface() {
+                return SimulatedFailOnStartDriver.class;
+            }
+        };
+        Entities.manage(entity);
+        
+        try {
+            entity.start(ImmutableList.of(loc));
+            Assert.fail();
+        } catch (Exception e) {
+            IllegalStateException cause = Throwables2.getFirstThrowableOfType(e, IllegalStateException.class);
+            if (cause == null || !cause.toString().contains("Simulating start error")) throw e; 
+        }
+        
+        try {
+            entity.stop();
+        } catch (Exception e) {
+            // Keep going
+            LOG.info("Error during stop, after simulating error during start", e);
+        }
+        Assert.assertEquals(loc.getAvailable(), ImmutableSet.of(machine));
+        Entities.unmanage(entity);
+    }
+
+    @SuppressWarnings("rawtypes")
+    public void doTestReleaseEvenIfErrorDuringStop(final Class driver) throws Exception {
+        MyServiceImpl entity = new MyServiceImpl(app) {
+            @Override public Class<?> getDriverInterface() {
+                return driver;
+            }
+        };
+        Entities.manage(entity);
+        
+        entity.start(ImmutableList.of(loc));
+        Task<Void> t = entity.invoke(Startable.STOP);
+        t.blockUntilEnded();
+        
+        assertFalse(t.isError(), "Expected parent to succeed, not fail with " + Tasks.getError(t));
+        Iterator<Task<?>> failures;
+        failures = Tasks.failed(Tasks.descendants(t, true)).iterator();
+        Assert.assertTrue(failures.hasNext(), "Expected error in descendants");
+        failures = Tasks.failed(Tasks.children(t)).iterator();
+        Assert.assertTrue(failures.hasNext(), "Expected error in child");
+        Throwable e = Tasks.getError(failures.next());
+        if (e == null || !e.toString().contains("Simulating stop error")) 
+            Assert.fail("Wrong error", e);
+
+        Assert.assertEquals(loc.getAvailable(), ImmutableSet.of(machine), "Expected location to be available again");
+
+        Entities.unmanage(entity);
+    }
+
+    @Test
+    public void testReleaseEvenIfErrorDuringStop() throws Exception {
+        doTestReleaseEvenIfErrorDuringStop(SimulatedFailOnStopDriver.class);
+    }
+    
+    @Test
+    public void testReleaseEvenIfChildErrorDuringStop() throws Exception {
+        doTestReleaseEvenIfErrorDuringStop(SimulatedFailInChildOnStopDriver.class);
+    }
+
+    @Test
+    public void testDoubleStopEntity() {
+        ReflectiveEntityDriverFactory f = ((BasicEntityDriverManager)mgmt.getEntityDriverManager()).getReflectiveDriverFactory();
+        f.addClassFullNameMapping(EmptySoftwareProcessDriver.class.getName(), MinimalEmptySoftwareProcessTestDriver.class.getName());
+
+        // Second stop on SoftwareProcess will return early, while the first stop is still in progress
+        // This causes the app to shutdown prematurely, leaking machines.
+        EntityManager emgr = mgmt.getEntityManager();
+        EntitySpec<TestApplication> appSpec = EntitySpec.create(TestApplication.class);
+        TestApplication app = emgr.createEntity(appSpec);
+        emgr.manage(app);
+        EntitySpec<?> latchEntitySpec = EntitySpec.create(EmptySoftwareProcess.class);
+        Entity entity = app.createAndManageChild(latchEntitySpec);
+
+        final ReleaseLatchLocation loc = mgmt.getLocationManager().createLocation(LocationSpec.create(ReleaseLatchLocation.class));
+        try {
+            app.start(ImmutableSet.of(loc));
+            EntityTestUtils.assertAttributeEquals(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
+    
+            final Task<Void> firstStop = entity.invoke(Startable.STOP, ImmutableMap.<String, Object>of());
+            // Wait until first task tries to release the location, at this point the entity's reference 
+            // to the location is already cleared.
+            Asserts.succeedsEventually(new Runnable() {
+                @Override
+                public void run() {
+                    assertTrue(loc.isBlocked());
+                }
+            });
+    
+            // Subsequent stops will end quickly - no location to release,
+            // while the first one is still releasing the machine.
+            final Task<Void> secondStop = entity.invoke(Startable.STOP, ImmutableMap.<String, Object>of());;
+            Asserts.succeedsEventually(new Runnable() {
+                @Override
+                public void run() {
+                    assertTrue(secondStop.isDone());
+                }
+            });
+    
+            // Entity state is STOPPED even though first location is still releasing
+            EntityTestUtils.assertAttributeEquals(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.STOPPED);
+            Asserts.succeedsContinually(new Runnable() {
+                @Override
+                public void run() {
+                    assertFalse(firstStop.isDone());
+                }
+            });
+
+            loc.unblock();
+
+            // After the location is released, first task ends as well.
+            EntityTestUtils.assertAttributeEquals(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.STOPPED);
+            Asserts.succeedsEventually(new Runnable() {
+                @Override
+                public void run() {
+                    assertTrue(firstStop.isDone());
+                }
+            });
+
+        } finally {
+            loc.unblock();
+        }
+
+    }
+
+    @Test
+    public void testDoubleStopApp() {
+        ReflectiveEntityDriverFactory f = ((BasicEntityDriverManager)mgmt.getEntityDriverManager()).getReflectiveDriverFactory();
+        f.addClassFullNameMapping(EmptySoftwareProcessDriver.class.getName(), MinimalEmptySoftwareProcessTestDriver.class.getName());
+
+        // Second stop on SoftwareProcess will return early, while the first stop is still in progress
+        // This causes the app to shutdown prematurely, leaking machines.
+        EntityManager emgr = mgmt.getEntityManager();
+        EntitySpec<TestApplication> appSpec = EntitySpec.create(TestApplication.class);
+        final TestApplication app = emgr.createEntity(appSpec);
+        emgr.manage(app);
+        EntitySpec<?> latchEntitySpec = EntitySpec.create(EmptySoftwareProcess.class);
+        final Entity entity = app.createAndManageChild(latchEntitySpec);
+
+        final ReleaseLatchLocation loc = mgmt.getLocationManager().createLocation(LocationSpec.create(ReleaseLatchLocation.class));
+        try {
+            app.start(ImmutableSet.of(loc));
+            EntityTestUtils.assertAttributeEquals(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
+    
+            final Task<Void> firstStop = app.invoke(Startable.STOP, ImmutableMap.<String, Object>of());
+            // Wait until first task tries to release the location, at this point the entity's reference 
+            // to the location is already cleared.
+            Asserts.succeedsEventually(new Runnable() {
+                @Override
+                public void run() {
+                    assertTrue(loc.isBlocked());
+                }
+            });
+    
+            // Subsequent stops will end quickly - no location to release,
+            // while the first one is still releasing the machine.
+            final Task<Void> secondStop = app.invoke(Startable.STOP, ImmutableMap.<String, Object>of());;
+            Asserts.succeedsEventually(new Runnable() {
+                @Override
+                public void run() {
+                    assertTrue(secondStop.isDone());
+                }
+            });
+    
+            // Since second stop succeeded the app will get unmanaged.
+            Asserts.succeedsEventually(new Runnable() {
+                @Override
+                public void run() {
+                    assertTrue(!Entities.isManaged(entity));
+                    assertTrue(!Entities.isManaged(app));
+                }
+            });
+    
+            // Unmanage will cancel the first task
+            Asserts.succeedsEventually(new Runnable() {
+                @Override
+                public void run() {
+                    assertTrue(firstStop.isDone());
+                }
+            });
+        } finally {
+            // We still haven't unblocked the location release, but entity is already unmanaged.
+            // Double STOP on an application could leak locations!!!
+            loc.unblock();
+        }
+    }
+
+    @Test
+    public void testOpenPortsWithPortRangeConfig() throws Exception {
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)
+            .configure("http.port", "9999+"));
+        Assert.assertTrue(entity.getRequiredOpenPorts().contains(9999));
+    }
+
+    @ImplementedBy(MyServiceImpl.class)
+    public interface MyService extends SoftwareProcess {
+        PortAttributeSensorAndConfigKey HTTP_PORT = Attributes.HTTP_PORT;
+        public SoftwareProcessDriver getDriver();
+        public Collection<Integer> getRequiredOpenPorts();
+    }
+
+    public static class MyServiceImpl extends SoftwareProcessImpl implements MyService {
+        public MyServiceImpl() {}
+        public MyServiceImpl(Entity parent) { super(parent); }
+
+        @Override
+        protected void initEnrichers() {
+            // Don't add enrichers messing with the SERVICE_UP state - we are setting it manually
+        }
+
+        @Override
+        public Class<?> getDriverInterface() {
+            return SimulatedDriver.class;
+        }
+
+        @Override
+        public Collection<Integer> getRequiredOpenPorts() {
+            return super.getRequiredOpenPorts();
+        }
+    }
+
+    @ImplementedBy(MyServiceWithVersionImpl.class)
+    public interface MyServiceWithVersion extends MyService {
+        public static ConfigKey<String> SUGGESTED_VERSION = ConfigKeys.newConfigKeyWithDefault(SoftwareProcess.SUGGESTED_VERSION, "9.9.9");
+    }
+
+    public static class MyServiceWithVersionImpl extends MyServiceImpl implements MyServiceWithVersion {
+        public MyServiceWithVersionImpl() {}
+        public MyServiceWithVersionImpl(Entity parent) { super(parent); }
+    }
+
+    public static class SimulatedFailOnStartDriver extends SimulatedDriver {
+        public SimulatedFailOnStartDriver(EntityLocal entity, SshMachineLocation machine) {
+            super(entity, machine);
+        }
+        
+        @Override
+        public void install() {
+            throw new IllegalStateException("Simulating start error");
+        }
+    }
+    
+    public static class SimulatedFailOnStopDriver extends SimulatedDriver {
+        public SimulatedFailOnStopDriver(EntityLocal entity, SshMachineLocation machine) {
+            super(entity, machine);
+        }
+        
+        @Override
+        public void stop() {
+            throw new IllegalStateException("Simulating stop error");
+        }
+    }
+    
+    public static class SimulatedFailInChildOnStopDriver extends SimulatedDriver {
+        public SimulatedFailInChildOnStopDriver(EntityLocal entity, SshMachineLocation machine) {
+            super(entity, machine);
+        }
+        
+        @Override
+        public void stop() {
+            DynamicTasks.queue(Tasks.fail("Simulating stop error in child", null));
+        }
+    }
+    
+    public static class SimulatedDriver extends AbstractSoftwareProcessSshDriver {
+        public List<String> events = new ArrayList<String>();
+        private volatile boolean launched = false;
+        
+        public SimulatedDriver(EntityLocal entity, SshMachineLocation machine) {
+            super(entity, machine);
+        }
+
+        @Override
+        public boolean isRunning() {
+            return launched;
+        }
+    
+        @Override
+        public void stop() {
+            events.add("stop");
+            launched = false;
+            entity.setAttribute(Startable.SERVICE_UP, false);
+            entity.setAttribute(SoftwareProcess.SERVICE_STATE_ACTUAL, Lifecycle.STOPPED);
+        }
+    
+        @Override
+        public void kill() {
+            events.add("kill");
+            launched = false;
+            entity.setAttribute(Startable.SERVICE_UP, false);
+        }
+    
+        @Override
+        public void install() {
+            events.add("install");
+            entity.setAttribute(SoftwareProcess.SERVICE_STATE_ACTUAL, Lifecycle.STARTING);
+        }
+    
+        @Override
+        public void customize() {
+            events.add("customize");
+        }
+    
+        @Override
+        public void launch() {
+            events.add("launch");
+            launched = true;
+            entity.setAttribute(Startable.SERVICE_UP, true);
+            entity.setAttribute(SoftwareProcess.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
+        }
+
+        @Override
+        public void setup() {
+            events.add("setup");
+        }
+
+        @Override
+        public void copyInstallResources() {
+            events.add("copyInstallResources");
+        }
+
+        @Override
+        public void copyRuntimeResources() {
+            events.add("copyRuntimeResources");
+        }
+
+        @Override
+        public void runPreInstallCommand(String command) { }
+
+        @Override
+        public void runPostInstallCommand(String command) { }
+
+        @Override
+        public void runPreLaunchCommand(String command) { }
+
+        @Override
+        public void runPostLaunchCommand(String command) { }
+
+        @Override
+        protected String getInstallLabelExtraSalt() {
+            return (String)getEntity().getConfigRaw(ConfigKeys.newStringConfigKey("salt"), true).or((String)null);
+        }
+    }
+
+    public static class ReleaseLatchLocation extends SimulatedLocation {
+        private static final long serialVersionUID = 1L;
+        
+        private CountDownLatch lock = new CountDownLatch(1);
+        private volatile boolean isBlocked;
+
+        public void unblock() {
+            lock.countDown();
+        }
+        @Override
+        public void release(MachineLocation machine) {
+            super.release(machine);
+            try {
+                isBlocked = true;
+                lock.await();
+                isBlocked = false;
+            } catch (InterruptedException e) {
+                throw Exceptions.propagate(e);
+            }
+        }
+
+        public boolean isBlocked() {
+            return isBlocked;
+        }
+
+    }
+
+    public static class MinimalEmptySoftwareProcessTestDriver implements EmptySoftwareProcessDriver {
+
+        private EmptySoftwareProcessImpl entity;
+        private Location location;
+
+        public MinimalEmptySoftwareProcessTestDriver(EmptySoftwareProcessImpl entity, Location location) {
+            this.entity = entity;
+            this.location = location;
+        }
+
+        @Override
+        public Location getLocation() {
+            return location;
+        }
+
+        @Override
+        public EntityLocal getEntity() {
+            return entity;
+        }
+
+        @Override
+        public boolean isRunning() {
+            return true;
+        }
+
+        @Override
+        public void rebind() {
+        }
+
+        @Override
+        public void start() {
+        }
+
+        @Override
+        public void restart() {
+        }
+
+        @Override
+        public void stop() {
+        }
+
+        @Override
+        public void kill() {
+        }
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessSshDriverIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessSshDriverIntegrationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessSshDriverIntegrationTest.java
new file mode 100644
index 0000000..1b270b9
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessSshDriverIntegrationTest.java
@@ -0,0 +1,389 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
+import org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess;
+import org.apache.brooklyn.entity.trait.Startable;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.BrooklynNetworkUtils;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.stream.KnownSizeInputStream;
+import org.apache.brooklyn.util.stream.Streams;
+import org.apache.brooklyn.util.yaml.Yamls;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+import com.google.common.base.Charsets;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.io.ByteSource;
+import com.google.common.io.Files;
+
+
+public class SoftwareProcessSshDriverIntegrationTest {
+
+    private LocalManagementContext managementContext;
+    private LocalhostMachineProvisioningLocation localhost;
+    private SshMachineLocation machine127;
+    private TestApplication app;
+    private File tempDataDir;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        tempDataDir = Files.createTempDir();
+        managementContext = new LocalManagementContext();
+        
+        localhost = managementContext.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class));
+        machine127 = managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure("address", "localhost"));
+        app = ApplicationBuilder.newManagedApp(TestApplication.class, managementContext);
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (app != null) Entities.destroyAll(app.getManagementContext());
+        if (tempDataDir != null) Os.deleteRecursively(tempDataDir);
+    }
+
+    // Integration test because requires ssh'ing (and takes about 5 seconds)
+    // See also SoftwareProcessEntityTest.testCustomInstallDirX for a lot more mocked variants
+    @Test(groups="Integration")
+    public void testCanInstallMultipleVersionsOnSameMachine() throws Exception {
+        managementContext.getBrooklynProperties().put(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath());
+
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)
+                .configure(SoftwareProcess.SUGGESTED_VERSION, "0.1.0"));
+        MyService entity2 = app.createAndManageChild(EntitySpec.create(MyService.class)
+                .configure(SoftwareProcess.SUGGESTED_VERSION, "0.2.0"));
+        app.start(ImmutableList.of(machine127));
+        
+        String installDir1 = entity.getAttribute(SoftwareProcess.INSTALL_DIR);
+        String installDir2 = entity2.getAttribute(SoftwareProcess.INSTALL_DIR);
+        
+        assertNotEquals(installDir1, installDir2);
+        assertTrue(installDir1.contains("0.1.0"), "installDir1="+installDir1);
+        assertTrue(installDir2.contains("0.2.0"), "installDir2="+installDir2);
+        assertTrue(new File(new File(installDir1), "myfile").isFile());
+        assertTrue(new File(new File(installDir2), "myfile").isFile());
+    }
+
+    @Test(groups="Integration")
+    public void testLocalhostInTmp() throws Exception {
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
+        app.start(ImmutableList.of(localhost));
+
+        String installDir = entity.getAttribute(SoftwareProcess.INSTALL_DIR);
+        assertTrue(installDir.startsWith("/tmp/brooklyn-"+Os.user()+"/installs/"), "installed in "+installDir);
+    }
+
+    @Test(groups="Integration")
+    public void testMachine127InHome() throws Exception {
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
+        app.start(ImmutableList.of(machine127));
+
+        String installDir = entity.getAttribute(SoftwareProcess.INSTALL_DIR);
+        assertTrue(installDir.startsWith(Os.home()+"/brooklyn-managed-processes/installs/"), "installed in "+installDir);
+    }
+
+    @Test(groups="Integration")
+    public void testLocalhostInCustom() throws Exception {
+        localhost.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath());
+
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
+        app.start(ImmutableList.of(localhost));
+
+        String installDir = entity.getAttribute(SoftwareProcess.INSTALL_DIR);
+        assertTrue(installDir.startsWith(tempDataDir.getAbsolutePath()+"/installs/"), "installed in "+installDir);
+    }
+
+    @Test(groups="Integration")
+    @Deprecated
+    public void testMachineInCustomFromDataDir() throws Exception {
+        managementContext.getBrooklynProperties().put(BrooklynConfigKeys.BROOKLYN_DATA_DIR, tempDataDir.getAbsolutePath());
+
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
+        app.start(ImmutableList.of(machine127));
+
+        String installDir = entity.getAttribute(SoftwareProcess.INSTALL_DIR);
+        assertTrue(installDir.startsWith(tempDataDir.getAbsolutePath()+"/installs/"), "installed in "+installDir);
+    }
+
+    @Test(groups="Integration")
+    public void testCopyResource() throws Exception {
+        File tempDest = new File(tempDataDir, "tempDest.txt");
+        String tempLocalContent = "abc";
+        File tempLocal = new File(tempDataDir, "tempLocal.txt");
+        Files.write(tempLocalContent, tempLocal, Charsets.UTF_8);
+        
+        localhost.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath());
+
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
+        app.start(ImmutableList.of(localhost));
+
+        // Copy local file
+        entity.getDriver().copyResource(tempLocal, tempDest.getAbsolutePath());
+        assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent));
+        tempDest.delete();
+        
+        // Copy local file using url
+        entity.getDriver().copyResource(tempLocal.toURI().toString(), tempDest.getAbsolutePath());
+        assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent));
+        tempDest.delete();
+        
+        // Copy reader
+        entity.getDriver().copyResource(new StringReader(tempLocalContent), tempDest.getAbsolutePath());
+        assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent));
+        tempDest.delete();
+        
+        // Copy stream
+        entity.getDriver().copyResource(ByteSource.wrap(tempLocalContent.getBytes()).openStream(), tempDest.getAbsolutePath());
+        assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent));
+        tempDest.delete();
+        
+        // Copy known-size stream
+        entity.getDriver().copyResource(new KnownSizeInputStream(Streams.newInputStreamWithContents(tempLocalContent), tempLocalContent.length()), tempDest.getAbsolutePath());
+        assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent));
+        tempDest.delete();
+    }
+
+    @Test(groups="Integration")
+    public void testCopyResourceCreatingParentDir() throws Exception {
+        /*
+         * TODO copyResource will now always create the parent dir, irrespective of the createParentDir value!
+         * In SshMachineLocation on 2014-05-29, Alex added: mkdir -p `dirname '$DEST'`
+         * 
+         * Changing this test to assert that parent dir always created; should we delete boolean createParentDir
+         * from the copyResource method?
+         * 
+         * TODO Have also deleted test that if relative path is given it will write that relative to $RUN_DIR.
+         * That is not the case: it is relative to $HOME, which seems fine. For example, if copyResource
+         * is used during install phase then $RUN_DIR would be the wrong default. 
+         * Is there any code that relies on this behaviour?
+         */
+        File tempDataDirSub = new File(tempDataDir, "subdir");
+        File tempDest = new File(tempDataDirSub, "tempDest.txt");
+        String tempLocalContent = "abc";
+        File tempLocal = new File(tempDataDir, "tempLocal.txt");
+        Files.write(tempLocalContent, tempLocal, Charsets.UTF_8);
+        
+        localhost.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath());
+
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
+        app.start(ImmutableList.of(localhost));
+
+        // First confirm that even if createParentDir==false that it still gets created!
+        try {
+            entity.getDriver().copyResource(tempLocal.toURI().toString(), tempDest.getAbsolutePath(), false);
+            assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent));
+        } finally {
+            Os.deleteRecursively(tempDataDirSub);
+        }
+
+        // Copy to absolute path
+        try {
+            entity.getDriver().copyResource(tempLocal.toURI().toString(), tempDest.getAbsolutePath(), true);
+            assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent));
+        } finally {
+            Os.deleteRecursively(tempDataDirSub);
+        }
+    }
+
+    @Test(groups="Integration")
+    public void testPreAndPostLaunchCommands() throws IOException {
+        File tempFile = new File(tempDataDir, "tempFile.txt");
+        localhost.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath());
+        app.createAndManageChild(EntitySpec.create(VanillaSoftwareProcess.class)
+                .configure(VanillaSoftwareProcess.CHECK_RUNNING_COMMAND, "")
+                .configure(SoftwareProcess.PRE_LAUNCH_COMMAND, String.format("echo inPreLaunch >> %s", tempFile.getAbsoluteFile()))
+                .configure(VanillaSoftwareProcess.LAUNCH_COMMAND, String.format("echo inLaunch >> %s", tempFile.getAbsoluteFile()))
+                .configure(SoftwareProcess.POST_LAUNCH_COMMAND, String.format("echo inPostLaunch >> %s", tempFile.getAbsoluteFile())));
+        app.start(ImmutableList.of(localhost));
+
+        List<String> output = Files.readLines(tempFile, Charsets.UTF_8);
+        assertEquals(output.size(), 3);
+        assertEquals(output.get(0), "inPreLaunch");
+        assertEquals(output.get(1), "inLaunch");
+        assertEquals(output.get(2), "inPostLaunch");
+        tempFile.delete();
+    }
+
+    @Test(groups="Integration")
+    public void testInstallResourcesCopy() throws IOException {
+        localhost.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath());
+        File template = new File(Os.tmp(), "template.yaml");
+        VanillaSoftwareProcess entity = app.createAndManageChild(EntitySpec.create(VanillaSoftwareProcess.class)
+                .configure(VanillaSoftwareProcess.CHECK_RUNNING_COMMAND, "")
+                .configure(SoftwareProcess.INSTALL_FILES, MutableMap.of("classpath://org/apache/brooklyn/entity/software/base/frogs.txt", "frogs.txt"))
+                .configure(SoftwareProcess.INSTALL_TEMPLATES, MutableMap.of("classpath://org/apache/brooklyn/entity/software/base/template.yaml", template.getAbsolutePath()))
+                .configure(VanillaSoftwareProcess.LAUNCH_COMMAND, "date"));
+        app.start(ImmutableList.of(localhost));
+
+        File frogs = new File(entity.getAttribute(SoftwareProcess.INSTALL_DIR), "frogs.txt");
+        try {
+            Assert.assertTrue(frogs.canRead(), "File not readable: " + frogs);
+            String output = Files.toString(frogs, Charsets.UTF_8);
+            Assert.assertTrue(output.contains("Brekekekex"), "File content not found: " + output);
+        } finally {
+            frogs.delete();
+        }
+
+        try {
+            String expectedHostname = BrooklynNetworkUtils.getLocalhostInetAddress().getHostName();
+            String expectedIp = BrooklynNetworkUtils.getLocalhostInetAddress().getHostAddress();
+            
+            Map<?,?> data = (Map) Iterables.getOnlyElement(Yamls.parseAll(Files.toString(template, Charsets.UTF_8)));
+            Assert.assertEquals(data.size(), 3);
+            Assert.assertEquals(data.get("entity.hostname"), expectedHostname);
+            Assert.assertEquals(data.get("entity.address"), expectedIp);
+            Assert.assertEquals(data.get("frogs"), Integer.valueOf(12));
+        } finally {
+            template.delete();
+        }
+    }
+
+    @Test(groups="Integration")
+    public void testRuntimeResourcesCopy() throws IOException {
+        localhost.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath());
+        File template = new File(Os.tmp(), "template.yaml");
+        VanillaSoftwareProcess entity = app.createAndManageChild(EntitySpec.create(VanillaSoftwareProcess.class)
+                .configure(VanillaSoftwareProcess.CHECK_RUNNING_COMMAND, "")
+                .configure(SoftwareProcess.RUNTIME_FILES, MutableMap.of("classpath://org/apache/brooklyn/entity/software/base/frogs.txt", "frogs.txt"))
+                .configure(SoftwareProcess.RUNTIME_TEMPLATES, MutableMap.of("classpath://org/apache/brooklyn/entity/software/base/template.yaml", template.getAbsolutePath()))
+                .configure(VanillaSoftwareProcess.LAUNCH_COMMAND, "date"));
+        app.start(ImmutableList.of(localhost));
+
+        File frogs = new File(entity.getAttribute(SoftwareProcess.RUN_DIR), "frogs.txt");
+        try {
+            Assert.assertTrue(frogs.canRead(), "File not readable: " + frogs);
+            String output = Files.toString(frogs, Charsets.UTF_8);
+            Assert.assertTrue(output.contains("Brekekekex"), "File content not found: " + output);
+        } finally {
+            frogs.delete();
+        }
+
+        try {
+            String expectedHostname = BrooklynNetworkUtils.getLocalhostInetAddress().getHostName();
+            String expectedIp = BrooklynNetworkUtils.getLocalhostInetAddress().getHostAddress();
+            
+            Map<?,?> data = (Map) Iterables.getOnlyElement(Yamls.parseAll(Files.toString(template, Charsets.UTF_8)));
+            Assert.assertEquals(data.size(), 3);
+            Assert.assertEquals(data.get("entity.hostname"), expectedHostname);
+            Assert.assertEquals(data.get("entity.address"), expectedIp);
+            Assert.assertEquals(data.get("frogs"), Integer.valueOf(12));
+        } finally {
+            template.delete();
+        }
+    }
+
+    @ImplementedBy(MyServiceImpl.class)
+    public interface MyService extends SoftwareProcess {
+        public SimulatedDriver getDriver();
+    }
+    
+    public static class MyServiceImpl extends SoftwareProcessImpl implements MyService {
+        public MyServiceImpl() {
+        }
+
+        @Override
+        public Class<?> getDriverInterface() {
+            return SimulatedDriver.class;
+        }
+        
+        @Override
+        public SimulatedDriver getDriver() {
+            return (SimulatedDriver) super.getDriver();
+        }
+    }
+
+    public static class SimulatedDriver extends AbstractSoftwareProcessSshDriver {
+        public List<String> events = new ArrayList<String>();
+        private volatile boolean launched = false;
+        
+        public SimulatedDriver(EntityLocal entity, SshMachineLocation machine) {
+            super(entity, machine);
+        }
+
+        @Override
+        public void install() {
+            events.add("install");
+            newScript(INSTALLING)
+                    .failOnNonZeroResultCode()
+                    .body.append("touch myfile")
+                    .execute();
+        }
+        
+        @Override
+        public void customize() {
+            events.add("customize");
+        }
+    
+        @Override
+        public void launch() {
+            events.add("launch");
+            launched = true;
+            entity.setAttribute(Startable.SERVICE_UP, true);
+        }
+        
+        @Override
+        public boolean isRunning() {
+            return launched;
+        }
+    
+        @Override
+        public void stop() {
+            events.add("stop");
+            launched = false;
+            entity.setAttribute(Startable.SERVICE_UP, false);
+        }
+    
+        @Override
+        public void kill() {
+            events.add("kill");
+            launched = false;
+            entity.setAttribute(Startable.SERVICE_UP, false);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessSubclassTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessSubclassTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessSubclassTest.java
new file mode 100644
index 0000000..338b1f3
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessSubclassTest.java
@@ -0,0 +1,169 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import static org.testng.Assert.assertEquals;
+
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.effector.core.EffectorAndBody;
+import org.apache.brooklyn.effector.core.MethodEffector;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcessImpl;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+
+
+public class SoftwareProcessSubclassTest extends BrooklynAppUnitTestSupport {
+
+//  NB: These tests don't actually require ssh to localhost -- only that 'localhost' resolves.
+
+    @SuppressWarnings("unused")
+    private static final Logger LOG = LoggerFactory.getLogger(SoftwareProcessSubclassTest.class);
+
+    @ImplementedBy(SubSoftwareProcessImpl.class)
+    public static interface SubSoftwareProcess extends EmptySoftwareProcess {
+        public List<String> getCallHistory();
+        public void triggerStopOutsideOfEffector();
+        public void customRestart();
+    }
+    
+    public static class SubSoftwareProcessImpl extends EmptySoftwareProcessImpl implements SubSoftwareProcess {
+        
+        protected List<String> callHistory = Collections.synchronizedList(Lists.<String>newArrayList());
+
+        @Override
+        public void init() {
+            super.init();
+            getMutableEntityType().addEffector(new EffectorAndBody<Void>(SoftwareProcess.RESTART, new MethodEffector<Void>(SubSoftwareProcess.class, "customRestart").getBody()));
+        }
+        
+        @Override
+        public List<String> getCallHistory() {
+            return callHistory;
+        }
+
+        @Override
+        public void preStart() {
+            callHistory.add("doStart");
+            super.preStart();
+        }
+        
+        @Override
+        public void preStop() {
+            callHistory.add("doStop");
+            super.preStop();
+        }
+        
+        @Override
+        public void customRestart() {
+            callHistory.add("doRestart");
+        }
+        
+        @Override
+        public void triggerStopOutsideOfEffector() {
+            stop();
+        }
+        
+    }
+    
+    private Location loc;
+    private List<Location> locs;
+    private SubSoftwareProcess entity;
+    
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        loc = mgmt.getLocationRegistry().resolve("localhost");
+        locs = ImmutableList.of(loc);
+        entity = app.createAndManageChild(EntitySpec.create(SubSoftwareProcess.class));
+    }
+
+    @Test
+    public void testStartCalledViaMethod() throws Exception {
+        entity.start(locs);
+        
+        assertCallHistory(ImmutableList.of("doStart"));
+    }
+
+    @Test
+    public void testStopCalledViaMethod() throws Exception {
+        app.start(locs);
+        entity.stop();
+        
+        assertCallHistory(ImmutableList.of("doStart", "doStop"));
+    }
+
+    @Test
+    public void testRestartCalledViaMethod() throws Exception {
+        app.start(locs);
+        entity.restart();
+        
+        assertCallHistory(ImmutableList.of("doStart", "doRestart"));
+    }
+    
+    @Test
+    public void testStopCalledWithoutEffector() throws Exception {
+        app.start(locs);
+        entity.triggerStopOutsideOfEffector();
+        
+        assertCallHistory(ImmutableList.of("doStart", "doStop"));
+    }
+
+    @Test
+    public void testStartCalledViaInvokeEffector() throws Exception {
+        entity.invoke(SubSoftwareProcess.START, ImmutableMap.<String,Object>of("locations", locs)).get();
+        
+        assertCallHistory(ImmutableList.of("doStart"));
+    }
+
+    @Test
+    public void testStopCalledViaInvokeEffector() throws Exception {
+        app.start(locs);
+        entity.invoke(SubSoftwareProcess.STOP, ImmutableMap.<String,Object>of()).get();
+        
+        assertCallHistory(ImmutableList.of("doStart", "doStop"));
+    }
+
+    @Test
+    public void testRestartCalledViaInvokeEffector() throws Exception {
+        app.start(locs);
+        entity.invoke(SubSoftwareProcess.RESTART, ImmutableMap.<String,Object>of()).get();
+        
+        assertCallHistory(ImmutableList.of("doStart", "doRestart"));
+    }
+    
+    private void assertCallHistory(Iterable<String> expected) {
+        List<String> actual = entity.getCallHistory();
+        assertEquals(actual, ImmutableList.copyOf(expected), "actual="+actual);
+    }
+}


[18/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshCommandEffector.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshCommandEffector.java b/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshCommandEffector.java
new file mode 100644
index 0000000..671348b
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshCommandEffector.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.ssh;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.api.effector.ParameterType;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.effector.core.AddEffector;
+import org.apache.brooklyn.effector.core.EffectorBody;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.effector.core.Effectors.EffectorBuilder;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks.SshEffectorTaskFactory;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.text.Strings;
+
+import com.google.common.base.Preconditions;
+
+public final class SshCommandEffector extends AddEffector {
+    
+    public static final ConfigKey<String> EFFECTOR_COMMAND = ConfigKeys.newStringConfigKey("command");
+    public static final ConfigKey<String> EFFECTOR_EXECUTION_DIR = SshCommandSensor.SENSOR_EXECUTION_DIR;
+    
+    public SshCommandEffector(ConfigBag params) {
+        super(newEffectorBuilder(params).build());
+    }
+    
+    public SshCommandEffector(Map<String,String> params) {
+        this(ConfigBag.newInstance(params));
+    }
+
+    public static EffectorBuilder<String> newEffectorBuilder(ConfigBag params) {
+        EffectorBuilder<String> eff = AddEffector.newEffectorBuilder(String.class, params);
+        eff.impl(new Body(eff.buildAbstract(), params));
+        return eff;
+    }
+
+
+    protected static class Body extends EffectorBody<String> {
+        private final Effector<?> effector;
+        private final String command;
+        private final String executionDir;
+
+        public Body(Effector<?> eff, ConfigBag params) {
+            this.effector = eff;
+            this.command = Preconditions.checkNotNull(params.get(EFFECTOR_COMMAND), "command must be supplied when defining this effector");
+            this.executionDir = params.get(EFFECTOR_EXECUTION_DIR);
+            // TODO could take a custom "env" aka effectorShellEnv
+        }
+
+        @Override
+        public String call(ConfigBag params) {
+            String command = this.command;
+            
+            command = SshCommandSensor.makeCommandExecutingInDirectory(command, executionDir, entity());
+            
+            MutableMap<String, String> env = MutableMap.of();
+            // first set all declared parameters, including default values
+            for (ParameterType<?> param: effector.getParameters()) {
+                env.addIfNotNull(param.getName(), Strings.toString( params.get(Effectors.asConfigKey(param)) ));
+            }
+            
+            // then set things from the entities defined shell environment, if applicable
+            env.putAll(Strings.toStringMap(entity().getConfig(SoftwareProcess.SHELL_ENVIRONMENT), ""));
+            
+            // if we wanted to resolve the surrounding environment in real time -- see above
+//            Map<String,Object> paramsResolved = (Map<String, Object>) Tasks.resolveDeepValue(effectorShellEnv, Map.class, entity().getExecutionContext());
+            
+            // finally set the parameters we've been passed; this will repeat declared parameters but to no harm,
+            // it may pick up additional values (could be a flag defining whether this is permitted or not)
+            env.putAll(Strings.toStringMap(params.getAllConfig()));
+            
+            SshEffectorTaskFactory<String> t = SshEffectorTasks.ssh(command)
+                .requiringZeroAndReturningStdout()
+                .summary("effector "+effector.getName())
+                .environmentVariables(env);
+            return queue(t).get();
+        }
+        
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshCommandSensor.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshCommandSensor.java b/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshCommandSensor.java
new file mode 100644
index 0000000..03c2cb6
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshCommandSensor.java
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.ssh;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.EntityInitializer;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.effector.core.AddSensor;
+import org.apache.brooklyn.entity.java.JmxAttributeSensor;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.sensor.core.HttpRequestSensor;
+import org.apache.brooklyn.sensor.feed.ssh.SshFeed;
+import org.apache.brooklyn.sensor.feed.ssh.SshPollConfig;
+import org.apache.brooklyn.sensor.feed.ssh.SshValueFunctions;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.flags.TypeCoercions;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.text.Strings;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Function;
+import com.google.common.base.Functions;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Supplier;
+
+/** 
+ * Configurable {@link EntityInitializer} which adds an SSH sensor feed running the <code>command</code> supplied
+ * in order to populate the sensor with the indicated <code>name</code>. Note that the <code>targetType</code> is ignored,
+ * and always set to {@link String}.
+ *
+ * @see HttpRequestSensor
+ * @see JmxAttributeSensor
+ */
+@Beta
+public final class SshCommandSensor<T> extends AddSensor<T> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(SshCommandSensor.class);
+
+    public static final ConfigKey<String> SENSOR_COMMAND = ConfigKeys.newStringConfigKey("command", "SSH command to execute for sensor");
+    public static final ConfigKey<String> SENSOR_EXECUTION_DIR = ConfigKeys.newStringConfigKey("executionDir", "Directory where the command should run; "
+        + "if not supplied, executes in the entity's run dir (or home dir if no run dir is defined); "
+        + "use '~' to always execute in the home dir, or 'custom-feed/' to execute in a custom-feed dir relative to the run dir");
+
+    protected final String command;
+    protected final String executionDir;
+
+    public SshCommandSensor(final ConfigBag params) {
+        super(params);
+
+        // TODO create a supplier for the command string to support attribute embedding
+        command = Preconditions.checkNotNull(params.get(SENSOR_COMMAND), "command");
+        
+        executionDir = params.get(SENSOR_EXECUTION_DIR);
+    }
+
+    @Override
+    public void apply(final EntityLocal entity) {
+        super.apply(entity);
+
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Adding SSH sensor {} to {}", name, entity);
+        }
+
+        Supplier<Map<String,String>> envSupplier = new Supplier<Map<String,String>>() {
+            @Override
+            public Map<String, String> get() {
+                return MutableMap.copyOf(Strings.toStringMap(entity.getConfig(SoftwareProcess.SHELL_ENVIRONMENT), ""));
+            }
+        };
+
+        Supplier<String> commandSupplier = new Supplier<String>() {
+            @Override
+            public String get() {
+                return makeCommandExecutingInDirectory(command, executionDir, entity);
+            }
+        };
+
+        SshPollConfig<T> pollConfig = new SshPollConfig<T>(sensor)
+                .period(period)
+                .env(envSupplier)
+                .command(commandSupplier)
+                .checkSuccess(SshValueFunctions.exitStatusEquals(0))
+                .onFailureOrException(Functions.constant((T) null))
+                .onSuccess(Functions.compose(new Function<String, T>() {
+                        @Override
+                        public T apply(String input) {
+                            return TypeCoercions.coerce(input, getType(type));
+                        }}, SshValueFunctions.stdout()));
+
+        SshFeed.builder()
+                .entity(entity)
+                .onlyIfServiceUp()
+                .poll(pollConfig)
+                .build();
+    }
+
+    static String makeCommandExecutingInDirectory(String command, String executionDir, EntityLocal entity) {
+        String finalCommand = command;
+        String execDir = executionDir;
+        if (Strings.isBlank(execDir)) {
+            // default to run dir
+            execDir = entity.getAttribute(SoftwareProcess.RUN_DIR);
+            // if no run dir, default to home
+            if (Strings.isBlank(execDir)) {
+                execDir = "~";
+            }
+        } else if (!Os.isAbsolutish(execDir)) {
+            // relative paths taken wrt run dir
+            String runDir = entity.getAttribute(SoftwareProcess.RUN_DIR);
+            if (!Strings.isBlank(runDir)) {
+                execDir = Os.mergePaths(runDir, execDir);
+            }
+        }
+        if (!"~".equals(execDir)) {
+            finalCommand = "mkdir -p '"+execDir+"' && cd '"+execDir+"' && "+finalCommand;
+        }
+        return finalCommand;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasks.java b/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasks.java
new file mode 100644
index 0000000..4ea5ed5
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasks.java
@@ -0,0 +1,334 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.ssh;
+
+import java.util.List;
+import java.util.Map;
+
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.config.StringConfigMap;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.config.ConfigUtils;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
+import org.apache.brooklyn.effector.core.EffectorBody;
+import org.apache.brooklyn.effector.core.EffectorTasks;
+import org.apache.brooklyn.effector.core.EffectorTasks.EffectorTaskFactory;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.location.basic.LocationInternal;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.internal.ssh.SshTool;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.core.task.ssh.SshFetchTaskFactory;
+import org.apache.brooklyn.util.core.task.ssh.SshFetchTaskWrapper;
+import org.apache.brooklyn.util.core.task.ssh.SshPutTaskFactory;
+import org.apache.brooklyn.util.core.task.ssh.SshPutTaskWrapper;
+import org.apache.brooklyn.util.core.task.ssh.SshTasks;
+import org.apache.brooklyn.util.core.task.ssh.internal.AbstractSshExecTaskFactory;
+import org.apache.brooklyn.util.core.task.ssh.internal.PlainSshExecTaskFactory;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskFactory;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.apache.brooklyn.util.ssh.BashCommands;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Function;
+import com.google.common.collect.Maps;
+
+/**
+ * Conveniences for generating {@link Task} instances to perform SSH activities.
+ * <p>
+ * If the {@link SshMachineLocation machine} is not specified directly it
+ * will be inferred from the {@link Entity} context of either the {@link Effector}
+ * or the current {@link Task}.
+ * 
+ * @see SshTasks
+ * @since 0.6.0
+ */
+@Beta
+public class SshEffectorTasks {
+
+    private static final Logger log = LoggerFactory.getLogger(SshEffectorTasks.class);
+    
+    public static final ConfigKey<Boolean> IGNORE_ENTITY_SSH_FLAGS = ConfigKeys.newBooleanConfigKey("ignoreEntitySshFlags",
+        "Whether to ignore any ssh flags (behaviour constraints) set on the entity or location " +
+        "where this is running, using only flags explicitly specified", false);
+    
+    /** like {@link EffectorBody} but providing conveniences when in a {@link SoftwareProcess}
+     * (or other entity with a single machine location) */
+    public abstract static class SshEffectorBody<T> extends EffectorBody<T> {
+        
+        /** convenience for accessing the machine */
+        public SshMachineLocation machine() {
+            return EffectorTasks.getSshMachine(entity());
+        }
+
+        /** convenience for generating an {@link PlainSshExecTaskFactory} which can be further customised if desired, and then (it must be explicitly) queued */
+        public ProcessTaskFactory<Integer> ssh(String ...commands) {
+            return new SshEffectorTaskFactory<Integer>(commands).machine(machine());
+        }
+    }
+
+    /** variant of {@link PlainSshExecTaskFactory} which fulfills the {@link EffectorTaskFactory} signature so can be used directly as an impl for an effector,
+     * also injects the machine automatically; can also be used outwith effector contexts, and machine is still injected if it is
+     * run from inside a task at an entity with a single SshMachineLocation */
+    public static class SshEffectorTaskFactory<RET> extends AbstractSshExecTaskFactory<SshEffectorTaskFactory<RET>,RET> implements EffectorTaskFactory<RET> {
+
+        public SshEffectorTaskFactory(String ...commands) {
+            super(commands);
+        }
+        public SshEffectorTaskFactory(SshMachineLocation machine, String ...commands) {
+            super(machine, commands);
+        }
+        @Override
+        public ProcessTaskWrapper<RET> newTask(Entity entity, Effector<RET> effector, ConfigBag parameters) {
+            markDirty();
+            if (summary==null) summary(effector.getName()+" (ssh)");
+            machine(EffectorTasks.getSshMachine(entity));
+            return newTask();
+        }
+        @Override
+        public synchronized ProcessTaskWrapper<RET> newTask() {
+            Entity entity = BrooklynTaskTags.getTargetOrContextEntity(Tasks.current());
+            if (machine==null) {
+                if (log.isDebugEnabled())
+                    log.debug("Using an ssh task not in an effector without any machine; will attempt to infer the machine: "+this);
+                if (entity!=null)
+                    machine(EffectorTasks.getSshMachine(entity));
+            }
+            applySshFlags(getConfig(), entity, getMachine());
+            return super.newTask();
+        }
+        
+        @Override
+        public <T2> SshEffectorTaskFactory<T2> returning(ScriptReturnType type) {
+            return (SshEffectorTaskFactory<T2>) super.<T2>returning(type);
+        }
+
+        @Override
+        public SshEffectorTaskFactory<Boolean> returningIsExitCodeZero() {
+            return (SshEffectorTaskFactory<Boolean>) super.returningIsExitCodeZero();
+        }
+
+        public SshEffectorTaskFactory<String> requiringZeroAndReturningStdout() {
+            return (SshEffectorTaskFactory<String>) super.requiringZeroAndReturningStdout();
+        }
+        
+        public <RET2> SshEffectorTaskFactory<RET2> returning(Function<ProcessTaskWrapper<?>, RET2> resultTransformation) {
+            return (SshEffectorTaskFactory<RET2>) super.returning(resultTransformation);
+        }
+    }
+    
+    public static class SshPutEffectorTaskFactory extends SshPutTaskFactory implements EffectorTaskFactory<Void> {
+        public SshPutEffectorTaskFactory(String remoteFile) {
+            super(remoteFile);
+        }
+        public SshPutEffectorTaskFactory(SshMachineLocation machine, String remoteFile) {
+            super(machine, remoteFile);
+        }
+        @Override
+        public SshPutTaskWrapper newTask(Entity entity, Effector<Void> effector, ConfigBag parameters) {
+            machine(EffectorTasks.getSshMachine(entity));
+            applySshFlags(getConfig(), entity, getMachine());
+            return super.newTask();
+        }
+        @Override
+        public SshPutTaskWrapper newTask() {
+            Entity entity = BrooklynTaskTags.getTargetOrContextEntity(Tasks.current());
+            if (machine==null) {
+                if (log.isDebugEnabled())
+                    log.debug("Using an ssh put task not in an effector without any machine; will attempt to infer the machine: "+this);
+                if (entity!=null) {
+                    machine(EffectorTasks.getSshMachine(entity));
+                }
+
+            }
+            applySshFlags(getConfig(), entity, getMachine());
+            return super.newTask();
+        }
+    }
+
+    public static class SshFetchEffectorTaskFactory extends SshFetchTaskFactory implements EffectorTaskFactory<String> {
+        public SshFetchEffectorTaskFactory(String remoteFile) {
+            super(remoteFile);
+        }
+        public SshFetchEffectorTaskFactory(SshMachineLocation machine, String remoteFile) {
+            super(machine, remoteFile);
+        }
+        @Override
+        public SshFetchTaskWrapper newTask(Entity entity, Effector<String> effector, ConfigBag parameters) {
+            machine(EffectorTasks.getSshMachine(entity));
+            applySshFlags(getConfig(), entity, getMachine());
+            return super.newTask();
+        }
+        @Override
+        public SshFetchTaskWrapper newTask() {
+            Entity entity = BrooklynTaskTags.getTargetOrContextEntity(Tasks.current());
+            if (machine==null) {
+                if (log.isDebugEnabled())
+                    log.debug("Using an ssh fetch task not in an effector without any machine; will attempt to infer the machine: "+this);
+                if (entity!=null)
+                    machine(EffectorTasks.getSshMachine(entity));
+            }
+            applySshFlags(getConfig(), entity, getMachine());
+            return super.newTask();
+        }
+    }
+
+    public static SshEffectorTaskFactory<Integer> ssh(String ...commands) {
+        return new SshEffectorTaskFactory<Integer>(commands);
+    }
+
+    public static SshEffectorTaskFactory<Integer> ssh(List<String> commands) {
+        return ssh(commands.toArray(new String[commands.size()]));
+    }
+
+    public static SshPutTaskFactory put(String remoteFile) {
+        return new SshPutEffectorTaskFactory(remoteFile);
+    }
+
+    public static SshFetchEffectorTaskFactory fetch(String remoteFile) {
+        return new SshFetchEffectorTaskFactory(remoteFile);
+    }
+
+    /** task which returns 0 if pid is running */
+    public static SshEffectorTaskFactory<Integer> codePidRunning(Integer pid) {
+        return ssh("ps -p "+pid).summary("PID "+pid+" is-running check (exit code)").allowingNonZeroExitCode();
+    }
+    
+    /** task which fails if the given PID is not running */
+    public static SshEffectorTaskFactory<?> requirePidRunning(Integer pid) {
+        return codePidRunning(pid).summary("PID "+pid+" is-running check (required)").requiringExitCodeZero("Process with PID "+pid+" is required to be running");
+    }
+
+    /** as {@link #codePidRunning(Integer)} but returning boolean */
+    public static SshEffectorTaskFactory<Boolean> isPidRunning(Integer pid) {
+        return codePidRunning(pid).summary("PID "+pid+" is-running check (boolean)").returning(new Function<ProcessTaskWrapper<?>, Boolean>() {
+            public Boolean apply(@Nullable ProcessTaskWrapper<?> input) { return Integer.valueOf(0).equals(input.getExitCode()); }
+        });
+    }
+
+
+    /** task which returns 0 if pid in the given file is running;
+     * method accepts wildcards so long as they match a single file on the remote end
+     * <p>
+     * returns 1 if no matching file, 
+     * 1 if matching file but no matching process,
+     * and 2 if 2+ matching files */
+    public static SshEffectorTaskFactory<Integer> codePidFromFileRunning(final String pidFile) {
+        return ssh(BashCommands.chain(
+                // this fails, but isn't an error
+                BashCommands.requireTest("-f "+pidFile, "The PID file "+pidFile+" does not exist."),
+                // this fails and logs an error picked up later
+                BashCommands.requireTest("`ls "+pidFile+" | wc -w` -eq 1", "ERROR: there are multiple matching PID files"),
+                // this fails and logs an error picked up later
+                BashCommands.require("cat "+pidFile, "ERROR: the PID file "+pidFile+" cannot be read (permissions?)."),
+                // finally check the process
+                "ps -p `cat "+pidFile+"`")).summary("PID file "+pidFile+" is-running check (exit code)")
+                .allowingNonZeroExitCode()
+                .addCompletionListener(new Function<ProcessTaskWrapper<?>,Void>() {
+                    public Void apply(ProcessTaskWrapper<?> input) {
+                        if (input.getStderr().contains("ERROR:"))
+                            throw new IllegalStateException("Invalid or inaccessible PID filespec: "+pidFile);
+                        return null;
+                    }
+                });
+    }
+    
+    /** task which fails if the pid in the given file is not running (or if there is no such PID file);
+     * method accepts wildcards so long as they match a single file on the remote end (fails if 0 or 2+ matching files) */
+    public static SshEffectorTaskFactory<?> requirePidFromFileRunning(String pidFile) {
+        return codePidFromFileRunning(pidFile)
+                .summary("PID file "+pidFile+" is-running check (required)")
+                .requiringExitCodeZero("Process with PID from file "+pidFile+" is required to be running");
+    }
+
+    /** as {@link #codePidFromFileRunning(String)} but returning boolean */
+    public static SshEffectorTaskFactory<Boolean> isPidFromFileRunning(String pidFile) {
+        return codePidFromFileRunning(pidFile).summary("PID file "+pidFile+" is-running check (boolean)").
+                returning(new Function<ProcessTaskWrapper<?>, Boolean>() {
+                    public Boolean apply(@Nullable ProcessTaskWrapper<?> input) { return ((Integer)0).equals(input.getExitCode()); }
+                });
+    }
+
+    /** extracts the values for the main brooklyn.ssh.config.* config keys (i.e. those declared in ConfigKeys) 
+     * as declared on the entity, and inserts them in a map using the unprefixed state, for ssh.
+     * <p>
+     * currently this is computed for each call, which may be wasteful, but it is reliable in the face of config changes.
+     * we could cache the Map.  note that we do _not_ cache (or even own) the SshTool; 
+     * the SshTool is created or re-used by the SshMachineLocation making use of these properties */
+    @Beta
+    public static Map<String, Object> getSshFlags(Entity entity, Location optionalLocation) {
+        ConfigBag allConfig = ConfigBag.newInstance();
+        
+        StringConfigMap globalConfig = ((EntityInternal)entity).getManagementContext().getConfig();
+        allConfig.putAll(globalConfig.getAllConfig());
+        
+        if (optionalLocation!=null)
+            allConfig.putAll(((LocationInternal)optionalLocation).config().getBag());
+        
+        allConfig.putAll(((EntityInternal)entity).getAllConfig());
+        
+        Map<String, Object> result = Maps.newLinkedHashMap();
+        for (String keyS : allConfig.getAllConfig().keySet()) {
+            if (keyS.startsWith(SshTool.BROOKLYN_CONFIG_KEY_PREFIX)) {
+                ConfigKey<?> key = ConfigKeys.newConfigKey(Object.class, keyS);
+                
+                Object val = allConfig.getStringKey(keyS);
+                
+                /*
+                 * NOV 2013 changing this to rely on config above being inserted in the right order,
+                 * so entity config will be preferred over location, and location over global.
+                 * If that is consistent then remove the lines below.
+                 * (We can also accept null entity and so combine with SshTasks.getSshFlags.)
+                 */
+                
+//                // have to use raw config to test whether the config is set
+//                Object val = ((EntityInternal)entity).getConfigMap().getRawConfig(key);
+//                if (val!=null) {
+//                    val = entity.getConfig(key);
+//                } else {
+//                    val = globalConfig.getRawConfig(key);
+//                    if (val!=null) val = globalConfig.getConfig(key);
+//                }
+//                if (val!=null) {
+                    result.put(ConfigUtils.unprefixedKey(SshTool.BROOKLYN_CONFIG_KEY_PREFIX, key).getName(), val);
+//                }
+            }
+        }
+        return result;
+    }
+
+    private static void applySshFlags(ConfigBag config, Entity entity, Location machine) {
+        if (entity!=null) {
+            if (!config.get(IGNORE_ENTITY_SSH_FLAGS)) {
+                config.putIfAbsent(getSshFlags(entity, machine));
+            }
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/sensor/winrm/WindowsPerformanceCounterSensors.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/sensor/winrm/WindowsPerformanceCounterSensors.java b/software/base/src/main/java/org/apache/brooklyn/sensor/winrm/WindowsPerformanceCounterSensors.java
new file mode 100644
index 0000000..5acdd1c
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/sensor/winrm/WindowsPerformanceCounterSensors.java
@@ -0,0 +1,73 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.winrm;
+
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.brooklyn.api.entity.EntityInitializer;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.sensor.feed.windows.WindowsPerformanceCounterFeed;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.text.Strings;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.reflect.TypeToken;
+
+public class WindowsPerformanceCounterSensors implements EntityInitializer {
+
+    private static final Logger LOG = LoggerFactory.getLogger(WindowsPerformanceCounterSensors.class);
+
+    public final static ConfigKey<Set<Map<String, String>>> PERFORMANCE_COUNTERS = ConfigKeys.newConfigKey(new TypeToken<Set<Map<String, String>>>(){}, "performance.counters");
+
+    protected final Set<Map<String, String>> sensors;
+
+    public WindowsPerformanceCounterSensors(ConfigBag params) {
+        sensors = params.get(PERFORMANCE_COUNTERS);
+    }
+
+    public WindowsPerformanceCounterSensors(Map<String, String> params) {
+        this(ConfigBag.newInstance(params));
+    }
+
+    @Override
+    public void apply(EntityLocal entity) {
+        WindowsPerformanceCounterFeed.Builder builder = WindowsPerformanceCounterFeed.builder()
+                .entity(entity);
+        for (Map<String, String> sensorConfig : sensors) {
+            String name = sensorConfig.get("name");
+            String sensorType = sensorConfig.get("sensorType");
+            Class<?> clazz;
+            try {
+                clazz = Strings.isNonEmpty(sensorType)
+                        ? ((EntityInternal)entity).getManagementContext().getCatalog().getRootClassLoader().loadClass(sensorType) 
+                        : String.class;
+            } catch (ClassNotFoundException e) {
+                throw new IllegalStateException("Could not load type "+sensorType+" for sensor "+name, e);
+            }
+            builder.addSensor(sensorConfig.get("counter"), Sensors.newSensor(clazz, name, sensorConfig.get("description")));
+        }
+        builder.build();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/resources/brooklyn/entity/brooklynnode/brooklyn-cluster.yaml
----------------------------------------------------------------------
diff --git a/software/base/src/main/resources/brooklyn/entity/brooklynnode/brooklyn-cluster.yaml b/software/base/src/main/resources/brooklyn/entity/brooklynnode/brooklyn-cluster.yaml
deleted file mode 100644
index cb32596..0000000
--- a/software/base/src/main/resources/brooklyn/entity/brooklynnode/brooklyn-cluster.yaml
+++ /dev/null
@@ -1,33 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#  http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied.  See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-name: Example Brooklyn Cluster
-
-services:
-- type: brooklyn.entity.brooklynnode.BrooklynCluster
-  initialSize: 2
-  memberSpec:
-    $brooklyn:entitySpec: 
-#      type: classpath://brooklyn/entity/brooklynnode/brooklyn-node-persisting-to-tmp.yaml
-      type: brooklyn.entity.brooklynnode.BrooklynNode
-      brooklyn.config:
-        # persistence location must be the same for all nodes; if anywhere other than localhost configure a shared obj store or nfs mount
-        brooklynnode.launch.parameters.extra: --persist auto --persistenceDir /tmp/brooklyn-persistence-example/
-
-# location: localhost

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/resources/brooklyn/entity/brooklynnode/brooklyn-node-persisting-to-tmp.yaml
----------------------------------------------------------------------
diff --git a/software/base/src/main/resources/brooklyn/entity/brooklynnode/brooklyn-node-persisting-to-tmp.yaml b/software/base/src/main/resources/brooklyn/entity/brooklynnode/brooklyn-node-persisting-to-tmp.yaml
deleted file mode 100644
index afb53e7..0000000
--- a/software/base/src/main/resources/brooklyn/entity/brooklynnode/brooklyn-node-persisting-to-tmp.yaml
+++ /dev/null
@@ -1,27 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#  http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied.  See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-name: Example Persisting Brooklyn Node
-
-services:
-- type: classpath://brooklyn/entity/brooklynnode/brooklyn-node.yaml
-  brooklyn.config:
-    brooklynnode.launch.parameters.extra: --persist auto --persistenceDir /tmp/brooklyn-persistence-example/
-
-location: localhost

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/resources/brooklyn/entity/brooklynnode/brooklyn-node.yaml
----------------------------------------------------------------------
diff --git a/software/base/src/main/resources/brooklyn/entity/brooklynnode/brooklyn-node.yaml b/software/base/src/main/resources/brooklyn/entity/brooklynnode/brooklyn-node.yaml
deleted file mode 100644
index db5b1c7..0000000
--- a/software/base/src/main/resources/brooklyn/entity/brooklynnode/brooklyn-node.yaml
+++ /dev/null
@@ -1,35 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#  http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied.  See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-name: Example Brooklyn Node
-
-services:
-- type: brooklyn.entity.brooklynnode.BrooklynNode
-
-  ## URL for uploading the brooklyn distro (retrieved locally and pushed to remote install location)
-  # brooklynnode.distro.uploadurl: file:///tmp/brooklyn-dist-<version>-dist.tar.gz
-
-  ## if deploying to anything other than localhost you must also configure login details, e.g.:
-  # managementUsername: admin
-  # managementPassword: p4ssw0rd
-  # brooklynLocalPropertiesContents: |
-  #   brooklyn.webconsole.security.users=admin
-  #   brooklyn.webconsole.security.user.admin.password=p4ssw0rd
-
-# location: localhost

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/resources/brooklyn/entity/service/service.sh
----------------------------------------------------------------------
diff --git a/software/base/src/main/resources/brooklyn/entity/service/service.sh b/software/base/src/main/resources/brooklyn/entity/service/service.sh
deleted file mode 100644
index 4a1b293..0000000
--- a/software/base/src/main/resources/brooklyn/entity/service/service.sh
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/usr/bin/env bash
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#  http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied.  See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-# chkconfig: - 80 20
-#
-### BEGIN INIT INFO
-# Provides:          ${service.name}
-# Required-Start:    $network $syslog
-# Required-Stop:     $network $syslog
-# Default-Start:
-# Default-Stop:
-# Short-Description: Brooklyn entity service
-# Description:       Service for Brooklyn managed entity
-### END INIT INFO
-
-case $1 in
- start)
-  touch ${service.log_path}/${service.name}.log
-  chown ${service.user} ${service.log_path}/${service.name}.log
-  sudo -u ${service.user} ${service.launch_script} >> ${service.log_path}/${service.name}.log 2>&1
-  ;;
-# stop)
-#  ;;
-# restart)
-#  ;;
-# status)
-#  ;;
-# reload)
-#  ;;
- *)
-#  echo "Usage: $0 {start|stop|restart|reload|status}"
-  echo "Usage: $0 {start}"
-  exit 2
-  ;;
-esac

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/resources/org/apache/brooklyn/entity/brooklynnode/brooklyn-cluster.yaml
----------------------------------------------------------------------
diff --git a/software/base/src/main/resources/org/apache/brooklyn/entity/brooklynnode/brooklyn-cluster.yaml b/software/base/src/main/resources/org/apache/brooklyn/entity/brooklynnode/brooklyn-cluster.yaml
new file mode 100644
index 0000000..97a7fc1
--- /dev/null
+++ b/software/base/src/main/resources/org/apache/brooklyn/entity/brooklynnode/brooklyn-cluster.yaml
@@ -0,0 +1,33 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#  http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+name: Example Brooklyn Cluster
+
+services:
+- type: org.apache.brooklyn.entity.brooklynnode.BrooklynCluster
+  initialSize: 2
+  memberSpec:
+    $brooklyn:entitySpec: 
+#      type: classpath://org/apache/brooklyn/entity/brooklynnode/brooklyn-node-persisting-to-tmp.yaml
+      type: org.apache.brooklyn.entity.brooklynnode.BrooklynNode
+      brooklyn.config:
+        # persistence location must be the same for all nodes; if anywhere other than localhost configure a shared obj store or nfs mount
+        brooklynnode.launch.parameters.extra: --persist auto --persistenceDir /tmp/brooklyn-persistence-example/
+
+# location: localhost

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/resources/org/apache/brooklyn/entity/brooklynnode/brooklyn-node-persisting-to-tmp.yaml
----------------------------------------------------------------------
diff --git a/software/base/src/main/resources/org/apache/brooklyn/entity/brooklynnode/brooklyn-node-persisting-to-tmp.yaml b/software/base/src/main/resources/org/apache/brooklyn/entity/brooklynnode/brooklyn-node-persisting-to-tmp.yaml
new file mode 100644
index 0000000..6081bd6
--- /dev/null
+++ b/software/base/src/main/resources/org/apache/brooklyn/entity/brooklynnode/brooklyn-node-persisting-to-tmp.yaml
@@ -0,0 +1,27 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#  http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+name: Example Persisting Brooklyn Node
+
+services:
+- type: classpath://org/apache/brooklyn/entity/brooklynnode/brooklyn-node.yaml
+  brooklyn.config:
+    brooklynnode.launch.parameters.extra: --persist auto --persistenceDir /tmp/brooklyn-persistence-example/
+
+location: localhost

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/resources/org/apache/brooklyn/entity/brooklynnode/brooklyn-node.yaml
----------------------------------------------------------------------
diff --git a/software/base/src/main/resources/org/apache/brooklyn/entity/brooklynnode/brooklyn-node.yaml b/software/base/src/main/resources/org/apache/brooklyn/entity/brooklynnode/brooklyn-node.yaml
new file mode 100644
index 0000000..6d813d1
--- /dev/null
+++ b/software/base/src/main/resources/org/apache/brooklyn/entity/brooklynnode/brooklyn-node.yaml
@@ -0,0 +1,35 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#  http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+name: Example Brooklyn Node
+
+services:
+- type: org.apache.brooklyn.entity.brooklynnode.BrooklynNode
+
+  ## URL for uploading the brooklyn distro (retrieved locally and pushed to remote install location)
+  # brooklynnode.distro.uploadurl: file:///tmp/brooklyn-dist-<version>-dist.tar.gz
+
+  ## if deploying to anything other than localhost you must also configure login details, e.g.:
+  # managementUsername: admin
+  # managementPassword: p4ssw0rd
+  # brooklynLocalPropertiesContents: |
+  #   brooklyn.webconsole.security.users=admin
+  #   brooklyn.webconsole.security.user.admin.password=p4ssw0rd
+
+# location: localhost

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/resources/org/apache/brooklyn/entity/system_service/service.sh
----------------------------------------------------------------------
diff --git a/software/base/src/main/resources/org/apache/brooklyn/entity/system_service/service.sh b/software/base/src/main/resources/org/apache/brooklyn/entity/system_service/service.sh
new file mode 100644
index 0000000..4a1b293
--- /dev/null
+++ b/software/base/src/main/resources/org/apache/brooklyn/entity/system_service/service.sh
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#  http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# chkconfig: - 80 20
+#
+### BEGIN INIT INFO
+# Provides:          ${service.name}
+# Required-Start:    $network $syslog
+# Required-Stop:     $network $syslog
+# Default-Start:
+# Default-Stop:
+# Short-Description: Brooklyn entity service
+# Description:       Service for Brooklyn managed entity
+### END INIT INFO
+
+case $1 in
+ start)
+  touch ${service.log_path}/${service.name}.log
+  chown ${service.user} ${service.log_path}/${service.name}.log
+  sudo -u ${service.user} ${service.launch_script} >> ${service.log_path}/${service.name}.log 2>&1
+  ;;
+# stop)
+#  ;;
+# restart)
+#  ;;
+# status)
+#  ;;
+# reload)
+#  ;;
+ *)
+#  echo "Usage: $0 {start|stop|restart|reload|status}"
+  echo "Usage: $0 {start}"
+  exit 2
+  ;;
+esac

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/AbstractEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/AbstractEc2LiveTest.java b/software/base/src/test/java/brooklyn/entity/AbstractEc2LiveTest.java
deleted file mode 100644
index ad10b00..0000000
--- a/software/base/src/test/java/brooklyn/entity/AbstractEc2LiveTest.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity;
-
-import java.util.Map;
-
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.location.jclouds.JcloudsLocation;
-import org.apache.brooklyn.location.jclouds.JcloudsLocationConfig;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-/**
- * Runs a test with many different distros and versions.
- */
-public abstract class AbstractEc2LiveTest extends BrooklynAppLiveTestSupport {
-    
-    // FIXME Currently have just focused on test_Debian_6; need to test the others as well!
-
-    // TODO No nice fedora VMs
-    
-    // TODO Instead of this sub-classing approach, we could use testng's "provides" mechanism
-    // to say what combo of provider/region/flags should be used. The problem with that is the
-    // IDE integration: one can't just select a single test to run.
-    
-    public static final String PROVIDER = "aws-ec2";
-    public static final String REGION_NAME = "us-east-1";
-    public static final String LOCATION_SPEC = PROVIDER + (REGION_NAME == null ? "" : ":" + REGION_NAME);
-    public static final String TINY_HARDWARE_ID = "t1.micro";
-    public static final String SMALL_HARDWARE_ID = "m1.small";
-    
-    protected BrooklynProperties brooklynProperties;
-    
-    protected Location jcloudsLocation;
-    
-    @BeforeMethod(alwaysRun=true)
-    @Override
-    public void setUp() throws Exception {
-        // Don't let any defaults from brooklyn.properties (except credentials) interfere with test
-        brooklynProperties = BrooklynProperties.Factory.newDefault();
-        brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-description-regex");
-        brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-name-regex");
-        brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-id");
-        brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".inboundPorts");
-        brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".hardware-id");
-
-        // Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can cause "stdin: is not a tty")
-        brooklynProperties.remove("brooklyn.ssh.config.scriptHeader");
-        
-        mgmt = new LocalManagementContextForTests(brooklynProperties);
-        
-        super.setUp();
-    }
-
-    // Image ids for Debian: https://wiki.debian.org/Cloud/AmazonEC2Image/Squeeze
-    @Test(groups = {"Live"})
-    public void test_Debian_6() throws Exception {
-        // release codename "squeeze"
-        runTest(ImmutableMap.of("imageId", "us-east-1/ami-5e12dc36", "loginUser", "admin", "hardwareId", SMALL_HARDWARE_ID));
-    }
-
-    @Test(groups = {"Live"})
-    public void test_Debian_7_2() throws Exception {
-        // release codename "wheezy"
-        runTest(ImmutableMap.of("imageId", "us-east-1/ami-5586a43c", "loginUser", "admin", "hardwareId", SMALL_HARDWARE_ID));
-    }
-
-    @Test(groups = {"Live"})
-    public void test_Ubuntu_10_0() throws Exception {
-        // Image: {id=us-east-1/ami-5e008437, providerId=ami-5e008437, name=RightImage_Ubuntu_10.04_x64_v5.8.8.3, location={scope=REGION, id=us-east-1, description=us-east-1, parent=aws-ec2, iso3166Codes=[US-VA]}, os={family=ubuntu, arch=paravirtual, version=10.04, description=rightscale-us-east/RightImage_Ubuntu_10.04_x64_v5.8.8.3.manifest.xml, is64Bit=true}, description=rightscale-us-east/RightImage_Ubuntu_10.04_x64_v5.8.8.3.manifest.xml, version=5.8.8.3, status=AVAILABLE[available], loginUser=root, userMetadata={owner=411009282317, rootDeviceType=instance-store, virtualizationType=paravirtual, hypervisor=xen}}
-        runTest(ImmutableMap.of("imageId", "us-east-1/ami-5e008437", "loginUser", "root", "hardwareId", SMALL_HARDWARE_ID));
-    }
-
-    @Test(groups = {"Live"})
-    public void test_Ubuntu_12_0() throws Exception {
-        // Image: {id=us-east-1/ami-d0f89fb9, providerId=ami-d0f89fb9, name=ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1, location={scope=REGION, id=us-east-1, description=us-east-1, parent=aws-ec2, iso3166Codes=[US-VA]}, os={family=ubuntu, arch=paravirtual, version=12.04, description=099720109477/ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1, is64Bit=true}, description=099720109477/ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1, version=20130411.1, status=AVAILABLE[available], loginUser=ubuntu, userMetadata={owner=099720109477, rootDeviceType=ebs, virtualizationType=paravirtual, hypervisor=xen}}
-        runTest(ImmutableMap.of("imageId", "us-east-1/ami-d0f89fb9", "loginUser", "ubuntu", "hardwareId", SMALL_HARDWARE_ID));
-    }
-
-    @Test(groups = {"Live"})
-    public void test_CentOS_6_3() throws Exception {
-        // TODO Should openIptables=true be the default?!
-        // Image: {id=us-east-1/ami-a96b01c0, providerId=ami-a96b01c0, name=CentOS-6.3-x86_64-GA-EBS-02-85586466-5b6c-4495-b580-14f72b4bcf51-ami-bb9af1d2.1, location={scope=REGION, id=us-east-1, description=us-east-1, parent=aws-ec2, iso3166Codes=[US-VA]}, os={family=centos, arch=paravirtual, version=6.3, description=aws-marketplace/CentOS-6.3-x86_64-GA-EBS-02-85586466-5b6c-4495-b580-14f72b4bcf51-ami-bb9af1d2.1, is64Bit=true}, description=CentOS-6.3-x86_64-GA-EBS-02 on EBS x86_64 20130527:1219, version=bb9af1d2.1, status=AVAILABLE[available], loginUser=root, userMetadata={owner=679593333241, rootDeviceType=ebs, virtualizationType=paravirtual, hypervisor=xen}})
-        runTest(ImmutableMap.of("imageId", "us-east-1/ami-a96b01c0", "hardwareId", SMALL_HARDWARE_ID, JcloudsLocation.OPEN_IPTABLES.getName(), true));
-    }
-
-    @Test(groups = {"Live"})
-    public void test_CentOS_5() throws Exception {
-        // Image: {id=us-east-1/ami-e4bffe8d, providerId=ami-e4bffe8d, name=RightImage_CentOS_5.9_x64_v12.11.4_EBS, location={scope=REGION, id=us-east-1, description=us-east-1, parent=aws-ec2, iso3166Codes=[US-VA]}, os={family=centos, arch=paravirtual, version=5.0, description=411009282317/RightImage_CentOS_5.9_x64_v12.11.4_EBS, is64Bit=true}, description=RightImage_CentOS_5.9_x64_v12.11.4_EBS, version=12.11.4_EBS, status=AVAILABLE[available], loginUser=root, userMetadata={owner=411009282317, rootDeviceType=ebs, virtualizationType=paravirtual, hypervisor=xen}}
-        runTest(ImmutableMap.of("imageId", "us-east-1/ami-e4bffe8d", "hardwareId", SMALL_HARDWARE_ID));
-    }
-
-    @Test(groups = {"Live"})
-    public void test_Red_Hat_Enterprise_Linux_6() throws Exception {
-        // Image: {id=us-east-1/ami-a35a33ca, providerId=ami-a35a33ca, name=RHEL-6.3_GA-x86_64-5-Hourly2, location={scope=REGION, id=us-east-1, description=us-east-1, parent=aws-ec2, iso3166Codes=[US-VA]}, os={family=rhel, arch=paravirtual, version=6.0, description=309956199498/RHEL-6.3_GA-x86_64-5-Hourly2, is64Bit=true}, description=309956199498/RHEL-6.3_GA-x86_64-5-Hourly2, version=Hourly2, status=AVAILABLE[available], loginUser=root, userMetadata={owner=309956199498, rootDeviceType=ebs, virtualizationType=paravirtual, hypervisor=xen}}
-        runTest(ImmutableMap.of("imageId", "us-east-1/ami-a35a33ca", "hardwareId", SMALL_HARDWARE_ID, JcloudsLocationConfig.OPEN_IPTABLES.getName(), "true"));
-    }
-    
-    @Test(groups = {"Live"})
-    public void test_Suse_11sp3() throws Exception {
-        // Image: {id=us-east-1/ami-c08fcba8, providerId=ami-c08fcba8, name=suse-sles-11-sp3-v20150127-pv-ssd-x86_64, location={scope=REGION, id=us-east-1, description=us-east-1, parent=aws-ec2, iso3166Codes=[US-VA]}, os={family=suse, arch=paravirtual, version=, description=amazon/suse-sles-11-sp3-v20150127-pv-ssd-x86_64, is64Bit=true}, description=SUSE Linux Enterprise Server 11 Service Pack 3 (PV, 64-bit, SSD-Backed), version=x86_64, status=AVAILABLE[available], loginUser=root, userMetadata={owner=013907871322, rootDeviceType=ebs, virtualizationType=paravirtual, hypervisor=xen}}
-        runTest(ImmutableMap.of("imageId", "us-east-1/ami-c08fcba8", "hardwareId", SMALL_HARDWARE_ID, "loginUser", "ec2-user"));//, JcloudsLocationConfig.OPEN_IPTABLES.getName(), "true"));
-    }
-    
-    protected void runTest(Map<String,?> flags) throws Exception {
-        Map<String,?> allFlags = MutableMap.<String,Object>builder()
-                .put("tags", ImmutableList.of(getClass().getName()))
-                .putAll(flags)
-                .build();
-        jcloudsLocation = mgmt.getLocationRegistry().resolve(LOCATION_SPEC, allFlags);
-
-        doTest(jcloudsLocation);
-    }
-    
-    protected abstract void doTest(Location loc) throws Exception;
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/AbstractGoogleComputeLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/AbstractGoogleComputeLiveTest.java b/software/base/src/test/java/brooklyn/entity/AbstractGoogleComputeLiveTest.java
deleted file mode 100644
index 0301e1a..0000000
--- a/software/base/src/test/java/brooklyn/entity/AbstractGoogleComputeLiveTest.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity;
-
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.base.CaseFormat;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-/**
- * Runs a test with many different distros and versions.
- */
-public abstract class AbstractGoogleComputeLiveTest {
-    
-    // TODO See todos in AbstractEc2LiveTest
-    
-    public static final String PROVIDER = "google-compute-engine";
-    public static final String REGION_NAME = null;//"us-central1";
-    public static final String LOCATION_SPEC = PROVIDER + (REGION_NAME == null ? "" : ":" + REGION_NAME);
-    public static final String STANDARD_HARDWARE_ID = "us-central1-b/n1-standard-1-d";
-    private static final int MAX_TAG_LENGTH = 63;
-
-    protected BrooklynProperties brooklynProperties;
-    protected ManagementContext ctx;
-    
-    protected TestApplication app;
-    protected Location jcloudsLocation;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        List<String> propsToRemove = ImmutableList.of("imageId", "imageDescriptionRegex", "imageNameRegex", "inboundPorts", "hardwareId", "minRam");
-        
-     // Don't let any defaults from brooklyn.properties (except credentials) interfere with test
-        brooklynProperties = BrooklynProperties.Factory.newDefault();
-        for (String propToRemove : propsToRemove) {
-            for (String propVariant : ImmutableList.of(propToRemove, CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propToRemove))) {
-                brooklynProperties.remove("brooklyn.locations.jclouds."+PROVIDER+"."+propVariant);
-                brooklynProperties.remove("brooklyn.locations."+propVariant);
-                brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+"."+propVariant);
-                brooklynProperties.remove("brooklyn.jclouds."+propVariant);
-            }
-        }
-
-        // Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can cause "stdin: is not a tty")
-        brooklynProperties.remove("brooklyn.ssh.config.scriptHeader");
-        
-        ctx = new LocalManagementContext(brooklynProperties);
-        app = ApplicationBuilder.newManagedApp(TestApplication.class, ctx);
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (app != null) Entities.destroyAllCatching(app.getManagementContext());
-    }
-
-    @Test(groups = {"Live"})
-    public void test_DefaultImage() throws Exception {
-        runTest(ImmutableMap.<String,String>of());
-    }
-
-    // most of these not available
-    
-//    @Test(groups = {"Live"})
-//    public void test_GCEL_10_04() throws Exception {
-//        // release codename "squeeze"
-//        runTest(ImmutableMap.of("imageId", "gcel-10-04-v20130325", "loginUser", "admin", "hardwareId", STANDARD_HARDWARE_ID));
-//    }
-//
-//    @Test(groups = {"Live"})
-//    public void test_GCEL_12_04() throws Exception {
-//        // release codename "squeeze"
-//        runTest(ImmutableMap.of("imageId", "gcel-12-04-v20130325", "loginUser", "admin", "hardwareId", STANDARD_HARDWARE_ID));
-//    }
-//
-//    @Test(groups = {"Live"})
-//    public void test_Ubuntu_10_04() throws Exception {
-//        // release codename "squeeze"
-//        runTest(ImmutableMap.of("imageId", "ubuntu-10-04-v20120912", "loginUser", "admin", "hardwareId", STANDARD_HARDWARE_ID));
-//    }
-//
-//    @Test(groups = {"Live"})
-//    public void test_Ubuntu_12_04() throws Exception {
-//        // release codename "squeeze"
-//        runTest(ImmutableMap.of("imageId", "ubuntu-10-04-v20120912", "loginUser", "admin", "hardwareId", STANDARD_HARDWARE_ID));
-//    }
-//
-//    @Test(groups = {"Live"})
-//    public void test_CentOS_6() throws Exception {
-//        runTest(ImmutableMap.of("imageId", "centos-6-v20130325", "hardwareId", STANDARD_HARDWARE_ID));
-//    }
-
-    protected void runTest(Map<String,?> flags) throws Exception {
-        String tag = getClass().getSimpleName().toLowerCase();
-        int length = tag.length();
-        if (length > MAX_TAG_LENGTH)
-            tag = tag.substring(length - MAX_TAG_LENGTH, length);
-        Map<String,?> allFlags = MutableMap.<String,Object>builder()
-                .put("tags", ImmutableList.of(tag))
-                .putAll(flags)
-                .build();
-        jcloudsLocation = ctx.getLocationRegistry().resolve(LOCATION_SPEC, allFlags);
-
-        doTest(jcloudsLocation);
-    }
-
-    protected abstract void doTest(Location loc) throws Exception;
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/AbstractSoftlayerLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/AbstractSoftlayerLiveTest.java b/software/base/src/test/java/brooklyn/entity/AbstractSoftlayerLiveTest.java
deleted file mode 100644
index 58c3260..0000000
--- a/software/base/src/test/java/brooklyn/entity/AbstractSoftlayerLiveTest.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity;
-
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.text.StringShortener;
-import org.apache.brooklyn.util.text.Strings;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.base.CaseFormat;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-/**
- * Runs a test with many different distros and versions.
- */
-public abstract class AbstractSoftlayerLiveTest {
-    
-    public static final String PROVIDER = "softlayer";
-    public static final int MAX_TAG_LENGTH = 20;
-    public static final int MAX_VM_NAME_LENGTH = 30;
-
-    protected BrooklynProperties brooklynProperties;
-    protected ManagementContext ctx;
-    
-    protected TestApplication app;
-    protected Location jcloudsLocation;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        List<String> propsToRemove = ImmutableList.of("imageId", "imageDescriptionRegex", "imageNameRegex", "inboundPorts", "hardwareId", "minRam");
-
-        // Don't let any defaults from brooklyn.properties (except credentials) interfere with test
-        brooklynProperties = BrooklynProperties.Factory.newDefault();
-        for (String propToRemove : propsToRemove) {
-            for (String propVariant : ImmutableList.of(propToRemove, CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propToRemove))) {
-                brooklynProperties.remove("brooklyn.locations.jclouds."+PROVIDER+"."+propVariant);
-                brooklynProperties.remove("brooklyn.locations."+propVariant);
-                brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+"."+propVariant);
-                brooklynProperties.remove("brooklyn.jclouds."+propVariant);
-            }
-        }
-
-        // Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can cause "stdin: is not a tty")
-        brooklynProperties.remove("brooklyn.ssh.config.scriptHeader");
-        
-        ctx = new LocalManagementContext(brooklynProperties);
-        app = ApplicationBuilder.newManagedApp(TestApplication.class, ctx);
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-    }
-
-    @Test(groups = {"Live"})
-    public void test_Default() throws Exception {
-        runTest(ImmutableMap.<String,Object>of());
-    }
-
-    @Test(groups = {"Live"})
-    public void test_Ubuntu_12_0_4() throws Exception {
-        // Image: {id=UBUNTU_12_64, providerId=UBUNTU_12_64, os={family=ubuntu, version=12.04, description=Ubuntu / Ubuntu / 12.04.0-64 Minimal, is64Bit=true}, description=UBUNTU_12_64, status=AVAILABLE, loginUser=root}
-        runTest(ImmutableMap.<String,Object>of("imageId", "UBUNTU_12_64"));
-    }
-
-    @Test(groups = {"Live"})
-    public void test_Centos_6_0() throws Exception {
-      // Image: {id=CENTOS_6_64, providerId=CENTOS_6_64, os={family=centos, version=6.5, description=CentOS / CentOS / 6.5-64 LAMP for Bare Metal, is64Bit=true}, description=CENTOS_6_64, status=AVAILABLE, loginUser=root}
-        runTest(ImmutableMap.<String,Object>of("imageId", "CENTOS_6_64"));
-    }
-    
-    protected void runTest(Map<String,?> flags) throws Exception {
-        StringShortener shortener = Strings.shortener().separator("-");
-        shortener.canTruncate(getClass().getSimpleName(), MAX_TAG_LENGTH);
-        Map<String,?> allFlags = MutableMap.<String,Object>builder()
-                .put("tags", ImmutableList.of(shortener.getStringOfMaxLength(MAX_TAG_LENGTH)))
-                .put("vmNameMaxLength", MAX_VM_NAME_LENGTH)
-                .putAll(flags)
-                .build();
-        jcloudsLocation = ctx.getLocationRegistry().resolve(PROVIDER, allFlags);
-
-        doTest(jcloudsLocation);
-    }
-    
-    protected abstract void doTest(Location loc) throws Exception;
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/AbstractSoftwareProcessRestartIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/AbstractSoftwareProcessRestartIntegrationTest.java b/software/base/src/test/java/brooklyn/entity/basic/AbstractSoftwareProcessRestartIntegrationTest.java
deleted file mode 100644
index cb610d7..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/AbstractSoftwareProcessRestartIntegrationTest.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.collections.CollectionFunctionals;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess.RestartSoftwareParameters;
-import brooklyn.entity.basic.SoftwareProcess.StopSoftwareParameters;
-
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-/**
- * Tests restart of the software *process* (as opposed to the VM).
- */
-public abstract class AbstractSoftwareProcessRestartIntegrationTest extends BrooklynAppLiveTestSupport {
-    
-    // TODO Remove duplication from TomcatServerRestartIntegrationTest and MySqlRestartIntegrationTest
-    
-    @SuppressWarnings("unused")
-    private static final Logger LOG = LoggerFactory.getLogger(AbstractSoftwareProcessRestartIntegrationTest.class);
-
-    protected abstract EntitySpec<? extends SoftwareProcess> newEntitySpec();
-    
-    @Test(groups="Integration")
-    public void testStopProcessAndRestart() throws Exception {
-        runStopProcessAndRestart(
-                SoftwareProcess.RESTART, 
-                ImmutableMap.of(RestartSoftwareParameters.RESTART_MACHINE.getName(), RestartSoftwareParameters.RestartMachineMode.FALSE));
-    }
-    
-    @Test(groups="Integration")
-    public void testStopProcessAndStart() throws Exception {
-        runStopProcessAndRestart(
-                SoftwareProcess.START, 
-                ImmutableMap.of("locations", ImmutableList.of()));
-    }
-    
-    protected void runStopProcessAndRestart(Effector<?> restartEffector, Map<String, ?> args) throws Exception {
-        LocalhostMachineProvisioningLocation loc = app.newLocalhostProvisioningLocation();
-        SoftwareProcess entity = app.createAndManageChild(newEntitySpec());
-        
-        // Start the app
-        app.start(ImmutableList.of(loc));
-        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_UP, true);
-        EntityTestUtils.assertAttributeEqualsEventually(app, SoftwareProcess.SERVICE_UP, true);
-
-        // Stop the process
-        Entities.invokeEffector(app, entity, SoftwareProcess.STOP, ImmutableMap.of(
-                StopSoftwareParameters.STOP_MACHINE_MODE.getName(), StopSoftwareParameters.StopMode.NEVER))
-                .get();
-        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_UP, false);
-        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_STATE_ACTUAL, Lifecycle.STOPPED);
-        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, false);
-        EntityTestUtils.assertAttributeEventually(entity, ServiceStateLogic.SERVICE_NOT_UP_INDICATORS, CollectionFunctionals.<String>mapSizeEquals(1));
-        
-        // Restart the process
-        Entities.invokeEffector(app, entity, restartEffector, args).get();
-        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_UP, true);
-        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
-        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, true);
-        EntityTestUtils.assertAttributeEqualsEventually(entity, ServiceStateLogic.SERVICE_NOT_UP_INDICATORS, ImmutableMap.<String, Object>of());
-
-        EntityTestUtils.assertAttributeEqualsEventually(app, SoftwareProcess.SERVICE_UP, true);
-        EntityTestUtils.assertAttributeEqualsEventually(app, SoftwareProcess.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/DoNothingSoftwareProcess.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/DoNothingSoftwareProcess.java b/software/base/src/test/java/brooklyn/entity/basic/DoNothingSoftwareProcess.java
deleted file mode 100644
index d0ddf38..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/DoNothingSoftwareProcess.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-
-@ImplementedBy(DoNothingSoftwareProcessImpl.class)
-public interface DoNothingSoftwareProcess extends SoftwareProcess {
-    
-    public static final ConfigKey<Boolean> SKIP_ON_BOX_BASE_DIR_RESOLUTION = ConfigKeys.newConfigKeyWithDefault(
-            BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION,
-            true);
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/DoNothingSoftwareProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/DoNothingSoftwareProcessDriver.java b/software/base/src/test/java/brooklyn/entity/basic/DoNothingSoftwareProcessDriver.java
deleted file mode 100644
index 3439f1f..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/DoNothingSoftwareProcessDriver.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-/**
- * Implements methods in {@link brooklyn.entity.basic.AbstractSoftwareProcessSshDriver}
- * such that no actions are performed.
- * <p>
- * {@link #isRunning()} returns true.
- */
-public class DoNothingSoftwareProcessDriver extends AbstractSoftwareProcessSshDriver {
-
-    public DoNothingSoftwareProcessDriver(EntityLocal entity, SshMachineLocation machine) {
-        super(entity, machine);
-    }
-
-    @Override
-    public boolean isRunning() {
-        return true;
-    }
-
-    @Override
-    public void copyPreInstallResources() {
-    }
-
-    @Override
-    public void copyInstallResources() {
-    }
-
-    @Override
-    public void copyRuntimeResources() {
-    }
-
-    @Override
-    public void install() {
-    }
-
-    @Override
-    public void customize() {
-    }
-
-    @Override
-    public void launch() {
-    }
-
-    @Override
-    public void stop() {
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/DoNothingSoftwareProcessImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/DoNothingSoftwareProcessImpl.java b/software/base/src/test/java/brooklyn/entity/basic/DoNothingSoftwareProcessImpl.java
deleted file mode 100644
index dc862fe..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/DoNothingSoftwareProcessImpl.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-
-public class DoNothingSoftwareProcessImpl extends SoftwareProcessImpl implements DoNothingSoftwareProcess {
-
-    @Override
-    public Class getDriverInterface() {
-        return DoNothingSoftwareProcessDriver.class;
-    }
-    
-    @Override
-    protected void connectSensors() {
-        super.connectSensors();
-        if (getAttribute(SERVICE_STATE_ACTUAL) == Lifecycle.STARTING) {
-            setAttribute(SERVICE_UP, true);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/SameServerEntityTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/SameServerEntityTest.java b/software/base/src/test/java/brooklyn/entity/basic/SameServerEntityTest.java
deleted file mode 100644
index 3b2838a..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/SameServerEntityTest.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertSame;
-import static org.testng.Assert.assertTrue;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.entity.core.Entities;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-
-public class SameServerEntityTest {
-
-    private LocalhostMachineProvisioningLocation loc;
-    private ManagementContext mgmt;
-    private TestApplication app;
-    private SameServerEntity entity;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() {
-        loc = new LocalhostMachineProvisioningLocation();
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        mgmt = app.getManagementContext();
-        entity = app.createAndManageChild(EntitySpec.create(SameServerEntity.class));
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() {
-        if (app != null) Entities.destroyAll(mgmt);
-    }
-    
-    @Test
-    public void testUsesSameMachineLocationForEachChild() throws Exception {
-        Entity child1 = entity.addChild(EntitySpec.create(TestEntity.class));
-        Entity child2 = entity.addChild(EntitySpec.create(TestEntity.class));
-        Entities.manage(child1);
-        Entities.manage(child2);
-        
-        app.start(ImmutableList.of(loc));
-        
-        Location child1Loc = Iterables.getOnlyElement(child1.getLocations());
-        Location child2Loc = Iterables.getOnlyElement(child2.getLocations());
-        
-        assertSame(child1Loc, child2Loc);
-        assertTrue(child1Loc instanceof LocalhostMachine, "loc="+child1Loc);
-        
-        assertEquals(ImmutableSet.of(child1Loc), ImmutableSet.copyOf(loc.getInUse()));
-
-        app.stop();
-        
-        assertEquals(ImmutableSet.of(), ImmutableSet.copyOf(loc.getInUse()));
-    }
-}


[35/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/lifecycle/ScriptHelper.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/lifecycle/ScriptHelper.java b/software/base/src/main/java/brooklyn/entity/basic/lifecycle/ScriptHelper.java
deleted file mode 100644
index b722b1f..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/lifecycle/ScriptHelper.java
+++ /dev/null
@@ -1,436 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic.lifecycle;
-
-import static java.lang.String.format;
-import groovy.lang.Closure;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.LinkedHashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.mgmt.ExecutionContext;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.api.mgmt.TaskQueueingContext;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.util.GroovyJavaMethods;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.internal.ssh.ShellTool;
-import org.apache.brooklyn.util.core.mutex.WithMutexes;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.TaskBuilder;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.exceptions.RuntimeInterruptedException;
-import org.apache.brooklyn.util.stream.Streams;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.apache.brooklyn.util.text.Strings;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-
-public class ScriptHelper {
-
-    public static final Logger log = LoggerFactory.getLogger(ScriptHelper.class);
-
-    protected final NaiveScriptRunner runner;
-    public final String summary;
-
-    public final ScriptPart header = new ScriptPart(this);
-    public final ScriptPart body = new ScriptPart(this);
-    public final ScriptPart footer = new ScriptPart(this);
-    
-    @SuppressWarnings("rawtypes")
-    protected final Map flags = new LinkedHashMap();
-    protected Predicate<? super Integer> resultCodeCheck = Predicates.alwaysTrue();
-    protected Predicate<? super ScriptHelper> executionCheck = Predicates.alwaysTrue();
-    
-    protected boolean isTransient = false;
-    protected boolean isInessential = false;
-    protected boolean closeSshConnection = false;
-    protected boolean gatherOutput = false;
-    protected boolean noExtraOutput = false;
-    protected ByteArrayOutputStream stdout, stderr;
-    protected Task<Integer> task;
-
-    public ScriptHelper(NaiveScriptRunner runner, String summary) {
-        this.runner = runner;
-        this.summary = summary;
-    }
-
-    /**
-     * Takes a closure which accepts this ScriptHelper and returns true or false
-     * as to whether the script needs to run (or can throw error if desired)
-     */
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    public ScriptHelper executeIf(Closure c) {
-        Predicate<ScriptHelper> predicate = GroovyJavaMethods.predicateFromClosure(c);
-        return executeIf(predicate);
-    }
-
-    public ScriptHelper executeIf(Predicate<? super ScriptHelper> c) {
-        executionCheck = c;
-        return this;
-    }
-
-    public ScriptHelper skipIfBodyEmpty() {
-        Predicate<ScriptHelper> p = new Predicate<ScriptHelper>() {
-            @Override
-            public boolean apply(ScriptHelper input) {
-                return !input.body.isEmpty();
-            }
-        };
-
-        return executeIf(p);
-    }
-
-    public ScriptHelper failIfBodyEmpty() {
-        Predicate<ScriptHelper> p = new Predicate<ScriptHelper>() {
-            @Override
-            public boolean apply(ScriptHelper input) {
-                if (input.body.isEmpty()) {
-                    throw new IllegalStateException("body empty for " + summary);
-                }
-                return true;
-            }
-        };
-
-        return executeIf(p);
-    }
-
-    public ScriptHelper failOnNonZeroResultCode(boolean val) {
-        if (val) {
-            failOnNonZeroResultCode();
-        } else {
-            requireResultCode(Predicates.alwaysTrue());
-        }
-        return this;
-    }
-
-    public ScriptHelper failOnNonZeroResultCode() {
-        return updateTaskAndFailOnNonZeroResultCode();
-    }
-
-    public ScriptHelper failOnNonZeroResultCodeWithoutUpdatingTask() {
-        requireResultCode(Predicates.equalTo(0));
-        return this;
-    }
-    
-    public ScriptHelper updateTaskAndFailOnNonZeroResultCode() {
-        gatherOutput();
-        // a failure listener would be a cleaner way
-
-        resultCodeCheck = new Predicate<Integer>() {
-            @Override
-            public boolean apply(@Nullable Integer input) {
-                if (input==0) return true;
-
-                try {
-                    String notes = "";
-                    if (!getResultStderr().isEmpty())
-                        notes += "STDERR\n" + getResultStderr()+"\n";
-                    if (!getResultStdout().isEmpty())
-                        notes += "\n" + "STDOUT\n" + getResultStdout()+"\n";
-                    Tasks.setExtraStatusDetails(notes.trim());
-                } catch (Exception e) {
-                    log.warn("Unable to collect additional metadata on failure of "+summary+": "+e);
-                }
-
-                return false;
-            }
-        };
-        
-        return this;
-    }
-    
-    /**
-     * Convenience for error-checking the result.
-     * <p/>
-     * Takes closure which accepts bash exit code (integer),
-     * and returns false if it is invalid. Default is that this resultCodeCheck
-     * closure always returns true (and the exit code is made available to the
-     * caller if they care)
-     */
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    public ScriptHelper requireResultCode(Closure integerFilter) {
-        Predicate<Integer> objectPredicate = GroovyJavaMethods.predicateFromClosure(integerFilter);
-        return requireResultCode(objectPredicate);
-    }
-
-    public ScriptHelper requireResultCode(Predicate<? super Integer> integerFilter) {
-        resultCodeCheck = integerFilter;
-        return this;
-    }
-
-    protected Runnable mutexAcquire = new Runnable() {
-        public void run() {
-        }
-    };
-
-    protected Runnable mutexRelease = new Runnable() {
-        public void run() {
-        }
-    };
-
-    /**
-     * indicates that the script should acquire the given mutexId on the given mutexSupport
-     * and maintain it for the duration of script execution;
-     * typically used to prevent parallel scripts from conflicting in access to a resource
-     * (e.g. a folder, or a config file used by a process)
-     */
-    public ScriptHelper useMutex(final WithMutexes mutexSupport, final String mutexId, final String description) {
-        mutexAcquire = new Runnable() {
-            public void run() {
-                try {
-                    mutexSupport.acquireMutex(mutexId, description);
-                } catch (InterruptedException e) {
-                    throw new RuntimeInterruptedException(e);
-                }
-            }
-        };
-
-        mutexRelease = new Runnable() {
-            public void run() {
-                mutexSupport.releaseMutex(mutexId);
-            }
-        };
-
-        return this;
-    }
-
-    public ScriptHelper gatherOutput() {
-        return gatherOutput(true);
-    }
-    public ScriptHelper gatherOutput(boolean gather) {
-        gatherOutput = gather;
-        return this;
-    }
-
-    /**
-     * Indicate that no extra output should be appended to stdout.
-     * <p>
-     * By default Brooklyn appends a message like
-     * "<tt>Executed /tmp/brooklyn-20141010-164855950...sh, result 0</tt>"
-     * to script output.
-     */
-    public ScriptHelper noExtraOutput() {
-        return noExtraOutput(true);
-    }
-
-    /**
-     * @see #noExtraOutput()
-     */
-    private ScriptHelper noExtraOutput(boolean output) {
-        this.noExtraOutput = output;
-        return this;
-    }
-
-    /** The connection should be closed and disconnected once the commands have executed. */
-    public ScriptHelper closeSshConnection() {
-        closeSshConnection = true;
-        return this;
-    }
-    
-    /** Unique ID for the command execution; ensures new SSH connection from the pool. */
-    public ScriptHelper uniqueSshConnection() {
-        setFlag(SshMachineLocation.UNIQUE_ID, Identifiers.makeRandomBase64Id(32));
-        return this;
-    }
-    
-    /** indicates explicitly that the task can be safely forgotten about after it runs; useful for things like
-     * check_running which run repeatedly */
-    public void setTransient() {
-        isTransient = true;
-    }
-    
-    public void setInessential() {
-        isInessential = true;
-    }
-
-    public ScriptHelper inessential() {
-        isInessential = true;
-        return this;
-    }
-
-    /** creates a task which will execute this script; note this can only be run once per instance of this class */
-    public synchronized Task<Integer> newTask() {
-        if (task!=null) throw new IllegalStateException("task can only be generated once");
-        TaskBuilder<Integer> tb = Tasks.<Integer>builder().name("ssh: "+summary).body(
-                new Callable<Integer>() {
-                    public Integer call() throws Exception {
-                        return executeInternal();
-                    }
-                });
-        
-        try {
-            ByteArrayOutputStream stdin = new ByteArrayOutputStream();
-            for (String line: getLines()) {
-                stdin.write(line.getBytes());
-                stdin.write("\n".getBytes());
-            }
-            tb.tag(BrooklynTaskTags.tagForStreamSoft(BrooklynTaskTags.STREAM_STDIN, stdin));
-        } catch (IOException e) {
-            log.warn("Error registering stream "+BrooklynTaskTags.STREAM_STDIN+" on "+tb+": "+e, e);
-        }
-        
-        Map<?,?> env = (Map<?,?>) flags.get("env");
-        if (env!=null) {
-            // if not explicitly set, env will come from getShellEnv in AbstractSoftwareProcessSshDriver.execute,
-            // which will also update this tag appropriately
-            tb.tag(BrooklynTaskTags.tagForEnvStream(BrooklynTaskTags.STREAM_ENV, env));
-        }
-        
-        if (gatherOutput) {
-            stdout = new ByteArrayOutputStream();
-            tb.tag(BrooklynTaskTags.tagForStreamSoft(BrooklynTaskTags.STREAM_STDOUT, stdout));
-            stderr = new ByteArrayOutputStream();
-            tb.tag(BrooklynTaskTags.tagForStreamSoft(BrooklynTaskTags.STREAM_STDERR, stderr));
-        }
-        task = tb.build();
-        if (isTransient) BrooklynTaskTags.setTransient(task);
-        if (isInessential) BrooklynTaskTags.setInessential(task);
-        return task;
-    }
-    
-    /** returns the task, if it has been constructed, or null; use {@link #newTask()} to build 
-     * (if it is null and you need a task) */
-    public Task<Integer> peekTask() {
-        return task;
-    }
-
-    /** queues the task for execution if we are in a {@link TaskQueueingContext} (e.g. EffectorTaskFactory); 
-     * or if we aren't in a queueing context, it will submit the task (assuming there is an {@link ExecutionContext}
-     * _and_ block until completion, throwing on error */
-    @Beta
-    public Task<Integer> queue() {
-        return DynamicTasks.queueIfPossible(newTask()).orSubmitAndBlock().getTask();
-    }
-    
-    public int execute() {
-        if (DynamicTasks.getTaskQueuingContext()!=null) {
-            return queue().getUnchecked();
-        } else {
-            return executeInternal();
-        }
-    }
-
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    public int executeInternal() {
-        if (!executionCheck.apply(this)) {
-            return 0;
-        }
-
-        List<String> lines = getLines();
-        if (log.isTraceEnabled()) log.trace("executing: {} - {}", summary, lines);
-        
-        int result;
-        try {
-            mutexAcquire.run();
-            Map flags = getFlags();
-            if (closeSshConnection) {
-                flags.put("close", true);
-            }
-            if (gatherOutput) {
-                if (stdout==null) stdout = new ByteArrayOutputStream();
-                if (stderr==null) stderr = new ByteArrayOutputStream();
-                flags.put("out", stdout);
-                flags.put("err", stderr);
-            }
-            flags.put(ShellTool.PROP_NO_EXTRA_OUTPUT.getName(), noExtraOutput);
-            result = runner.execute(flags, lines, summary);
-        } catch (RuntimeInterruptedException e) {
-            throw logWithDetailsAndThrow(format("Execution failed, invocation error for %s: %s", summary, e.getMessage()), e);
-        } catch (Exception e) {
-            throw logWithDetailsAndThrow(format("Execution failed, invocation error for %s: %s", summary, e.getMessage()), e);
-        } finally {
-            mutexRelease.run();
-        }
-        if (log.isTraceEnabled()) log.trace("finished executing: {} - result code {}", summary, result);
-        
-        if (!resultCodeCheck.apply(result)) {
-            throw logWithDetailsAndThrow(format("Execution failed, invalid result %s for %s", result, summary), null);
-        }
-        return result;
-    }
-
-    protected RuntimeException logWithDetailsAndThrow(String message, Throwable optionalCause) {
-        log.warn(message+" (throwing)");
-        Streams.logStreamTail(log, "STDERR of problem in "+Tasks.current(), stderr, 1024);
-        Streams.logStreamTail(log, "STDOUT of problem in "+Tasks.current(), stdout, 1024);
-        Streams.logStreamTail(log, "STDIN of problem in "+Tasks.current(), Streams.byteArrayOfString(Strings.join(getLines(),"\n")), 4096);
-        if (optionalCause!=null) throw new IllegalStateException(message, optionalCause);
-        throw new IllegalStateException(message);
-    }
-
-    @SuppressWarnings("rawtypes")
-    public Map getFlags() {
-        return flags;
-    }
-    
-    @SuppressWarnings("unchecked")
-    public ScriptHelper setFlag(String flag, Object value) {
-        flags.put(flag, value);
-        return this;
-    }
-    
-    public <T> ScriptHelper setFlag(ConfigKey<T> flag, T value) {
-        return setFlag(flag.getName(), value);
-    }
-    
-    /** ensures the script runs with no environment variables; by default they will be inherited */
-    public ScriptHelper environmentVariablesReset() {
-        return environmentVariablesReset(MutableMap.of());
-    }
-    
-    /** overrides the default environment variables to use the given set; by default they will be inherited.
-     * TODO would be nice to have a way to add just a few, but there is no way currently to access the
-     * getShellEnvironment() from the driver which is what gets inherited (at execution time) */
-    public ScriptHelper environmentVariablesReset(Map<?,?> envVarsToSet) {
-        setFlag("env", envVarsToSet);
-        return this;
-    }
-
-    public List<String> getLines() {
-        List<String> result = new LinkedList<String>();
-        result.addAll(header.lines);
-        result.addAll(body.lines);
-        result.addAll(footer.lines);
-        return result;
-    }
-    
-    public String getResultStdout() {
-        if (stdout==null) throw new IllegalStateException("output not available on "+this+"; ensure gatherOutput(true) is set");
-        return stdout.toString();
-    }
-    public String getResultStderr() {
-        if (stderr==null) throw new IllegalStateException("output not available on "+this+"; ensure gatherOutput(true) is set");
-        return stderr.toString();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/lifecycle/ScriptPart.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/lifecycle/ScriptPart.java b/software/base/src/main/java/brooklyn/entity/basic/lifecycle/ScriptPart.java
deleted file mode 100644
index e14c526..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/lifecycle/ScriptPart.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic.lifecycle;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-
-public class ScriptPart {
-    protected ScriptHelper helper;
-    protected List<String> lines = new LinkedList<String>();
-
-    public ScriptPart(ScriptHelper helper) {
-        this.helper = helper;
-    }
-
-    public ScriptHelper append(CharSequence line) {
-        lines.add(line.toString());
-        return helper;
-    }
-
-    public ScriptHelper append(Collection<? extends CharSequence> lines) {
-        for (CharSequence line : lines) {
-            append(line);
-        }
-        return helper;
-    }
-
-    public ScriptHelper append(CharSequence... lines) {
-        return append(Arrays.asList(lines));
-    }
-
-    public ScriptHelper prepend(CharSequence line) {
-        lines.add(0, line.toString());
-        return helper;
-    }
-
-    public ScriptHelper prepend(Collection<? extends CharSequence> lines) {
-        List<CharSequence> reversedLines = new ArrayList<CharSequence>(lines);
-        Collections.reverse(reversedLines);
-        for (CharSequence line : reversedLines) {
-            prepend(line);
-        }
-        return helper;
-    }
-
-    public ScriptHelper prepend(CharSequence... lines) {
-        return prepend(Arrays.asList(lines));
-    }
-
-    public ScriptHelper reset(CharSequence line) {
-        return reset(Arrays.asList(line));
-    }
-
-    public ScriptHelper reset(List<? extends CharSequence> ll) {
-        lines.clear();
-        return append(ll);
-    }
-
-    public boolean isEmpty() {
-        return lines.isEmpty();
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynCluster.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynCluster.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynCluster.java
deleted file mode 100644
index 0123231..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynCluster.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.entity.group.DynamicCluster;
-import org.apache.brooklyn.sensor.core.Sensors;
-
-import brooklyn.entity.brooklynnode.effector.BrooklynNodeUpgradeEffectorBody;
-
-@ImplementedBy(BrooklynClusterImpl.class)
-public interface BrooklynCluster extends DynamicCluster {
-    
-    ConfigKey<EntitySpec<?>> MEMBER_SPEC = ConfigKeys.newConfigKeyWithDefault(DynamicCluster.MEMBER_SPEC, 
-            EntitySpec.create(BrooklynNode.class));
-    
-    AttributeSensor<BrooklynNode> MASTER_NODE = Sensors.newSensor(
-            BrooklynNode.class, "brooklyncluster.master", "Pointer to the child node with MASTER state in the cluster");
-
-    interface SelectMasterEffector {
-        ConfigKey<String> NEW_MASTER_ID = ConfigKeys.newStringConfigKey(
-                "brooklyncluster.new_master_id", "The ID of the node to become master", null);
-        Effector<Void> SELECT_MASTER = Effectors.effector(Void.class, "selectMaster")
-                .description("Select a new master in the cluster")
-                .parameter(NEW_MASTER_ID)
-                .buildAbstract();
-    }
-
-    Effector<Void> SELECT_MASTER = SelectMasterEffector.SELECT_MASTER;
-
-    interface UpgradeClusterEffector {
-        ConfigKey<String> DOWNLOAD_URL = BrooklynNode.DOWNLOAD_URL.getConfigKey();
-        ConfigKey<Map<String,Object>> EXTRA_CONFIG = BrooklynNodeUpgradeEffectorBody.EXTRA_CONFIG;
-
-        Effector<Void> UPGRADE_CLUSTER = Effectors.effector(Void.class, "upgradeCluster")
-                .description("Upgrade the cluster with new distribution version, "
-                    + "by provisioning new nodes with the new version, failing over, "
-                    + "and then deprovisioning the original nodes")
-                .parameter(BrooklynNode.SUGGESTED_VERSION)
-                .parameter(DOWNLOAD_URL)
-                .parameter(EXTRA_CONFIG)
-                .buildAbstract();
-    }
-
-    Effector<Void> UPGRADE_CLUSTER = UpgradeClusterEffector.UPGRADE_CLUSTER;
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynClusterImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynClusterImpl.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynClusterImpl.java
deleted file mode 100644
index 5209192..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynClusterImpl.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import java.util.Collection;
-import java.util.concurrent.Callable;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
-import org.apache.brooklyn.entity.core.EntityFunctions;
-import org.apache.brooklyn.entity.core.EntityPredicates;
-import org.apache.brooklyn.entity.group.DynamicClusterImpl;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic.ServiceProblemsLogic;
-import org.apache.brooklyn.sensor.enricher.Enrichers;
-import org.apache.brooklyn.sensor.feed.function.FunctionFeed;
-import org.apache.brooklyn.sensor.feed.function.FunctionPollConfig;
-import org.apache.brooklyn.util.time.Duration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.brooklynnode.effector.BrooklynClusterUpgradeEffectorBody;
-import brooklyn.entity.brooklynnode.effector.SelectMasterEffectorBody;
-
-import com.google.common.collect.FluentIterable;
-import com.google.common.collect.Iterables;
-
-public class BrooklynClusterImpl extends DynamicClusterImpl implements BrooklynCluster {
-
-    private static final String MSG_NO_MASTER = "No master node in cluster";
-    private static final String MSG_TOO_MANY_MASTERS = "Too many master nodes in cluster";
-
-    private static final Logger LOG = LoggerFactory.getLogger(BrooklynClusterImpl.class);
-
-    // TODO should we set a default MEMBER_SPEC ?  difficult though because we'd need to set a password
-
-    @Override
-    public void init() {
-        super.init();
-        getMutableEntityType().addEffector(SelectMasterEffectorBody.SELECT_MASTER);
-        getMutableEntityType().addEffector(BrooklynClusterUpgradeEffectorBody.UPGRADE_CLUSTER);
-
-        ServiceProblemsLogic.updateProblemsIndicator(this, MASTER_NODE, MSG_NO_MASTER);
-        addFeed(FunctionFeed.builder()
-                .entity(this)
-                .poll(new FunctionPollConfig<Object, BrooklynNode>(MASTER_NODE)
-                        .period(Duration.ONE_SECOND)
-                        .callable(new MasterChildFinder()))
-                .build());
-        
-        addEnricher( Enrichers.builder().transforming(MASTER_NODE)
-            .uniqueTag("master-node-web-uri")
-            .publishing(BrooklynNode.WEB_CONSOLE_URI)
-            .computing(EntityFunctions.attribute(BrooklynNode.WEB_CONSOLE_URI))
-            .build() );
-    }
-
-    private final class MasterChildFinder implements Callable<BrooklynNode> {
-        @Override
-        public BrooklynNode call() throws Exception {
-            return findMasterChild();
-        }
-    }
-
-    BrooklynNode findMasterChild() {
-        Collection<Entity> masters = FluentIterable.from(getMembers())
-                .filter(EntityPredicates.attributeEqualTo(BrooklynNode.MANAGEMENT_NODE_STATE, ManagementNodeState.MASTER))
-                .toList();
-
-        if (masters.size() == 0) {
-            ServiceProblemsLogic.updateProblemsIndicator(this, MASTER_NODE, MSG_NO_MASTER);
-            return null;
-            
-        } else if (masters.size() == 1) {
-            ServiceStateLogic.ServiceProblemsLogic.clearProblemsIndicator(this, MASTER_NODE);
-            return (BrooklynNode)Iterables.getOnlyElement(masters);
-            
-        } else if (masters.size() == 2) {
-            LOG.warn("Two masters detected, probably a handover just occured: " + masters);
-
-            //Don't clearProblemsIndicator - if there were no masters previously why have two now.
-            //But also don't set it. Probably hit a window where we have a new master
-            //its BrooklynNode picked it up, but the BrooklynNode
-            //for the old master hasn't refreshed its state yet.
-            //Just pick one of them, should sort itself out in next update.
-            
-            //TODO Do set such indicator if this continues for an extended period of time
-            
-            return (BrooklynNode)masters.iterator().next();
-            
-        } else {
-            ServiceProblemsLogic.updateProblemsIndicator(this, MASTER_NODE, MSG_TOO_MANY_MASTERS);
-            String msg = "Multiple (>=3) master nodes in cluster: " + masters;
-            LOG.error(msg);
-            throw new IllegalStateException(msg);
-            
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynEntityMirror.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynEntityMirror.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynEntityMirror.java
deleted file mode 100644
index c8b665f..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynEntityMirror.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.catalog.Catalog;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.util.time.Duration;
-
-import brooklyn.entity.brooklynnode.BrooklynNode;
-
-/** Provides an entity which can sit in one brooklyn domain and reflect the status of an entity 
- * via the REST API of another domain.
- * <p>
- * Note tests for this depend on a REST server so are in other projects; search for *Mirror*Test,
- * as well as *BrooklynNode*Test. */
-@Catalog(name="Brooklyn Entity Mirror", description="Provides an entity which can sit in one brooklyn "
-        + "domain and reflect the status of an entity via the REST API of another domain.")
-@ImplementedBy(BrooklynEntityMirrorImpl.class)
-public interface BrooklynEntityMirror extends Entity {
-
-    // caller must specify this:
-    public static final ConfigKey<String> MIRRORED_ENTITY_URL = ConfigKeys.newStringConfigKey("brooklyn.mirror.entity_url",
-        "URL for the entity in the remote Brooklyn mgmt endpoint");
-    
-    // caller may specify this for reference:
-    public static final ConfigKey<String> MIRRORED_ENTITY_ID = ConfigKeys.newStringConfigKey("brooklyn.mirror.entity_id",
-        "Brooklyn ID of the entity being mirrored");
-    
-    // must be specified if required (could be inherited if parent/config is available at init time, but it's not currently)
-    public static final ConfigKey<String> MANAGEMENT_USER = BrooklynNode.MANAGEMENT_USER;
-    public static final ConfigKey<String> MANAGEMENT_PASSWORD = BrooklynNode.MANAGEMENT_PASSWORD;
-    
-    public static final ConfigKey<Duration> POLL_PERIOD = ConfigKeys.newConfigKey(Duration.class, "brooklyn.mirror.poll_period",
-        "Frequency to poll for client sensors", Duration.FIVE_SECONDS);
-    
-    public static final AttributeSensor<String> MIRROR_STATUS = Sensors.newStringSensor("brooklyn.mirror.monitoring_status");
-    @SuppressWarnings("rawtypes")
-    public static final AttributeSensor<Map> MIRROR_SUMMARY = Sensors.newSensor(Map.class, "brooklyn.mirror.summary",
-        "The json map returned by the entity rest endpoint (ie the EntitySummary model)");
-    public static final AttributeSensor<String> MIRROR_CATALOG_ITEM_ID = Sensors.newStringSensor("brooklyn.mirror.catalog_item_id",
-        "The catalog item id of the mirrored entity in the remote brooklyn");
-    
-    public EntityHttpClient http();
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynEntityMirrorImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynEntityMirrorImpl.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynEntityMirrorImpl.java
deleted file mode 100644
index 72b9d01..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynEntityMirrorImpl.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import java.util.Collection;
-import java.util.Map;
-import java.util.concurrent.Callable;
-
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.effector.core.EffectorBody;
-import org.apache.brooklyn.entity.core.AbstractEntity;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.core.EntityDynamicType;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.sensor.feed.http.HttpFeed;
-import org.apache.brooklyn.sensor.feed.http.HttpPollConfig;
-import org.apache.brooklyn.util.collections.Jsonya;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.http.HttpToolResponse;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.http.HttpStatus;
-
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
-import com.google.common.net.MediaType;
-import com.google.gson.Gson;
-
-public class BrooklynEntityMirrorImpl extends AbstractEntity implements BrooklynEntityMirror {
-    @SuppressWarnings("rawtypes")
-    private class MirrorSummary implements Function<HttpToolResponse, Map> {
-        @Override
-        public Map apply(HttpToolResponse input) {
-            Map<?, ?> entitySummary = new Gson().fromJson(input.getContentAsString(), Map.class);
-            String catalogItemId = (String)entitySummary.get("catalogItemId");
-            setAttribute(MIRROR_CATALOG_ITEM_ID, catalogItemId);
-            return entitySummary;
-        }
-    }
-
-    private HttpFeed mirror;
-    
-
-    //Passively mirror entity's state
-    @Override
-    protected void initEnrichers() {}
-
-    @Override
-    public void init() {
-        super.init();
-        connectSensorsAsync();
-
-        //start spinning, could take some time before MIRRORED_ENTITY_URL is available for first time mirroring
-        setAttribute(Attributes.SERVICE_STATE_ACTUAL, Lifecycle.STARTING);
-    }
-
-    @Override
-    public void rebind() {
-        super.rebind();
-        connectSensorsAsync();
-    }
-
-    protected void connectSensorsAsync() {
-        Callable<Void> asyncTask = new Callable<Void>() {
-            @Override
-            public Void call() throws Exception {
-                //blocks until available (could be a task)
-                String mirroredEntityUrl = getConfig(MIRRORED_ENTITY_URL);
-                Preconditions.checkNotNull(mirroredEntityUrl, "Required config: "+MIRRORED_ENTITY_URL);
-
-                connectSensors(mirroredEntityUrl);
-                return null;
-            }
-        };
-
-        DynamicTasks.queueIfPossible(
-                Tasks.<Void>builder()
-                    .name("Start entity mirror feed")
-                    .body(asyncTask)
-                    .build())
-            .orSubmitAsync(this);
-    }
-
-    protected void connectSensors(String mirroredEntityUrl) {
-        Function<HttpToolResponse, Void> mirrorSensors = new Function<HttpToolResponse,Void>() {
-            @SuppressWarnings("rawtypes")
-            @Override
-            public Void apply(HttpToolResponse input) {
-                Map sensors = new Gson().fromJson(input.getContentAsString(), Map.class);
-                for (Object kv: sensors.entrySet())
-                    setAttribute(Sensors.newSensor(Object.class, ""+((Map.Entry)kv).getKey()), ((Map.Entry)kv).getValue());
-                setAttribute(MIRROR_STATUS, "normal");
-                return null;
-            }
-        };
-
-        final BrooklynEntityMirrorImpl self = this;
-        mirror = HttpFeed.builder().entity(this)
-            .baseUri(mirroredEntityUrl)
-            .credentialsIfNotNull(getConfig(BrooklynNode.MANAGEMENT_USER), getConfig(BrooklynNode.MANAGEMENT_PASSWORD))
-            .period(getConfig(POLL_PERIOD))
-            .poll(HttpPollConfig.forMultiple()
-                .suburl("/sensors/current-state")
-                .onSuccess(mirrorSensors)
-                .onFailureOrException(new Function<Object, Void>() {
-                    @Override
-                    public Void apply(Object input) {
-                        ServiceStateLogic.updateMapSensorEntry(self, Attributes.SERVICE_PROBLEMS, "mirror-feed", "error contacting service");
-                        if (input instanceof HttpToolResponse) {
-                            int responseCode = ((HttpToolResponse)input).getResponseCode();
-                            if (responseCode == HttpStatus.SC_NOT_FOUND) {
-                                //the remote entity no longer exists
-                                Entities.unmanage(self);
-                            }
-                        }
-                        return null;
-                    }
-                }))
-            .poll(HttpPollConfig.forSensor(MIRROR_SUMMARY).onSuccess(new MirrorSummary())).build();
-
-        populateEffectors();
-    }
-
-    private void populateEffectors() {
-        HttpToolResponse result = http().get("/effectors");
-        Collection<?> cfgEffectors = new Gson().fromJson(result.getContentAsString(), Collection.class);
-        Collection<Effector<String>> remoteEntityEffectors = RemoteEffectorBuilder.of(cfgEffectors);
-        EntityDynamicType mutableEntityType = getMutableEntityType();
-        for (Effector<String> eff : remoteEntityEffectors) {
-            //remote already started
-            if ("start".equals(eff.getName())) continue;
-            mutableEntityType.addEffector(eff);
-        }
-    }
-
-    protected void disconnectSensors() {
-        if (mirror != null) mirror.stop();
-    }
-
-    @Override
-    public void destroy() {
-        disconnectSensors();
-    }
-
-    @Override
-    public EntityHttpClient http() {
-        return new EntityHttpClientImpl(this, MIRRORED_ENTITY_URL);
-    }
-
-    public static class RemoteEffector<T> extends EffectorBody<T> {
-        public final String remoteEffectorName;
-        public final Function<HttpToolResponse, T> resultParser;
-        
-        /** creates an effector implementation which POSTs to a remote effector endpoint, optionally converting
-         * the byte[] response (if resultParser is null then null is returned) */
-        public RemoteEffector(String remoteEffectorName, @Nullable Function<HttpToolResponse,T> resultParser) {
-            this.remoteEffectorName = remoteEffectorName;
-            this.resultParser = resultParser;
-        }
-
-        @Override
-        public T call(ConfigBag parameters) {
-            MutableMap<String, String> headers = MutableMap.of(com.google.common.net.HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString());
-            byte[] httpBody = Jsonya.of(parameters.getAllConfig()).toString().getBytes();
-            String effectorUrl = Urls.mergePaths("effectors", Urls.encode(remoteEffectorName));
-            HttpToolResponse result = ((BrooklynEntityMirror)entity()).http().post(effectorUrl, headers, httpBody);
-            if (resultParser!=null) return resultParser.apply(result);
-            else return null;
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/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
deleted file mode 100644
index e232d4e..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java
+++ /dev/null
@@ -1,313 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import java.net.InetAddress;
-import java.net.URI;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.catalog.Catalog;
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.BrooklynVersion;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.config.MapConfigKey;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
-import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
-import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey.StringAttributeSensorAndConfigKey;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.apache.brooklyn.util.net.Networking;
-import org.apache.brooklyn.util.ssh.BashCommands;
-import org.apache.brooklyn.util.time.Duration;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.java.UsesJava;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Function;
-import com.google.common.base.Functions;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-import com.google.common.reflect.TypeToken;
-
-@Catalog(name="Brooklyn Node", description="Deploys a Brooklyn management server")
-@ImplementedBy(BrooklynNodeImpl.class)
-public interface BrooklynNode extends SoftwareProcess, UsesJava {
-
-    @SuppressWarnings("serial")
-    @SetFromFlag("copyToRundir")
-    public static final BasicAttributeSensorAndConfigKey<Map<String,String>> COPY_TO_RUNDIR = new BasicAttributeSensorAndConfigKey<Map<String,String>>(
-            new TypeToken<Map<String,String>>() {}, "brooklynnode.copytorundir", "URLs of resources to be copied across to the server, giving the path they are to be copied to", MutableMap.<String,String>of());
-    
-    @SetFromFlag("version")
-    public static final ConfigKey<String> SUGGESTED_VERSION = ConfigKeys.newConfigKeyWithDefault(BrooklynConfigKeys.SUGGESTED_VERSION, "0.8.0-SNAPSHOT"); // BROOKLYN_VERSION
-
-    @SetFromFlag("distroUploadUrl")
-    public static final ConfigKey<String> DISTRO_UPLOAD_URL = ConfigKeys.newStringConfigKey(
-            "brooklynnode.distro.uploadurl", "URL for uploading the brooklyn distro (retrieved locally and pushed to remote install location. Takes precedence over downloadUrl, if non-null)", null);
-
-    // Note that download URL only supports versions in org.apache.brooklyn, so not 0.6.0 and earlier 
-    // (which used maven group io.brooklyn). Aled thinks we can live with that.
-    @SetFromFlag("downloadUrl")
-    BasicAttributeSensorAndConfigKey<String> DOWNLOAD_URL = new StringAttributeSensorAndConfigKey(
-            SoftwareProcess.DOWNLOAD_URL,
-            "<#if version?contains(\"SNAPSHOT\")>"+
-                "https://repository.apache.org/service/local/artifact/maven/redirect?r=snapshots&g=org.apache.brooklyn&v=${version}&a=brooklyn-dist&c=dist&e=tar.gz" +
-            "<#else>"+
-                "http://search.maven.org/remotecontent?filepath=org/apache/brooklyn/brooklyn-dist/${version}/brooklyn-dist-${version}-dist.tar.gz"+
-            "</#if>");
-
-    @SetFromFlag("subpathInArchive")
-    ConfigKey<String> SUBPATH_IN_ARCHIVE = ConfigKeys.newStringConfigKey("brooklynnode.download.archive.subpath",
-        "Path to the main directory in the archive being supplied for installation; "
-        + "to use the root of an archive, specify '.'; "
-        + "default value taken based on download URL (e.g. 'name' for 'http://path/name.tgz' or 'http://path/name-dist.tgz') "
-        + "falling back to an appropriate value for brooklyn, "
-        + "e.g. 'brooklyn-"+BrooklynVersion.INSTANCE.getVersion()+"'", null);
-
-    @SetFromFlag("managementUser")
-    ConfigKey<String> MANAGEMENT_USER = ConfigKeys.newConfigKey("brooklynnode.managementUser",
-            "The user for logging into the brooklyn web-console (also used for health-checks)",
-            "admin");
-
-    @SetFromFlag("managementPassword")
-    ConfigKey<String> MANAGEMENT_PASSWORD =
-            ConfigKeys.newStringConfigKey("brooklynnode.managementPassword", "Password for MANAGEMENT_USER", null);
-
-    /** useful e.g. with {@link BashCommands#generateKeyInDotSshIdRsaIfNotThere() } */
-    @SetFromFlag("extraCustomizationScript")
-    ConfigKey<String> EXTRA_CUSTOMIZATION_SCRIPT = ConfigKeys.newStringConfigKey("brooklynnode.customization.extraScript",
-        "Optional additional script commands to run as part of customization; this might e.g. ensure id_rsa is set up",
-        null);
-
-    static enum ExistingFileBehaviour {
-        DO_NOT_USE, USE_EXISTING, OVERWRITE, FAIL
-    }
-    
-    @SetFromFlag("onExistingProperties")
-    ConfigKey<ExistingFileBehaviour> ON_EXISTING_PROPERTIES_FILE = ConfigKeys.newConfigKey(ExistingFileBehaviour.class,
-        "brooklynnode.properties.file.ifExists",
-        "What to do in the case where a global brooklyn.properties already exists", 
-        ExistingFileBehaviour.FAIL);
-
-    @SetFromFlag("launchCommand")
-    ConfigKey<String> LAUNCH_COMMAND = ConfigKeys.newStringConfigKey("brooklynnode.launch.command",
-        "Path to the script to launch Brooklyn / the app relative to the subpath in the archive, defaulting to 'bin/brooklyn'", 
-        "bin/brooklyn");
-
-    @SetFromFlag("launchParameters")
-    ConfigKey<String> EXTRA_LAUNCH_PARAMETERS = ConfigKeys.newStringConfigKey("brooklynnode.launch.parameters.extra",
-        "Launch parameters passed on the CLI, in addition to 'launch' and parameters implied by other config keys (and placed afterwards on the command line)");
-
-    @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, "
-        + "but note it will not necessarily kill sub-processes", 
-        true);
-
-    @SetFromFlag("app")
-    public static final BasicAttributeSensorAndConfigKey<String> APP = new BasicAttributeSensorAndConfigKey<String>(
-            String.class, "brooklynnode.app", "Application (fully qualified class name) to launch using the brooklyn CLI", null);
-    
-    @SetFromFlag("locations")
-    public static final BasicAttributeSensorAndConfigKey<String> LOCATIONS = new BasicAttributeSensorAndConfigKey<String>(
-            String.class, "brooklynnode.locations", "Locations to use when launching the app", null);
-    
-    /**
-     * Exposed just for testing; remote path is not passed into the launched brooklyn so this won't be used!
-     * This will likely change in a future version.
-     */
-    @VisibleForTesting
-    @SetFromFlag("brooklynGlobalPropertiesRemotePath")
-    public static final ConfigKey<String> BROOKLYN_GLOBAL_PROPERTIES_REMOTE_PATH = ConfigKeys.newStringConfigKey(
-            "brooklynnode.brooklynproperties.global.remotepath", 
-            "Remote path for the global brooklyn.properties file to be uploaded", "${HOME}/.brooklyn/brooklyn.properties; "+
-                "only useful for testing as this path will not be used on the remote system");
-    
-    @SetFromFlag("brooklynGlobalPropertiesUri")
-    public static final ConfigKey<String> BROOKLYN_GLOBAL_PROPERTIES_URI = ConfigKeys.newStringConfigKey(
-            "brooklynnode.brooklynproperties.global.uri", "URI for the global brooklyn properties file (uploaded to ~/.brooklyn/brooklyn.properties)", null);
-
-    @SetFromFlag("brooklynGlobalPropertiesContents")
-    public static final ConfigKey<String> BROOKLYN_GLOBAL_PROPERTIES_CONTENTS = ConfigKeys.newStringConfigKey(
-            "brooklynnode.brooklynproperties.global.contents", "Contents for the global brooklyn properties file (uploaded to ~/.brooklyn/brooklyn.properties)", null);
-
-    @SetFromFlag("brooklynLocalPropertiesRemotePath")
-    public static final ConfigKey<String> BROOKLYN_LOCAL_PROPERTIES_REMOTE_PATH = ConfigKeys.newStringConfigKey(
-            "brooklynnode.brooklynproperties.local.remotepath", "Remote path for the launch-specific brooklyn.properties file to be uploaded", "${driver.runDir}/brooklyn-local.properties");
-    
-    @SetFromFlag("brooklynLocalPropertiesUri")
-    public static final ConfigKey<String> BROOKLYN_LOCAL_PROPERTIES_URI = ConfigKeys.newStringConfigKey(
-            "brooklynnode.brooklynproperties.local.uri", "URI for the launch-specific brooklyn properties file", null);
-
-    @SetFromFlag("brooklynLocalPropertiesContents")
-    public static final ConfigKey<String> BROOKLYN_LOCAL_PROPERTIES_CONTENTS = ConfigKeys.newStringConfigKey(
-            "brooklynnode.brooklynproperties.local.contents", "Contents for the launch-specific brooklyn properties file", null);
-    
-    // For use in testing primarily
-    /** @deprecated since 0.7.0; TODO this should support BOM files */
-    @Deprecated
-    @SetFromFlag("brooklynCatalogRemotePath")
-    public static final ConfigKey<String> BROOKLYN_CATALOG_REMOTE_PATH = ConfigKeys.newStringConfigKey(
-            "brooklynnode.brooklyncatalog.remotepath", "Remote path for the brooklyn catalog.xml file to be uploaded", "${HOME}/.brooklyn/catalog.xml");
-    
-    /** @deprecated since 0.7.0; TODO this should support BOM files */
-    @Deprecated
-    @SetFromFlag("brooklynCatalogUri")
-    public static final ConfigKey<String> BROOKLYN_CATALOG_URI = ConfigKeys.newStringConfigKey(
-            "brooklynnode.brooklyncatalog.uri", "URI for the brooklyn catalog.xml file (uploaded to ~/.brooklyn/catalog.xml)", null);
-
-    /** @deprecated since 0.7.0; TODO this should support BOM files */
-    @Deprecated
-    @SetFromFlag("brooklynCatalogContents")
-    public static final ConfigKey<String> BROOKLYN_CATALOG_CONTENTS = ConfigKeys.newStringConfigKey(
-            "brooklynnode.brooklyncatalog.contents", "Contents for the brooklyn catalog.xml file (uploaded to ~/.brooklyn/catalog.xml)", null);
-
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    @SetFromFlag("enabledHttpProtocols")
-    public static final BasicAttributeSensorAndConfigKey<List<String>> ENABLED_HTTP_PROTOCOLS = new BasicAttributeSensorAndConfigKey(
-            List.class, "brooklynnode.webconsole.enabledHttpProtocols", "List of enabled protocols (e.g. http, https)", ImmutableList.of("http"));
-
-    @SetFromFlag("httpPort")
-    public static final PortAttributeSensorAndConfigKey HTTP_PORT = new PortAttributeSensorAndConfigKey(
-            "brooklynnode.webconsole.httpPort", "HTTP Port for the brooklyn web-console", "8081+");
-    
-    @SetFromFlag("httpsPort")
-    public static final PortAttributeSensorAndConfigKey HTTPS_PORT = new PortAttributeSensorAndConfigKey(
-            "brooklynnode.webconsole.httpsPort", "HTTPS Port for the brooklyn web-console", "8443+");
-
-    @SetFromFlag("noWebConsoleSecurity")
-    public static final BasicAttributeSensorAndConfigKey<Boolean> NO_WEB_CONSOLE_AUTHENTICATION = new BasicAttributeSensorAndConfigKey<Boolean>(
-            Boolean.class, "brooklynnode.webconsole.nosecurity", "Whether to start the web console with no security", false);
-
-    @SetFromFlag("bindAddress")
-    public static final BasicAttributeSensorAndConfigKey<InetAddress> WEB_CONSOLE_BIND_ADDRESS = new BasicAttributeSensorAndConfigKey<InetAddress>(
-            InetAddress.class, "brooklynnode.webconsole.address.bind", "Specifies the IP address of the NIC to bind the Brooklyn Management Console to (default 0.0.0.0)", Networking.ANY_NIC);
-
-    @SetFromFlag("publicAddress")
-    public static final BasicAttributeSensorAndConfigKey<InetAddress> WEB_CONSOLE_PUBLIC_ADDRESS = new BasicAttributeSensorAndConfigKey<InetAddress>(
-            InetAddress.class, "brooklynnode.webconsole.address.public", "Specifies the public IP address or hostname for the Brooklyn Management Console");
-
-    public static final AttributeSensor<Boolean> WEB_CONSOLE_ACCESSIBLE = Sensors.newBooleanSensor(
-        "brooklynnode.webconsole.up", "Whether the web console is responding normally");
-
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    @SetFromFlag("classpath")
-    public static final BasicAttributeSensorAndConfigKey<List<String>> CLASSPATH = new BasicAttributeSensorAndConfigKey(
-            List.class, "brooklynnode.classpath", "classpath to use, as list of URL entries", Lists.newArrayList());
-
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    @SetFromFlag("portMapper")
-    public static final ConfigKey<Function<? super Integer, ? extends Integer>> PORT_MAPPER = (ConfigKey) ConfigKeys.newConfigKey(Function.class,
-            "brooklynnode.webconsole.portMapper", "Function for mapping private to public ports, for use in inferring the brooklyn URI", Functions.<Integer>identity());
-
-    public static final AttributeSensor<URI> WEB_CONSOLE_URI = new BasicAttributeSensor<URI>(
-            URI.class, "brooklynnode.webconsole.url", "URL of the brooklyn web-console");
-
-    public static final AttributeSensor<ManagementNodeState> MANAGEMENT_NODE_STATE = new BasicAttributeSensor<ManagementNodeState>(
-            ManagementNodeState.class, "brooklynnode.ha.state", "High-availability state of the management node (MASTER, HOT_STANDBY, etc)");
-    
-    public static final ConfigKey<Duration> POLL_PERIOD = ConfigKeys.newConfigKey(Duration.class, "brooklynnode.poll_period",
-            "Frequency to poll for client sensors", Duration.seconds(2));
-
-    public interface DeployBlueprintEffector {
-        ConfigKey<Map<String,Object>> BLUEPRINT_CAMP_PLAN = new MapConfigKey<Object>(Object.class, "blueprintPlan",
-            "CAMP plan for the blueprint to be deployed; currently only supports Java map or JSON string (not yet YAML)");
-        ConfigKey<String> BLUEPRINT_TYPE = ConfigKeys.newStringConfigKey("blueprintType");
-        ConfigKey<Map<String,Object>> BLUEPRINT_CONFIG = new MapConfigKey<Object>(Object.class, "blueprintConfig");
-        Effector<String> DEPLOY_BLUEPRINT = Effectors.effector(String.class, "deployBlueprint")
-            .description("Deploy a blueprint, either given a plan (as Java map or JSON string for a map), or given URL and optional config")
-            .parameter(BLUEPRINT_TYPE)
-            .parameter(BLUEPRINT_CONFIG)
-            .parameter(BLUEPRINT_CAMP_PLAN)
-            .buildAbstract();
-    }
-
-    public static final Effector<String> DEPLOY_BLUEPRINT = DeployBlueprintEffector.DEPLOY_BLUEPRINT;
-
-    public interface ShutdownEffector {
-        ConfigKey<Boolean> STOP_APPS_FIRST = ConfigKeys.newBooleanConfigKey("stopAppsFirst", "Whether to stop apps before shutting down");
-        ConfigKey<Boolean> FORCE_SHUTDOWN_ON_ERROR = ConfigKeys.newBooleanConfigKey("forceShutdownOnError", "Force shutdown if apps fail to stop or timeout");
-        ConfigKey<Duration> SHUTDOWN_TIMEOUT = ConfigKeys.newConfigKey(Duration.class, "shutdownTimeout", "A maximum delay to wait for apps to gracefully stop before giving up or forcibly exiting");
-        ConfigKey<Duration> REQUEST_TIMEOUT = ConfigKeys.newConfigKey(Duration.class, "requestTimeout", "Maximum time to block the request for the shutdown to finish, 0 to wait infinitely");
-        ConfigKey<Duration> DELAY_FOR_HTTP_RETURN = ConfigKeys.newConfigKey(Duration.class, "delayForHttpReturn", "The delay before exiting the process, to permit the REST response to be returned");
-        Effector<Void> SHUTDOWN = Effectors.effector(Void.class, "shutdown")
-            .description("Shutdown the remote brooklyn instance (stops via the REST API only; leaves any VM)")
-            .parameter(STOP_APPS_FIRST)
-            .parameter(FORCE_SHUTDOWN_ON_ERROR)
-            .parameter(SHUTDOWN_TIMEOUT)
-            .parameter(REQUEST_TIMEOUT)
-            .parameter(DELAY_FOR_HTTP_RETURN)
-            .buildAbstract();
-    }
-
-    public static final Effector<Void> SHUTDOWN = ShutdownEffector.SHUTDOWN;
-
-    public interface StopNodeButLeaveAppsEffector {
-        ConfigKey<Duration> TIMEOUT = ConfigKeys.newConfigKey(Duration.class, "timeout", "How long to wait before giving up on stopping the node", Duration.ONE_HOUR);
-        Effector<Void> STOP_NODE_BUT_LEAVE_APPS = Effectors.effector(Void.class, "stopNodeButLeaveApps")
-                .description("Stop the Brooklyn process, and any VM created, and unmanage this entity; but if it was managing other applications, leave them running")
-                .parameter(TIMEOUT)
-                .buildAbstract();
-    }
-
-    public static final Effector<Void> STOP_NODE_BUT_LEAVE_APPS = StopNodeButLeaveAppsEffector.STOP_NODE_BUT_LEAVE_APPS;
-
-    public interface StopNodeAndKillAppsEffector {
-        ConfigKey<Duration> TIMEOUT = ConfigKeys.newConfigKey(Duration.class, "timeout", "How long to wait before giving up on stopping the node", Duration.ONE_HOUR);
-        Effector<Void> STOP_NODE_AND_KILL_APPS = Effectors.effector(Void.class, "stopNodeAndKillApps")
-                .description("Stop all apps managed by the Brooklyn process, stop the process, and any VM created, and unmanage this entity")
-                .parameter(TIMEOUT)
-                .buildAbstract();
-    }
-
-    public static final Effector<Void> STOP_NODE_AND_KILL_APPS = StopNodeAndKillAppsEffector.STOP_NODE_AND_KILL_APPS;
-
-    public interface SetHighAvailabilityPriorityEffector {
-        ConfigKey<Integer> PRIORITY = ConfigKeys.newIntegerConfigKey("priority", "HA priority");
-        Effector<Integer> SET_HIGH_AVAILABILITY_PRIORITY = Effectors.effector(Integer.class, "setHighAvailabilityPriority")
-                .description("Set the HA priority on the node, returning the old priority")
-                .parameter(PRIORITY)
-                .buildAbstract();
-    }
-
-    public static final Effector<Integer> SET_HIGH_AVAILABILITY_PRIORITY = SetHighAvailabilityPriorityEffector.SET_HIGH_AVAILABILITY_PRIORITY;
-
-    public interface SetHighAvailabilityModeEffector {
-        ConfigKey<HighAvailabilityMode> MODE = ConfigKeys.newConfigKey(HighAvailabilityMode.class, "mode", "HA mode");
-        Effector<ManagementNodeState> SET_HIGH_AVAILABILITY_MODE = Effectors.effector(ManagementNodeState.class, "setHighAvailabilityMode")
-                .description("Set the HA mode on the node, returning the existing state")
-                .parameter(MODE)
-                .buildAbstract();
-    }
-
-    public static final Effector<ManagementNodeState> SET_HIGH_AVAILABILITY_MODE = SetHighAvailabilityModeEffector.SET_HIGH_AVAILABILITY_MODE;
-
-    public EntityHttpClient http();
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNodeDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNodeDriver.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNodeDriver.java
deleted file mode 100644
index df27e1f..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNodeDriver.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import brooklyn.entity.java.JavaSoftwareProcessDriver;
-
-public interface BrooklynNodeDriver extends JavaSoftwareProcessDriver {
-
-    void clearInstallDir();
-
-}


[32/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/chef/ChefSoloDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/chef/ChefSoloDriver.java b/software/base/src/main/java/brooklyn/entity/chef/ChefSoloDriver.java
deleted file mode 100644
index aa97d72..0000000
--- a/software/base/src/main/java/brooklyn/entity/chef/ChefSoloDriver.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.mgmt.TaskAdaptable;
-import org.apache.brooklyn.api.mgmt.TaskFactory;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-
-import com.google.common.annotations.Beta;
-import com.google.common.reflect.TypeToken;
-
-/** Driver class to facilitate use of Chef */
-@Beta
-@Deprecated /** @deprecated since 0.7.0 use ChefEntity or ChefLifecycleEffectorTasks */
-public class ChefSoloDriver extends AbstractSoftwareProcessSshDriver implements ChefConfig {
-
-    @SuppressWarnings("serial")
-    public static final ConfigKey<TaskFactory<? extends TaskAdaptable<Boolean>>> IS_RUNNING_TASK = ConfigKeys.newConfigKey(
-            new TypeToken<TaskFactory<? extends TaskAdaptable<Boolean>>>() {}, 
-            "brooklyn.chef.task.driver.isRunningTask");
-    
-    @SuppressWarnings("serial")
-    public static final ConfigKey<TaskFactory<?>> STOP_TASK = ConfigKeys.newConfigKey(
-            new TypeToken<TaskFactory<?>>() {}, 
-            "brooklyn.chef.task.driver.stopTask");
-    
-    public ChefSoloDriver(EntityLocal entity, SshMachineLocation location) {
-        super(entity, location);
-    }
-
-    @Override
-    public void install() {
-        // TODO flag to force reinstallation
-        DynamicTasks.queue(
-                ChefSoloTasks.installChef(getInstallDir(), false), 
-                ChefSoloTasks.installCookbooks(getInstallDir(), getRequiredConfig(CHEF_COOKBOOKS), false));
-    }
-
-    @Override
-    public void customize() {
-        DynamicTasks.queue(ChefSoloTasks.buildChefFile(getRunDir(), getInstallDir(), "launch", getRequiredConfig(CHEF_RUN_LIST),
-                getEntity().getConfig(CHEF_LAUNCH_ATTRIBUTES)));
-    }
-
-    @Override
-    public void launch() {
-        DynamicTasks.queue(ChefSoloTasks.runChef(getRunDir(), "launch", getEntity().getConfig(CHEF_RUN_CONVERGE_TWICE)));
-    }
-
-    @Override
-    public boolean isRunning() {
-        return DynamicTasks.queue(getRequiredConfig(IS_RUNNING_TASK)).asTask().getUnchecked();
-    }
-
-    @Override
-    public void stop() {
-        DynamicTasks.queue(getRequiredConfig(STOP_TASK));
-    }
-
-    protected <T> T getRequiredConfig(ConfigKey<T> key) {
-        return ChefConfigs.getRequiredConfig(getEntity(), key);
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/chef/ChefSoloTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/chef/ChefSoloTasks.java b/software/base/src/main/java/brooklyn/entity/chef/ChefSoloTasks.java
deleted file mode 100644
index 629d7a9..0000000
--- a/software/base/src/main/java/brooklyn/entity/chef/ChefSoloTasks.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.mgmt.TaskFactory;
-import org.apache.brooklyn.util.ssh.BashCommands;
-
-import brooklyn.entity.software.SshEffectorTasks;
-
-import com.google.common.annotations.Beta;
-
-@Beta
-public class ChefSoloTasks {
-
-    public static TaskFactory<?> installChef(String chefDirectory, boolean force) {
-        // TODO check on entity whether it is chef _server_
-        String installCmd = cdAndRun(chefDirectory, ChefBashCommands.INSTALL_FROM_OPSCODE);
-        if (!force) installCmd = BashCommands.alternatives("which chef-solo", installCmd);
-        return SshEffectorTasks.ssh(installCmd).summary("install chef");
-    }
-
-    public static TaskFactory<?> installCookbooks(final String chefDirectory, final Map<String,String> cookbooksAndUrls, final boolean force) {
-        return ChefTasks.installCookbooks(chefDirectory, cookbooksAndUrls, force);
-    }
-
-    public static TaskFactory<?> installCookbook(String chefDirectory, String cookbookName, String cookbookArchiveUrl, boolean force) {
-        return ChefTasks.installCookbook(chefDirectory, cookbookName, cookbookArchiveUrl, force);
-    }
-
-    protected static String cdAndRun(String targetDirectory, String command) {
-        return BashCommands.chain("mkdir -p "+targetDirectory,
-                "cd "+targetDirectory,
-                command);
-    }
-
-    public static TaskFactory<?> buildChefFile(String runDirectory, String chefDirectory, String phase, Iterable<? extends String> runList,
-            Map<String, Object> optionalAttributes) {
-        return ChefTasks.buildChefFile(runDirectory, chefDirectory, phase, runList, optionalAttributes);
-    }
-
-    public static TaskFactory<?> runChef(String runDir, String phase) {
-        return runChef(runDir, phase, false);
-    }
-    /** see {@link ChefConfig#CHEF_RUN_CONVERGE_TWICE} for background on why 'twice' is available */
-    public static TaskFactory<?> runChef(String runDir, String phase, Boolean twice) {
-        String cmd = "sudo chef-solo -c "+phase+".rb -j "+phase+".json -ldebug";
-        if (twice!=null && twice) cmd = BashCommands.alternatives(cmd, cmd);
-
-        return SshEffectorTasks.ssh(cdAndRun(runDir, cmd)).
-                summary("run chef for "+phase).requiringExitCodeZero();
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/chef/ChefTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/chef/ChefTasks.java b/software/base/src/main/java/brooklyn/entity/chef/ChefTasks.java
deleted file mode 100644
index 7d5e46f..0000000
--- a/software/base/src/main/java/brooklyn/entity/chef/ChefTasks.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.mgmt.TaskAdaptable;
-import org.apache.brooklyn.api.mgmt.TaskFactory;
-import org.apache.brooklyn.effector.core.EffectorTasks;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.file.ArchiveTasks;
-import org.apache.brooklyn.util.core.file.ArchiveUtils.ArchiveType;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.TaskBuilder;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.brooklyn.util.ssh.BashCommands;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.apache.brooklyn.util.text.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.software.SshEffectorTasks;
-
-import com.google.common.annotations.Beta;
-import com.google.common.collect.ImmutableList;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-@Beta
-public class ChefTasks {
-
-    private static final Logger log = LoggerFactory.getLogger(ChefTasks.class);
-    
-    public static TaskFactory<?> installChef(String chefDirectory, boolean force) {
-        // TODO check on entity whether it is chef _server_
-        String installCmd = cdAndRun(chefDirectory, ChefBashCommands.INSTALL_FROM_OPSCODE);
-        if (!force) installCmd = BashCommands.alternatives("which chef-solo", installCmd);
-        return SshEffectorTasks.ssh(installCmd).summary("install chef");
-    }
-
-    public static TaskFactory<?> installCookbooks(final String chefDirectory, final Map<String,String> cookbooksAndUrls, final boolean force) {
-        return Tasks.<Void>builder().name("install "+(cookbooksAndUrls==null ? "0" : cookbooksAndUrls.size())+" cookbook"+Strings.s(cookbooksAndUrls)).body(
-                new Runnable() {
-                    public void run() {
-                        Entity e = EffectorTasks.findEntity();
-                        if (cookbooksAndUrls==null)
-                            throw new IllegalStateException("No cookbooks defined to install at "+e);
-                        for (String cookbook: cookbooksAndUrls.keySet())
-                            DynamicTasks.queue(installCookbook(chefDirectory, cookbook, cookbooksAndUrls.get(cookbook), force));
-                    }
-                }).buildFactory();
-    }
-
-    public static TaskFactory<?> installCookbook(final String chefDirectory, final String cookbookName, final String cookbookArchiveUrl, final boolean force) {
-        return new TaskFactory<TaskAdaptable<?>>() {
-            @Override
-            public TaskAdaptable<?> newTask() {
-                TaskBuilder<Void> tb = Tasks.<Void>builder().name("install cookbook "+cookbookName);
-                
-                String cookbookDir = Urls.mergePaths(chefDirectory, cookbookName);
-                String privateTmpDirContainingUnpackedCookbook = 
-                    Urls.mergePaths(chefDirectory, "tmp-"+Strings.makeValidFilename(cookbookName)+"-"+Identifiers.makeRandomId(4));
-
-                // TODO - skip the install earlier if it exists and isn't forced
-//                if (!force) {
-//                    // in builder.body, check 
-//                    // "ls "+cookbookDir
-//                    // and stop if it's zero
-//                    // remove reference to 'force' below
-//                }
-                
-                String destName = null;
-                if (ArchiveType.of(cookbookArchiveUrl)==ArchiveType.UNKNOWN) {
-                    destName = cookbookName + ".tgz";
-                    log.debug("Assuming TGZ type for chef cookbook url "+cookbookArchiveUrl+"; it will be downloaded as "+destName);
-                }
-                tb.add(ArchiveTasks.deploy(null, null, cookbookArchiveUrl, EffectorTasks.findSshMachine(), privateTmpDirContainingUnpackedCookbook,
-                    false, null, destName).newTask());
-                
-                String installCmd = BashCommands.chain(
-                    "cd "+privateTmpDirContainingUnpackedCookbook,  
-                    "COOKBOOK_EXPANDED_DIR=`ls`",
-                    BashCommands.requireTest("`ls | wc -w` -eq 1", 
-                            "The deployed archive "+cookbookArchiveUrl+" must contain exactly one directory"),
-                    "mv $COOKBOOK_EXPANDED_DIR '../"+cookbookName+"'",
-                    "cd ..",
-                    "rm -rf '"+privateTmpDirContainingUnpackedCookbook+"'");
-                
-                installCmd = force ? BashCommands.alternatives("rm -rf "+cookbookDir, installCmd) : BashCommands.alternatives("ls "+cookbookDir+" > /dev/null 2> /dev/null", installCmd);
-                tb.add(SshEffectorTasks.ssh(installCmd).summary("renaming cookbook dir").requiringExitCodeZero().newTask());
-                
-                return tb.build();
-            }
-        };
-    }
-
-    protected static String cdAndRun(String targetDirectory, String command) {
-        return BashCommands.chain("mkdir -p '"+targetDirectory+"'",
-                "cd '"+targetDirectory+"'",
-                command);
-    }
-
-    public static TaskFactory<?> buildChefFile(String runDirectory, String chefDirectory, String phase, Iterable<? extends String> runList,
-            Map<String, Object> optionalAttributes) {
-        // TODO if it's server, try knife first
-        // TODO configure add'l properties
-        String phaseRb = 
-            "root = "
-            + "'"+runDirectory+"'" 
-            // recommended alternate to runDir is the following, but it is not available in some rubies
-            //+ File.absolute_path(File.dirname(__FILE__))"+
-            + "\n"+
-            "file_cache_path root\n"+
-//            "cookbook_path root + '/cookbooks'\n";
-            "cookbook_path '"+chefDirectory+"'\n";
-
-        Map<String,Object> phaseJsonMap = MutableMap.of();
-        if (optionalAttributes!=null)
-            phaseJsonMap.putAll(optionalAttributes);
-        if (runList!=null)
-            phaseJsonMap.put("run_list", ImmutableList.copyOf(runList));
-        Gson json = new GsonBuilder().create();
-        String phaseJson = json.toJson(phaseJsonMap);
-
-        return Tasks.sequential("build chef files for "+phase,
-                    SshEffectorTasks.put(Urls.mergePaths(runDirectory)+"/"+phase+".rb").contents(phaseRb).createDirectory(),
-                    SshEffectorTasks.put(Urls.mergePaths(runDirectory)+"/"+phase+".json").contents(phaseJson));
-    }
-
-    public static TaskFactory<?> runChef(String runDir, String phase) {
-        // TODO chef server
-        return SshEffectorTasks.ssh(cdAndRun(runDir, "sudo chef-solo -c "+phase+".rb -j "+phase+".json -ldebug")).
-                summary("run chef for "+phase).requiringExitCodeZero();
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/chef/KnifeConvergeTaskFactory.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/chef/KnifeConvergeTaskFactory.java b/software/base/src/main/java/brooklyn/entity/chef/KnifeConvergeTaskFactory.java
deleted file mode 100644
index f193598..0000000
--- a/software/base/src/main/java/brooklyn/entity/chef/KnifeConvergeTaskFactory.java
+++ /dev/null
@@ -1,246 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import static org.apache.brooklyn.util.text.StringEscapes.BashStringEscapes.wrapBash;
-
-import java.io.File;
-import java.util.List;
-import java.util.Map;
-
-import com.google.common.base.Strings;
-import com.google.common.net.HostAndPort;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.effector.core.EffectorTasks;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.util.collections.Jsonya;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.apache.brooklyn.util.ssh.BashCommands;
-
-import com.google.common.base.Function;
-import com.google.common.base.Functions;
-import com.google.gson.GsonBuilder;
-
-public class KnifeConvergeTaskFactory<RET> extends KnifeTaskFactory<RET> {
-
-    private static final Logger log = LoggerFactory.getLogger(KnifeConvergeTaskFactory.class);
-    
-    protected Function<? super Entity,String> runList;
-    protected Map<Object, Object> knifeAttributes = new MutableMap<Object, Object>();
-    protected List<String> extraBootstrapParameters = MutableList.of();
-    protected Boolean sudo;
-    protected Boolean runTwice;
-    protected String nodeName;
-    protected Integer port;
-    /** null means nothing specified, use user supplied or machine default;
-     * false means use machine default (disallow user supplied);
-     * true means use knife default (omit the argument and disallow user supplied)
-     */
-    protected Boolean portOmittedToUseKnifeDefault;
-
-    public KnifeConvergeTaskFactory(String taskName) {
-        super(taskName);
-    }
-    
-    @Override
-    protected KnifeConvergeTaskFactory<RET> self() {
-        return this;
-    }
-    
-    /** construct the knife command, based on the settings on other methods
-     * (called when instantiating the script, after all parameters sent)
-     */
-    protected List<String> initialKnifeParameters() {
-        // runs inside the task so can detect entity/machine at runtime
-        MutableList<String> result = new MutableList<String>();
-        SshMachineLocation machine = EffectorTasks.findSshMachine();
-        
-        result.add("bootstrap");
-        result.addAll(extraBootstrapParameters);
-
-        HostAndPort hostAndPort = machine.getSshHostAndPort();
-        result.add(wrapBash(hostAndPort.getHostText()));
-        Integer whichPort = knifeWhichPort(hostAndPort);
-        if (whichPort!=null)
-            result.add("-p "+whichPort);
-
-        result.add("-x "+wrapBash(checkNotNull(machine.getUser(), "user")));
-        
-        File keyfile = ChefServerTasks.extractKeyFile(machine);
-        if (keyfile!=null) result.add("-i "+keyfile.getPath());
-        else result.add("-P "+checkNotNull(machine.findPassword(), "No password or private key data for "+machine));
-        
-        result.add("--no-host-key-verify");
-        
-        if (sudo != Boolean.FALSE) result.add("--sudo");
-
-        if (!Strings.isNullOrEmpty(nodeName)) {
-            result.add("--node-name");
-            result.add(nodeName);
-        }
-
-        result.add("-r "+wrapBash(runList.apply(entity())));
-        
-        if (!knifeAttributes.isEmpty())
-            result.add("-j "+wrapBash(new GsonBuilder().create()
-                    .toJson(knifeAttributes)));
-
-        return result;
-    }
-    
-    /** whether knife should attempt to run twice;
-     * see {@link ChefConfig#CHEF_RUN_CONVERGE_TWICE} */
-    public KnifeConvergeTaskFactory<RET> knifeRunTwice(boolean runTwice) {
-        this.runTwice = runTwice;
-        return self();
-    }
-    
-    /** whether to pass --sudo to knife; default true */
-    public KnifeConvergeTaskFactory<RET> knifeSudo(boolean sudo) {
-        this.sudo = sudo;
-        return self();
-    }
-
-    /** what node name to pass to knife; default = null, meaning chef-client will pick the node name */
-    public KnifeConvergeTaskFactory<RET> knifeNodeName(String nodeName) {
-        this.nodeName = nodeName;
-        return self();
-    }
-
-    /** tell knife to use an explicit port */
-    public KnifeConvergeTaskFactory<RET> knifePort(int port) {
-        if (portOmittedToUseKnifeDefault!=null) {
-            log.warn("Port "+port+" specified to "+this+" for when already explicitly told to use a default (overriding previous); see subsequent warning for more details");
-        }
-        this.port = port;
-        return self();
-    }
-
-    /** omit the port parameter altogether (let knife use its default) */
-    public KnifeConvergeTaskFactory<RET> knifePortUseKnifeDefault() {
-        if (port!=null) {
-            log.warn("knifePortUseKnifeDefault specified to "+this+" when already told to use "+port+" explicitly (overriding previous); see subsequent warning for more details");
-            port = -1;
-        }
-        portOmittedToUseKnifeDefault = true;
-        return self();
-    }
-    
-    /** use the default port known to brooklyn for the target machine for ssh */
-    public KnifeConvergeTaskFactory<RET> knifePortUseMachineSshPort() {
-        if (port!=null) {
-            log.warn("knifePortUseMachineSshPort specified to "+this+" when already told to use "+port+" explicitly (overriding previous); see subsequent warning for more details");
-            port = -1;
-        }
-        portOmittedToUseKnifeDefault = false;
-        return self();
-    }
-    
-    protected Integer knifeWhichPort(HostAndPort hostAndPort) {
-        if (port==null) {
-            if (Boolean.TRUE.equals(portOmittedToUseKnifeDefault))
-                // user has explicitly said to use knife default, omitting port here
-                return null;
-            // default is to use the machine port
-            return hostAndPort.getPort();
-        }
-        if (port==-1) {
-            // port was supplied by user, then portDefault (true or false)
-            port = null;
-            Integer whichPort = knifeWhichPort(hostAndPort);
-            log.warn("knife port conflicting instructions for "+this+" at entity "+entity()+" on "+hostAndPort+"; using default ("+whichPort+")");
-            return whichPort;
-        }
-        if (portOmittedToUseKnifeDefault!=null) {
-            // portDefault was specified (true or false), then overridden with a port
-            log.warn("knife port conflicting instructions for "+this+" at entity "+entity()+" on "+hostAndPort+"; using supplied port "+port);
-        }
-        // port was supplied by user, use that
-        return port;
-    }
-    
-    /** parameters to pass to knife after the bootstrap command */
-    public KnifeConvergeTaskFactory<RET> knifeAddExtraBootstrapParameters(String extraBootstrapParameter1, String ...extraBootstrapParameters) {
-        this.extraBootstrapParameters.add(extraBootstrapParameter1);
-        for (String p: extraBootstrapParameters)
-            this.extraBootstrapParameters.add(p);
-        return self();
-    }
-    
-    /** function supplying the run list to be passed to knife, evaluated at the last moment */
-    public KnifeConvergeTaskFactory<RET> knifeRunList(Function<? super Entity, String> runList) {
-        this.runList = runList;
-        return self();
-    }
-    public KnifeConvergeTaskFactory<RET> knifeRunList(String runList) {
-        this.runList = Functions.constant(runList);
-        return self();
-    }
-    
-    /** includes the given attributes in the attributes to be passed to chef; 
-     * when combining with other attributes, this uses {@link Jsonya} semantics to add 
-     * (a deep add, combining lists and maps) */
-    public KnifeConvergeTaskFactory<RET> knifeAddAttributes(Map<? extends Object, ? extends Object> attributes) {
-        if (attributes!=null && !attributes.isEmpty()) {
-            Jsonya.of(knifeAttributes).add(attributes);
-        }
-        return self();
-    }
-    
-    protected String buildKnifeCommand(int knifeCommandIndex) {
-        String result = super.buildKnifeCommand(knifeCommandIndex);
-        if (Boolean.TRUE.equals(runTwice))
-            result = BashCommands.alternatives(result, result);
-        return result;
-    }
-
-    @Override
-    public <T2> KnifeConvergeTaskFactory<T2> returning(ScriptReturnType type) {
-        return (KnifeConvergeTaskFactory<T2>) super.<T2>returning(type);
-    }
-
-    @Override
-    public <RET2> KnifeConvergeTaskFactory<RET2> returning(Function<ProcessTaskWrapper<?>, RET2> resultTransformation) {
-        return (KnifeConvergeTaskFactory<RET2>) super.returning(resultTransformation);
-    }
-    
-    @Override
-    public KnifeConvergeTaskFactory<Boolean> returningIsExitCodeZero() {
-        return (KnifeConvergeTaskFactory<Boolean>) super.returningIsExitCodeZero();
-    }
-    
-    @Override
-    public KnifeConvergeTaskFactory<String> requiringZeroAndReturningStdout() {
-        return (KnifeConvergeTaskFactory<String>) super.requiringZeroAndReturningStdout();
-    }
-
-    public KnifeConvergeTaskFactory<RET> knifeAddParameters(String word1, String ...words) {
-        super.knifeAddParameters(word1, words);
-        return self();
-    }
-
-    // TODO other methods from KnifeTaskFactory will return KTF class not KCTF;
-    // should make it generic so it returns the right type...
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/chef/KnifeTaskFactory.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/chef/KnifeTaskFactory.java b/software/base/src/main/java/brooklyn/entity/chef/KnifeTaskFactory.java
deleted file mode 100644
index 80fad0e..0000000
--- a/software/base/src/main/java/brooklyn/entity/chef/KnifeTaskFactory.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.core.internal.ssh.process.ProcessTool;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskFactory;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.apache.brooklyn.util.core.task.system.internal.SystemProcessTaskFactory;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.text.StringEscapes.BashStringEscapes;
-
-import com.google.common.base.Function;
-
-/** A factory which acts like {@link ProcessTaskFactory} with special options for knife.
- * Typical usage is to {@link #addKnifeParameters(String)}s for the knife command to be run.
- * You can also {@link #add(String...)} commands as needed; these will run *before* knife,
- * unless you addKnifeCommandHere().
- * <p>
- * This impl will use sensible defaults, including {@link ConfigKey}s on the context entity,
- * for general knife config but not specific commands etc. It supports:
- * <li> {@link ChefConfig#KNIFE_EXECUTABLE}
- * <li> {@link ChefConfig#KNIFE_CONFIG_FILE}
- * <p>
- * (Other fields will typically be used by methods calling to this factory.) 
- *  */
-// see e.g. http://docs.opscode.com/knife_bootstrap.html
-public class KnifeTaskFactory<RET> extends SystemProcessTaskFactory<KnifeTaskFactory<RET>, RET>{
-    
-    private static String KNIFE_PLACEHOLDER = "<knife command goes here 1234>";
-    public final String taskName;
-    protected String knifeExecutable;
-    protected List<String> knifeParameters = new ArrayList<String>();
-    protected String knifeConfigFile;
-    protected String knifeSetupCommands;
-    protected Boolean throwOnCommonKnifeErrors;
-    
-    public KnifeTaskFactory(String taskName) {
-        this.taskName = taskName;
-        summary(taskName);
-        // knife setup usually requires a login shell
-        config.put(ProcessTool.PROP_LOGIN_SHELL, true);
-    }
-    
-    @Override
-    public List<Function<ProcessTaskWrapper<?>, Void>> getCompletionListeners() {
-        MutableList<Function<ProcessTaskWrapper<?>, Void>> result = MutableList.copyOf(super.getCompletionListeners());
-        if (throwOnCommonKnifeErrors != Boolean.FALSE)
-            insertKnifeCompletionListenerIntoCompletionListenersList(result);
-        return result.asUnmodifiable();
-    }
-    
-    public KnifeTaskFactory<RET> notThrowingOnCommonKnifeErrors() {
-        throwOnCommonKnifeErrors = false;
-        return self();
-    }
-
-    protected void insertKnifeCompletionListenerIntoCompletionListenersList(List<Function<ProcessTaskWrapper<?>, Void>> listeners) {
-        // give a nice warning if chef/knife not set up correctly
-        Function<ProcessTaskWrapper<?>, Void> propagateIfKnifeConfigFileMissing = new Function<ProcessTaskWrapper<?>, Void>() {
-            public Void apply(@Nullable ProcessTaskWrapper<?> input) {
-                if (input.getExitCode()!=0 && input.getStderr().indexOf("WARNING: No knife configuration file found")>=0) {
-                    String myConfig = knifeConfigFileOption();
-                    if (Strings.isEmpty(myConfig))
-                        throw new IllegalStateException("Config file for Chef knife must be specified in "+ChefConfig.KNIFE_CONFIG_FILE+" (or valid knife default set up)");
-                    else
-                        throw new IllegalStateException("Error reading config file for Chef knife ("+myConfig+") -- does it exist?");
-                }
-                return null;
-            }
-        };
-        listeners.add(propagateIfKnifeConfigFileMissing);
-    }
-
-    
-    @Override
-    public ProcessTaskWrapper<RET> newTask() {
-        return new SystemProcessTaskWrapper("Knife");
-    }
-
-    /** Inserts the knife command at the current place in the list.
-     * Can be run multiple times. The knife command added at the end of the list
-     * if this is not invoked (and it is the only command if nothing is {@link #add(String...)}ed.
-     */
-    public KnifeTaskFactory<RET> addKnifeCommandToScript() {
-        add(KNIFE_PLACEHOLDER);
-        return self();
-    }
-    
-    @Override
-    public List<String> getCommands() {
-        MutableList<String> result = new MutableList<String>();
-        String setupCommands = knifeSetupCommands();
-        if (setupCommands != null && Strings.isNonBlank(setupCommands))
-            result.add(setupCommands);
-        int numKnifes = 0;
-        for (String c: super.getCommands()) {
-            if (c==KNIFE_PLACEHOLDER)
-                result.add(buildKnifeCommand(numKnifes++));
-            else
-                result.add(c);
-        }
-        if (numKnifes==0)
-            result.add(buildKnifeCommand(numKnifes++));
-        return result.asUnmodifiable();
-    }
-    
-    /** creates the command for running knife.
-     * in some cases knife may be added multiple times,
-     * and in that case the parameter here tells which time it is being added, 
-     * on a single run. */
-    protected String buildKnifeCommand(int knifeCommandIndex) {
-        MutableList<String> words = new MutableList<String>();
-        words.add(knifeExecutable());
-        words.addAll(initialKnifeParameters());
-        words.addAll(knifeParameters());
-        String x = knifeConfigFileOption();
-        if (Strings.isNonBlank(x)) words.add(knifeConfigFileOption());
-        return Strings.join(words, " ");
-    }
-    
-    /** allows a way for subclasses to build up parameters at the start */
-    protected List<String> initialKnifeParameters() {
-        return new MutableList<String>();
-    }
-    
-    @Nullable /** callers should allow this to be null so task can be used outside of an entity */
-    protected Entity entity() {
-        return BrooklynTaskTags.getTargetOrContextEntity(Tasks.current());
-    }
-    protected <T> T entityConfig(ConfigKey<T> key) {
-        Entity entity = entity();
-        if (entity!=null)
-            return entity.getConfig(key);
-        return null;
-    }
-    
-    public KnifeTaskFactory<RET> knifeExecutable(String knifeExecutable) {
-        this.knifeExecutable = knifeExecutable;
-        return this;
-    }
-    
-    protected String knifeExecutable() {
-        if (knifeExecutable!=null) return knifeExecutable;
-        
-        String knifeExecFromConfig = entityConfig(ChefConfig.KNIFE_EXECUTABLE);
-        if (knifeExecFromConfig!=null) return BashStringEscapes.wrapBash(knifeExecFromConfig);
-        
-        // assume on the path, if executable not set
-        return "knife";
-    }
-    
-    protected List<String> knifeParameters() {
-        return knifeParameters;
-    }
-    
-    public KnifeTaskFactory<RET> knifeAddParameters(String word1, String ...words) {
-        knifeParameters.add(word1);
-        for (String w: words)
-            knifeParameters.add(w);
-        return self();
-    }
-
-    public KnifeTaskFactory<RET> knifeConfigFile(String knifeConfigFile) {
-        this.knifeConfigFile = knifeConfigFile;
-        return self();
-    }
-    
-    @Nullable
-    protected String knifeConfigFileOption() {
-        if (knifeConfigFile!=null) return "-c "+knifeConfigFile;
-
-        String knifeConfigFileFromConfig = entityConfig(ChefConfig.KNIFE_CONFIG_FILE);
-        if (knifeConfigFileFromConfig!=null) return "-c "+BashStringEscapes.wrapBash(knifeConfigFileFromConfig);
-
-        // if not supplied will use global config
-        return null;
-    }
-
-    public KnifeTaskFactory<RET> knifeSetupCommands(String knifeSetupCommands) {
-        this.knifeSetupCommands = knifeSetupCommands;
-        return self();
-    }
-    
-    @Nullable
-    protected String knifeSetupCommands() {
-        if (knifeSetupCommands!=null) return knifeSetupCommands;
-        
-        String knifeSetupCommandsFromConfig = entityConfig(ChefConfig.KNIFE_SETUP_COMMANDS);
-        if (knifeSetupCommandsFromConfig!=null) return knifeSetupCommandsFromConfig;
-        
-        // if not supplied will use global config
-        return null;
-    }
-    
-    @Override
-    public <T2> KnifeTaskFactory<T2> returning(ScriptReturnType type) {
-        return (KnifeTaskFactory<T2>) super.<T2>returning(type);
-    }
-
-    @Override
-    public <RET2> KnifeTaskFactory<RET2> returning(Function<ProcessTaskWrapper<?>, RET2> resultTransformation) {
-        return (KnifeTaskFactory<RET2>) super.returning(resultTransformation);
-    }
-    
-    @Override
-    public KnifeTaskFactory<Boolean> returningIsExitCodeZero() {
-        return (KnifeTaskFactory<Boolean>) super.returningIsExitCodeZero();
-    }
-    
-    @Override
-    public KnifeTaskFactory<String> requiringZeroAndReturningStdout() {
-        return (KnifeTaskFactory<String>) super.requiringZeroAndReturningStdout();
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/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
deleted file mode 100644
index 42cffda..0000000
--- a/software/base/src/main/java/brooklyn/entity/java/JavaAppUtils.java
+++ /dev/null
@@ -1,264 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import static org.apache.brooklyn.util.JavaGroovyEquivalents.groovyTruth;
-
-import java.lang.management.ManagementFactory;
-import java.lang.management.MemoryUsage;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-import javax.management.openmbean.CompositeData;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.core.config.render.RendererHints;
-import org.apache.brooklyn.policy.enricher.RollingTimeWindowMeanEnricher;
-import org.apache.brooklyn.policy.enricher.TimeFractionDeltaEnricher;
-import org.apache.brooklyn.sensor.feed.http.HttpValueFunctions;
-import org.apache.brooklyn.util.math.MathFunctions;
-import org.apache.brooklyn.util.text.ByteSizeStrings;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-
-import brooklyn.event.feed.jmx.JmxAttributePollConfig;
-import brooklyn.event.feed.jmx.JmxFeed;
-
-import com.google.common.base.Function;
-
-public class JavaAppUtils {
-
-    public static boolean isEntityMxBeanStatsEnabled(Entity entity) {
-        return groovyTruth(entity.getConfig(UsesJavaMXBeans.MXBEAN_STATS_ENABLED));
-    }
-
-    /**
-     * @see #connectJavaAppServerPolicies(EntityLocal, Duration)
-     * @see #getMxBeanSensorsBuilder(EntityLocal)
-     */
-    @Nullable
-    public static JmxFeed connectMXBeanSensors(EntityLocal entity) {
-        if (isEntityMxBeanStatsEnabled(entity)) {
-            return getMxBeanSensorsBuilder(entity).build();
-        } else {
-            return null;
-        }
-    }
-
-    /** @see #connectJavaAppServerPolicies(EntityLocal, Duration) */
-    @Nullable
-    public static JmxFeed connectMXBeanSensors(EntityLocal entity, long jmxPollPeriodMs) {
-        if (isEntityMxBeanStatsEnabled(entity)) {
-            return getMxBeanSensorsBuilder(entity, jmxPollPeriodMs).build();
-        } else {
-            return null;
-        }
-    }
-
-    /**
-     * @param entity The entity at which to poll
-     * @param jmxPollPeriod How often to poll
-     * @return A {@link JmxFeed} configured to poll the given entity at the given period,
-     *         or null if the entity is not configured for MXBEAN_STATS
-     * @see brooklyn.entity.java.UsesJavaMXBeans#MXBEAN_STATS_ENABLED
-     */
-    @Nullable
-    public static JmxFeed connectMXBeanSensors(EntityLocal entity, Duration jmxPollPeriod) {
-        if (isEntityMxBeanStatsEnabled(entity)) {
-            return getMxBeanSensorsBuilder(entity, jmxPollPeriod).build();
-        } else {
-            return null;
-        }
-    }
-    
-    public static void connectJavaAppServerPolicies(EntityLocal entity) {
-        connectJavaAppServerPolicies(entity, Duration.TEN_SECONDS);
-    }
-
-    public static void connectJavaAppServerPolicies(EntityLocal entity, Duration windowPeriod) {
-        entity.addEnricher(new TimeFractionDeltaEnricher<Double>(entity, UsesJavaMXBeans.PROCESS_CPU_TIME, 
-                UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_LAST, TimeUnit.MILLISECONDS));
-
-        entity.addEnricher(new RollingTimeWindowMeanEnricher<Double>(entity,
-                UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_LAST, UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_IN_WINDOW,
-                windowPeriod));
-    }
-
-    /**
-     * @param entity The entity at which to poll
-     * @return A {@link JmxFeed.Builder} configured to poll entity every ten seconds
-     * @see #getMxBeanSensorsBuilder(EntityLocal, Duration)
-     */
-    @Nonnull
-    public static JmxFeed.Builder getMxBeanSensorsBuilder(EntityLocal entity) {
-        return getMxBeanSensorsBuilder(entity, Duration.TEN_SECONDS);
-    }
-
-    /** @see #getMxBeanSensorsBuilder(EntityLocal, Duration) */
-    @Nonnull
-    public static JmxFeed.Builder getMxBeanSensorsBuilder(EntityLocal entity, long jmxPollPeriod) {
-        return getMxBeanSensorsBuilder(entity, Duration.millis(jmxPollPeriod));
-    }
-
-    /**
-     * @param entity The entity at which to poll
-     * @param jmxPollPeriod How often to poll
-     * @return A {@link JmxFeed.Builder} configured to poll many interesting MXBeans
-     *         at the given entity and to repeat according to the given poll period.
-     *         <p/>
-     *         If an entity does not have MXBean stats enabled (i.e. {@link UsesJavaMXBeans#MXBEAN_STATS_ENABLED} is
-     *         configured to false) then returns a builder configured with entity and duration but no polls.
-     *         <p/>
-     *         Use {@link #connectMXBeanSensors(EntityLocal, Duration)} to create and build in one step.
-     */
-    @Nonnull
-    @SuppressWarnings({"unchecked"})
-    public static JmxFeed.Builder getMxBeanSensorsBuilder(EntityLocal entity, Duration jmxPollPeriod) {
-        JmxFeed.Builder builder = JmxFeed.builder()
-                .entity(entity)
-                .period(jmxPollPeriod);
-        if (isEntityMxBeanStatsEnabled(entity)) {
-            // TODO Could we reuse the result of compositeDataToMemoryUsage?
-            builder
-                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.USED_HEAP_MEMORY)
-                        .objectName(ManagementFactory.MEMORY_MXBEAN_NAME)
-                        .attributeName("HeapMemoryUsage")
-                        .onSuccess((Function) HttpValueFunctions.chain(compositeDataToMemoryUsage(), new Function<MemoryUsage, Long>() {
-                            @Override public Long apply(MemoryUsage input) {
-                                return (input == null) ? null : input.getUsed();
-                            }})))
-                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.INIT_HEAP_MEMORY)
-                        .objectName(ManagementFactory.MEMORY_MXBEAN_NAME)
-                        .attributeName("HeapMemoryUsage")
-                        .onSuccess((Function) HttpValueFunctions.chain(compositeDataToMemoryUsage(), new Function<MemoryUsage, Long>() {
-                            @Override public Long apply(MemoryUsage input) {
-                                return (input == null) ? null : input.getInit();
-                            }})))
-                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.COMMITTED_HEAP_MEMORY)
-                        .objectName(ManagementFactory.MEMORY_MXBEAN_NAME)
-                        .attributeName("HeapMemoryUsage")
-                        .onSuccess((Function) HttpValueFunctions.chain(compositeDataToMemoryUsage(), new Function<MemoryUsage, Long>() {
-                            @Override public Long apply(MemoryUsage input) {
-                                return (input == null) ? null : input.getCommitted();
-                            }})))
-                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.MAX_HEAP_MEMORY)
-                        .objectName(ManagementFactory.MEMORY_MXBEAN_NAME)
-                        .attributeName("HeapMemoryUsage")
-                        .onSuccess((Function) HttpValueFunctions.chain(compositeDataToMemoryUsage(), new Function<MemoryUsage, Long>() {
-                            @Override public Long apply(MemoryUsage input) {
-                                return (input == null) ? null : input.getMax();
-                            }})))
-                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.NON_HEAP_MEMORY_USAGE)
-                        .objectName(ManagementFactory.MEMORY_MXBEAN_NAME)
-                        .attributeName("NonHeapMemoryUsage")
-                        .onSuccess((Function) HttpValueFunctions.chain(compositeDataToMemoryUsage(), new Function<MemoryUsage, Long>() {
-                            @Override public Long apply(MemoryUsage input) {
-                                return (input == null) ? null : input.getUsed();
-                            }})))
-
-                .pollAttribute(new JmxAttributePollConfig<Integer>(UsesJavaMXBeans.CURRENT_THREAD_COUNT)
-                        .objectName(ManagementFactory.THREAD_MXBEAN_NAME)
-                        .attributeName("ThreadCount"))
-                .pollAttribute(new JmxAttributePollConfig<Integer>(UsesJavaMXBeans.PEAK_THREAD_COUNT)
-                        .objectName(ManagementFactory.THREAD_MXBEAN_NAME)
-                        .attributeName("PeakThreadCount"))
-
-                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.START_TIME)
-                        .objectName(ManagementFactory.RUNTIME_MXBEAN_NAME)
-                        .period(60, TimeUnit.SECONDS)
-                        .attributeName("StartTime"))
-                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.UP_TIME)
-                        .objectName(ManagementFactory.RUNTIME_MXBEAN_NAME)
-                        .period(60, TimeUnit.SECONDS)
-                        .attributeName("Uptime"))
-
-                .pollAttribute(new JmxAttributePollConfig<Double>(UsesJavaMXBeans.PROCESS_CPU_TIME)
-                        .objectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME)
-                        .attributeName("ProcessCpuTime")
-                        .onSuccess((Function) MathFunctions.times(0.001*0.001)))   // nanos to millis
-                .pollAttribute(new JmxAttributePollConfig<Double>(UsesJavaMXBeans.SYSTEM_LOAD_AVERAGE)
-                        .objectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME)
-                        .attributeName("SystemLoadAverage"))
-                .pollAttribute(new JmxAttributePollConfig<Integer>(UsesJavaMXBeans.AVAILABLE_PROCESSORS)
-                        .objectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME)
-                        .period(60, TimeUnit.SECONDS)
-                        .attributeName("AvailableProcessors"))
-                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.TOTAL_PHYSICAL_MEMORY_SIZE)
-                        .objectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME)
-                        .period(60, TimeUnit.SECONDS)
-                        .attributeName("TotalPhysicalMemorySize"))
-                .pollAttribute(new JmxAttributePollConfig<Long>(UsesJavaMXBeans.FREE_PHYSICAL_MEMORY_SIZE)
-                        .objectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME)
-                        .period(60, TimeUnit.SECONDS)
-                        .attributeName("FreePhysicalMemorySize"));
-         //FIXME: need a new type of adapter that maps multiple objectNames to a mapping
-         // jmxAdapter.objectName(ManagementFactory.GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",*").with {
-         //     attribute("SystemLoadAverage").subscribe(UsesJavaMXBeans.GARBAGE_COLLECTION_TIME, { def m -> log.info("XXXXXXX $m") });
-         // }
-        }
-        return builder;
-    }
-
-    /** @deprecated Since 0.7.0. Use {@link org.apache.brooklyn.util.math.MathFunctions#times(double)} instead */
-    @Deprecated
-    public static Function<Number, Double> times(final double x) {
-        return MathFunctions.times(x);
-    }
-
-    public static Function<CompositeData, MemoryUsage> compositeDataToMemoryUsage() {
-        return new Function<CompositeData, MemoryUsage>() {
-            @Override public MemoryUsage apply(CompositeData input) {
-                return (input == null) ? null : MemoryUsage.from(input);
-            }
-        };
-    }
-
-    private static final AtomicBoolean initialized = new AtomicBoolean(false);
-
-    /** Setup renderer hints for the MXBean attributes. */
-    public static void init() {
-        if (initialized.get()) return;
-        synchronized (initialized) {
-            if (initialized.get()) return;
-
-            RendererHints.register(UsesJavaMXBeans.USED_HEAP_MEMORY, RendererHints.displayValue(ByteSizeStrings.metric()));
-            RendererHints.register(UsesJavaMXBeans.INIT_HEAP_MEMORY, RendererHints.displayValue(ByteSizeStrings.metric()));
-            RendererHints.register(UsesJavaMXBeans.MAX_HEAP_MEMORY, RendererHints.displayValue(ByteSizeStrings.metric()));
-            RendererHints.register(UsesJavaMXBeans.COMMITTED_HEAP_MEMORY, RendererHints.displayValue(ByteSizeStrings.metric()));
-            RendererHints.register(UsesJavaMXBeans.NON_HEAP_MEMORY_USAGE, RendererHints.displayValue(ByteSizeStrings.metric()));
-            RendererHints.register(UsesJavaMXBeans.TOTAL_PHYSICAL_MEMORY_SIZE, RendererHints.displayValue(ByteSizeStrings.metric()));
-            RendererHints.register(UsesJavaMXBeans.FREE_PHYSICAL_MEMORY_SIZE, RendererHints.displayValue(ByteSizeStrings.metric()));
-
-            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(MathFunctions.percent(4)));
-            RendererHints.register(UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_IN_WINDOW, RendererHints.displayValue(MathFunctions.percent(4)));
-
-            initialized.set(true);
-        }
-    }
-
-    static {
-        init();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/java/JavaEntityMethods.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/java/JavaEntityMethods.java b/software/base/src/main/java/brooklyn/entity/java/JavaEntityMethods.java
deleted file mode 100644
index a9fad73..0000000
--- a/software/base/src/main/java/brooklyn/entity/java/JavaEntityMethods.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import org.apache.brooklyn.config.ConfigKey;
-
-/** DSL conveniences for Java entities. Also see {@link JavaAppUtils} for methods useful within Java classes. */
-public class JavaEntityMethods {
-
-    public static ConfigKey<String> javaSysProp(String propertyName) { return UsesJava.JAVA_SYSPROPS.subKey(propertyName); }
-    
-    // TODO javaMaxHeap javaInitialHeap javaMaxPermGen should all be supplied as ListConfigs on JAVA_OPTIONS
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/java/JavaSoftwareProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/java/JavaSoftwareProcessDriver.java b/software/base/src/main/java/brooklyn/entity/java/JavaSoftwareProcessDriver.java
deleted file mode 100644
index 890403f..0000000
--- a/software/base/src/main/java/brooklyn/entity/java/JavaSoftwareProcessDriver.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import brooklyn.entity.basic.SoftwareProcessDriver;
-
-/**
- * A {@link SoftwareProcessDriver} for Java processes.
- */
-public interface JavaSoftwareProcessDriver extends SoftwareProcessDriver {
-
-    public boolean isJmxEnabled();
-        
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/java/JavaSoftwareProcessSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/java/JavaSoftwareProcessSshDriver.java b/software/base/src/main/java/brooklyn/entity/java/JavaSoftwareProcessSshDriver.java
deleted file mode 100644
index 178d48f..0000000
--- a/software/base/src/main/java/brooklyn/entity/java/JavaSoftwareProcessSshDriver.java
+++ /dev/null
@@ -1,444 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import static org.apache.brooklyn.util.JavaGroovyEquivalents.groovyTruth;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.effector.core.EffectorTasks;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Function;
-import com.google.common.base.Joiner;
-import com.google.common.base.Optional;
-import com.google.common.base.Splitter;
-import com.google.common.base.Throwables;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.gson.internal.Primitives;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-import brooklyn.entity.software.SshEffectorTasks;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.collections.MutableSet;
-import org.apache.brooklyn.util.core.flags.TypeCoercions;
-import org.apache.brooklyn.util.core.internal.ssh.ShellTool;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.core.task.ssh.SshTasks;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskFactory;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.ssh.BashCommands;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.text.StringEscapes.BashStringEscapes;
-
-/**
- * The SSH implementation of the {@link brooklyn.entity.java.JavaSoftwareProcessDriver}.
- */
-public abstract class JavaSoftwareProcessSshDriver extends AbstractSoftwareProcessSshDriver implements JavaSoftwareProcessDriver {
-
-    public static final Logger log = LoggerFactory.getLogger(JavaSoftwareProcessSshDriver.class);
-
-    public static final List<List<String>> MUTUALLY_EXCLUSIVE_OPTS = ImmutableList.<List<String>> of(ImmutableList.of("-client",
-            "-server"));
-
-    public static final List<String> KEY_VAL_OPT_PREFIXES = ImmutableList.of("-Xmx", "-Xms", "-Xss");
-
-    public JavaSoftwareProcessSshDriver(EntityLocal entity, SshMachineLocation machine) {
-        super(entity, machine);
-
-        entity.setAttribute(Attributes.LOG_FILE_LOCATION, getLogFileLocation());
-    }
-
-    protected abstract String getLogFileLocation();
-
-    public boolean isJmxEnabled() {
-        return (entity instanceof UsesJmx) && (entity.getConfig(UsesJmx.USE_JMX));
-    }
-
-    public boolean isJmxSslEnabled() {
-        return isJmxEnabled() && groovyTruth(entity.getConfig(UsesJmx.JMX_SSL_ENABLED));
-    }
-
-    /**
-     * Sets all JVM options (-X.. -D..) in an environment var JAVA_OPTS.
-     * <p>
-     * That variable is constructed from {@link #getJavaOpts()}, then wrapped _unescaped_ in double quotes. An
-     * error is thrown if there is an unescaped double quote in the string. All other unescaped
-     * characters are permitted, but unless $var expansion or `command` execution is desired (although
-     * this is not confirmed as supported) the generally caller should escape any such characters, for
-     * example using {@link BashStringEscapes#escapeLiteralForDoubleQuotedBash(String)}.
-     */
-    @Override
-    public Map<String, String> getShellEnvironment() {
-        List<String> javaOpts = getJavaOpts();
-
-        for (String it : javaOpts) {
-            BashStringEscapes.assertValidForDoubleQuotingInBash(it);
-        }
-        // do not double quote here; the env var is double quoted subsequently;
-        // spaces should be preceded by double-quote
-        // (if dbl quotes are needed we could pass on the command-line instead of in an env var)
-        String sJavaOpts = Joiner.on(' ').join(javaOpts);
-        return MutableMap.<String, String>builder().putAll(super.getShellEnvironment()).put("JAVA_OPTS", sJavaOpts).build();
-    }
-
-    /**
-     * arguments to pass to the JVM; this is the config options (e.g. -Xmx1024; only the contents of
-     * {@link #getCustomJavaConfigOptions()} by default) and java system properties (-Dk=v; add custom
-     * properties in {@link #getCustomJavaSystemProperties()})
-     * <p>
-     * See {@link #getShellEnvironment()} for discussion of quoting/escaping strategy.
-     **/
-    public List<String> getJavaOpts() {
-        Iterable<String> sysprops = Iterables.transform(getJavaSystemProperties().entrySet(),
-                new Function<Map.Entry<String, ?>, String>() {
-                    public String apply(Map.Entry<String, ?> entry) {
-                        String k = entry.getKey();
-                        Object v = entry.getValue();
-                        try {
-                            if (v != null && Primitives.isWrapperType(v.getClass())) {
-                                v = "" + v;
-                            } else {
-                                v = Tasks.resolveValue(v, Object.class, ((EntityInternal)entity).getExecutionContext());
-                                if (v == null) {
-                                } else if (v instanceof CharSequence) {
-                                } else if (TypeCoercions.isPrimitiveOrBoxer(v.getClass())) {
-                                    v = "" + v;
-                                } else {
-                                    // could do toString, but that's likely not what is desired;
-                                    // probably a type mismatch,
-                                    // post-processing should be specified (common types are accepted
-                                    // above)
-                                    throw new IllegalArgumentException("cannot convert value " + v + " of type " + v.getClass()
-                                            + " to string to pass as JVM property; use a post-processor");
-                                }
-                            }
-                            return "-D" + k + (v != null ? "=" + v : "");
-                        } catch (Exception e) {
-                            log.warn("Error resolving java option key {}, propagating: {}", k, e);
-                            throw Throwables.propagate(e);
-                        }
-                    }
-                });
-
-        Set<String> result = MutableSet.<String> builder().
-                addAll(getJmxJavaConfigOptions()).
-                addAll(getCustomJavaConfigOptions()).
-                addAll(sysprops).
-            build();
-
-        for (String customOpt : entity.getConfig(UsesJava.JAVA_OPTS)) {
-            for (List<String> mutuallyExclusiveOpt : MUTUALLY_EXCLUSIVE_OPTS) {
-                if (mutuallyExclusiveOpt.contains(customOpt)) {
-                    result.removeAll(mutuallyExclusiveOpt);
-                }
-            }
-            for (String keyValOptPrefix : KEY_VAL_OPT_PREFIXES) {
-                if (customOpt.startsWith(keyValOptPrefix)) {
-                    for (Iterator<String> iter = result.iterator(); iter.hasNext();) {
-                        String existingOpt = iter.next();
-                        if (existingOpt.startsWith(keyValOptPrefix)) {
-                            iter.remove();
-                        }
-                    }
-                }
-            }
-            if (customOpt.contains("=")) {
-                String customOptPrefix = customOpt.substring(0, customOpt.indexOf("="));
-
-                for (Iterator<String> iter = result.iterator(); iter.hasNext();) {
-                    String existingOpt = iter.next();
-                    if (existingOpt.startsWith(customOptPrefix)) {
-                        iter.remove();
-                    }
-                }
-            }
-            result.add(customOpt);
-        }
-
-        return ImmutableList.copyOf(result);
-    }
-
-    /**
-     * Returns the complete set of Java system properties (-D defines) to set for the application.
-     * <p>
-     * This is exposed to the JVM as the contents of the {@code JAVA_OPTS} environment variable. Default
-     * set contains config key, custom system properties, and JMX defines.
-     * <p>
-     * Null value means to set -Dkey otherwise it is -Dkey=value.
-     * <p>
-     * See {@link #getShellEnvironment()} for discussion of quoting/escaping strategy.
-     */
-    protected Map<String,?> getJavaSystemProperties() {
-        return MutableMap.<String,Object>builder()
-                .putAll(getCustomJavaSystemProperties())
-                .putAll(isJmxEnabled() ? getJmxJavaSystemProperties() : Collections.<String,Object>emptyMap())
-                .putAll(entity.getConfig(UsesJava.JAVA_SYSPROPS))
-                .build();
-    }
-
-    /**
-     * Return extra Java system properties (-D defines) used by the application.
-     *
-     * Override as needed; default is an empty map.
-     */
-    protected Map getCustomJavaSystemProperties() {
-        return Maps.newLinkedHashMap();
-    }
-
-    /**
-     * Return extra Java config options, ie arguments starting with - which are passed to the JVM prior
-     * to the class name.
-     * <p>
-     * Note defines are handled separately, in {@link #getCustomJavaSystemProperties()}.
-     * <p>
-     * Override as needed; default is an empty list.
-     */
-    protected List<String> getCustomJavaConfigOptions() {
-        return Lists.newArrayList();
-    }
-
-    /** @deprecated since 0.6.0, the config key is always used instead of this */ @Deprecated
-    public Integer getJmxPort() {
-        return !isJmxEnabled() ? Integer.valueOf(-1) : entity.getAttribute(UsesJmx.JMX_PORT);
-    }
-
-    /** @deprecated since 0.6.0, the config key is always used instead of this */ @Deprecated
-    public Integer getRmiRegistryPort() {
-        return !isJmxEnabled() ? -1 : entity.getAttribute(UsesJmx.RMI_REGISTRY_PORT);
-    }
-
-    /** @deprecated since 0.6.0, the config key is always used instead of this */ @Deprecated
-    public String getJmxContext() {
-        return !isJmxEnabled() ? null : entity.getAttribute(UsesJmx.JMX_CONTEXT);
-    }
-
-    /**
-     * Return the configuration properties required to enable JMX for a Java application.
-     *
-     * These should be set as properties in the {@code JAVA_OPTS} environment variable when calling the
-     * run script for the application.
-     */
-    protected Map<String, ?> getJmxJavaSystemProperties() {
-        MutableMap.Builder<String, Object> result = MutableMap.<String, Object> builder();
-
-        if (isJmxEnabled()) {
-            new JmxSupport(getEntity(), getRunDir()).applyJmxJavaSystemProperties(result);
-        }
-
-        return result.build();
-    }
-
-    /**
-     * Return any JVM arguments required, other than the -D defines returned by {@link #getJmxJavaSystemProperties()}
-     */
-    protected List<String> getJmxJavaConfigOptions() {
-        List<String> result = new ArrayList<String>();
-        if (isJmxEnabled()) {
-            result.addAll(new JmxSupport(getEntity(), getRunDir()).getJmxJavaConfigOptions());
-        }
-        return result;
-    }
-
-    /**
-     * Checks for the presence of Java on the entity's location, installing if necessary.
-     * @return true if the required version of Java was found on the machine or if it was installed correctly,
-     * otherwise false.
-     */
-    protected boolean checkForAndInstallJava(String requiredVersion) {
-        int requiredJavaMinor;
-        if (requiredVersion.contains(".")) {
-            List<String> requiredVersionParts = Splitter.on(".").splitToList(requiredVersion);
-            requiredJavaMinor = Integer.valueOf(requiredVersionParts.get(1));
-        } else if (requiredVersion.length() == 1) {
-            requiredJavaMinor = Integer.valueOf(requiredVersion);
-        } else {
-            log.error("java version required {} is not supported", requiredVersion);
-            throw new IllegalArgumentException("Required java version " + requiredVersion + " not supported");
-        }
-        Optional<String> installedJavaVersion = getInstalledJavaVersion();
-        if (installedJavaVersion.isPresent()) {
-            List<String> installedVersionParts = Splitter.on(".").splitToList(installedJavaVersion.get());
-            int javaMajor = Integer.valueOf(installedVersionParts.get(0));
-            int javaMinor = Integer.valueOf(installedVersionParts.get(1));
-            if (javaMajor == 1 && javaMinor >= requiredJavaMinor) {
-                log.debug("Java {} already installed at {}@{}", new Object[]{installedJavaVersion.get(), getEntity(), getLocation()});
-                return true;
-            }
-        }
-        return tryJavaInstall(requiredVersion, BashCommands.installJava(requiredJavaMinor)) == 0;
-    }
-
-    protected int tryJavaInstall(String version, String command) {
-        getLocation().acquireMutex("installing", "installing Java at " + getLocation());
-        try {
-            log.debug("Installing Java {} at {}@{}", new Object[]{version, getEntity(), getLocation()});
-            ProcessTaskFactory<Integer> taskFactory = SshTasks.newSshExecTaskFactory(getLocation(), command)
-                    .summary("install java ("+version+")")
-                    .configure(ShellTool.PROP_EXEC_ASYNC, true);
-            ProcessTaskWrapper<Integer> installCommand = Entities.submit(getEntity(), taskFactory);
-            int result = installCommand.get();
-            if (result != 0) {
-                log.warn("Installation of Java {} failed at {}@{}: {}",
-                        new Object[]{version, getEntity(), getLocation(), installCommand.getStderr()});
-            }
-            return result;
-        } finally {
-            getLocation().releaseMutex("installing");
-        }
-    }
-
-    /**
-    * @deprecated since 0.7.0; instead use {@link #getInstalledJavaVersion()}
-    */
-    @Deprecated
-    protected Optional<String> getCurrentJavaVersion() {
-        return getInstalledJavaVersion();
-    }
-
-    /**
-     * Checks for the version of Java installed on the entity's location over SSH.
-     * @return An Optional containing the version portion of `java -version`, or absent if no Java found.
-     */
-    protected Optional<String> getInstalledJavaVersion() {
-        log.debug("Checking Java version at {}@{}", getEntity(), getLocation());
-        // sed gets stdin like 'java version "1.7.0_45"'
-        ProcessTaskWrapper<Integer> versionCommand = Entities.submit(getEntity(), SshTasks.newSshExecTaskFactory(
-                getLocation(), "java -version 2>&1 | grep \" version\" | sed 's/.*\"\\(.*\\).*\"/\\1/'"));
-        versionCommand.get();
-        String stdOut = versionCommand.getStdout().trim();
-        if (!Strings.isBlank(stdOut)) {
-            log.debug("Found Java version at {}@{}: {}", new Object[] {getEntity(), getLocation(), stdOut});
-            return Optional.of(stdOut);
-        } else {
-            log.debug("Found no Java installed at {}@{}", getEntity(), getLocation());
-            return Optional.absent();
-        }
-    }
-
-    /**
-     * Answers one of "OpenJDK", "Oracle", or other vendor info.
-     */
-    protected Optional<String> getCurrentJavaVendor() {
-        // TODO Also handle IBM jvm
-        log.debug("Checking Java vendor at {}@{}", getEntity(), getLocation());
-        ProcessTaskWrapper<Integer> versionCommand = Entities.submit(getEntity(), SshTasks.newSshExecTaskFactory(
-                getLocation(), "java -version 2>&1 | awk 'NR==2 {print $1}'"));
-        versionCommand.get();
-        String stdOut = versionCommand.getStdout().trim();
-        if (Strings.isBlank(stdOut)) {
-            log.debug("Found no Java installed at {}@{}", getEntity(), getLocation());
-            return Optional.absent();
-        } else if ("Java(TM)".equals(stdOut)) {
-            log.debug("Found Java version at {}@{}: {}", new Object[] {getEntity(), getLocation(), stdOut});
-            return Optional.of("Oracle");
-        } else {
-            return Optional.of(stdOut);
-        }
-    }
-
-    /**
-     * Checks for Java 6 or 7, installing Java 7 if neither are found. Override this method to
-     * check for and install specific versions of Java.
-     *
-     * @see #checkForAndInstallJava(String)
-     */
-    public boolean installJava() {
-        if (entity instanceof UsesJava) {
-            String version = entity.getConfig(UsesJava.JAVA_VERSION_REQUIRED);
-            return checkForAndInstallJava(version);
-        }
-        // by default it installs jdk7
-        return checkForAndInstallJava("1.7");
-    }
-
-    public void installJmxSupport() {
-        if (isJmxEnabled()) {
-            newScript("JMX_SETUP_PREINSTALL").body.append("mkdir -p "+getRunDir()).execute();
-            new JmxSupport(getEntity(), getRunDir()).install();
-        }
-    }
-
-    public void checkJavaHostnameBug() {
-        checkNoHostnameBug();
-
-        try {
-            ProcessTaskWrapper<Integer> hostnameTask = DynamicTasks.queue(SshEffectorTasks.ssh("echo FOREMARKER; hostname -f; echo AFTMARKER")).block();
-            String stdout = Strings.getFragmentBetween(hostnameTask.getStdout(), "FOREMARKER", "AFTMARKER");
-            if (hostnameTask.getExitCode() == 0 && Strings.isNonBlank(stdout)) {
-                String hostname = stdout.trim();
-                Integer len = hostname.length();
-                if (len > 63) {
-                    // likely to cause a java crash due to java bug 7089443 -- set a new short hostname
-                    // http://mail.openjdk.java.net/pipermail/net-dev/2012-July/004603.html
-                    String newHostname = "br-"+getEntity().getId().toLowerCase();
-                    log.info("Detected likelihood of Java hostname bug with hostname length "+len+" for "+getEntity()+"; renaming "+getMachine()+"  to hostname "+newHostname);
-                    DynamicTasks.queue(SshEffectorTasks.ssh(BashCommands.setHostname(newHostname, null))).block();
-                }
-            } else {
-                log.debug("Hostname length could not be determined for location "+EffectorTasks.findSshMachine()+"; not doing Java hostname bug check");
-            }
-        } catch (Exception e) {
-            Exceptions.propagateIfFatal(e);
-            log.warn("Error checking/fixing Java hostname bug (continuing): "+e, e);
-        }
-    }
-
-    @Override
-    public void setup() {
-        DynamicTasks.queue("install java", new Runnable() { public void run() {
-            installJava();
-        }});
-
-        // TODO check java version
-
-        if (getEntity().getConfig(UsesJava.CHECK_JAVA_HOSTNAME_BUG)) {
-            DynamicTasks.queue("check java hostname bug", new Runnable() { public void run() {
-                checkJavaHostnameBug(); }});
-        }
-    }
-
-    @Override
-    public void copyRuntimeResources() {
-        super.copyRuntimeResources();
-
-        if (isJmxEnabled()) {
-            DynamicTasks.queue("install jmx", new Runnable() { public void run() {
-                installJmxSupport(); }});
-        }
-    }
-
-}


[54/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/winrm/WinRmMachineLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/winrm/WinRmMachineLocation.java b/core/src/main/java/org/apache/brooklyn/location/winrm/WinRmMachineLocation.java
new file mode 100644
index 0000000..fb68c77
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/winrm/WinRmMachineLocation.java
@@ -0,0 +1,362 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.winrm;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.net.InetAddress;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.api.location.MachineDetails;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.OsDetails;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.commons.codec.binary.Base64;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Charsets;
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.net.HostAndPort;
+import com.google.common.reflect.TypeToken;
+
+import org.apache.brooklyn.location.access.PortForwardManager;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.stream.Streams;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+
+import io.cloudsoft.winrm4j.winrm.WinRmTool;
+import io.cloudsoft.winrm4j.winrm.WinRmToolResponse;
+
+public class WinRmMachineLocation extends AbstractLocation implements MachineLocation {
+
+    private static final Logger LOG = LoggerFactory.getLogger(WinRmMachineLocation.class);
+
+    // FIXME Respect `port` config when using {@link WinRmTool}
+    public static final ConfigKey<Integer> WINRM_PORT = ConfigKeys.newIntegerConfigKey(
+            "port",
+            "WinRM port to use when connecting to the remote machine",
+            5985);
+    
+    // TODO merge with {link SshTool#PROP_USER} and {@link SshMachineLocation#user}
+    public static final ConfigKey<String> USER = ConfigKeys.newStringConfigKey("user",
+            "Username to use when connecting to the remote machine");
+
+    // TODO merge with {link SshTool#PROP_PASSWORD}
+    public static final ConfigKey<String> PASSWORD = ConfigKeys.newStringConfigKey("password",
+            "Password to use when connecting to the remote machine");
+
+    public static final ConfigKey<Integer> COPY_FILE_CHUNK_SIZE_BYTES = ConfigKeys.newIntegerConfigKey("windows.copy.file.size.bytes",
+            "Size of file chunks (in bytes) to be used when copying a file to the remote server", 1024);
+
+     public static final ConfigKey<InetAddress> ADDRESS = ConfigKeys.newConfigKey(
+            InetAddress.class,
+            "address",
+            "Address of the remote machine");
+
+    public static final ConfigKey<Integer> EXECUTION_ATTEMPTS = ConfigKeys.newIntegerConfigKey(
+            "windows.exec.attempts",
+            "Number of attempts to execute a remote command",
+            1);
+    
+    // TODO See SshTool#PROP_SSH_TRIES, where it was called "sshTries"; remove duplication? Merge into one well-named thing?
+    public static final ConfigKey<Integer> EXEC_TRIES = ConfigKeys.newIntegerConfigKey(
+            "execTries", 
+            "Max number of times to attempt WinRM operations", 
+            10);
+
+    public static final ConfigKey<Iterable<String>> PRIVATE_ADDRESSES = ConfigKeys.newConfigKey(
+            new TypeToken<Iterable<String>>() {},
+            "privateAddresses",
+            "Private addresses of this machine, e.g. those within the private network", 
+            null);
+
+    public static final ConfigKey<Map<Integer, String>> TCP_PORT_MAPPINGS = ConfigKeys.newConfigKey(
+            new TypeToken<Map<Integer, String>>() {},
+            "tcpPortMappings",
+            "NAT'ed ports, giving the mapping from private TCP port to a public host:port", 
+            null);
+
+    @Override
+    public InetAddress getAddress() {
+        return getConfig(ADDRESS);
+    }
+
+    @Override
+    public OsDetails getOsDetails() {
+        return null;
+    }
+
+    @Override
+    public MachineDetails getMachineDetails() {
+        return null;
+    }
+
+    @Nullable
+    @Override
+    public String getHostname() {
+        InetAddress address = getAddress();
+        return (address != null) ? address.getHostAddress() : null;
+    }
+
+    @Nullable
+    protected String getHostAndPort() {
+        String host = getHostname();
+        return (host == null) ? null : host + ":" + config().get(WINRM_PORT);
+    }
+
+    @Override
+    public Set<String> getPublicAddresses() {
+        InetAddress address = getAddress();
+        return (address == null) ? ImmutableSet.<String>of() : ImmutableSet.of(address.getHostAddress());
+    }
+    
+    @Override
+    public Set<String> getPrivateAddresses() {
+        Iterable<String> result = getConfig(PRIVATE_ADDRESSES);
+        return (result == null) ? ImmutableSet.<String>of() : ImmutableSet.copyOf(result);
+    }
+
+    public WinRmToolResponse executeScript(String script) {
+        return executeScript(ImmutableList.of(script));
+    }
+
+    public WinRmToolResponse executeScript(List<String> script) {
+        int execTries = getRequiredConfig(EXEC_TRIES);
+        Collection<Throwable> exceptions = Lists.newArrayList();
+        for (int i = 0; i < execTries; i++) {
+            try {
+                return executeScriptNoRetry(script);
+            } catch (Exception e) {
+                Exceptions.propagateIfFatal(e);
+                if (i == (execTries+1)) {
+                    LOG.info("Propagating WinRM exception (attempt "+(i+1)+" of "+execTries+")", e);
+                } else if (i == 0) {
+                    LOG.warn("Ignoring WinRM exception and retrying (attempt "+(i+1)+" of "+execTries+")", e);
+                } else {
+                    LOG.debug("Ignoring WinRM exception and retrying (attempt "+(i+1)+" of "+execTries+")", e);
+                }
+                exceptions.add(e);
+            }
+        }
+        throw Exceptions.propagate("failed to execute shell script", exceptions);
+    }
+
+    protected WinRmToolResponse executeScriptNoRetry(List<String> script) {
+        WinRmTool winRmTool = WinRmTool.connect(getHostAndPort(), getUser(), getPassword());
+        WinRmToolResponse response = winRmTool.executeScript(script);
+        return response;
+    }
+
+    public WinRmToolResponse executePsScript(String psScript) {
+        return executePsScript(ImmutableList.of(psScript));
+    }
+
+    public WinRmToolResponse executePsScript(List<String> psScript) {
+        int execTries = getRequiredConfig(EXEC_TRIES);
+        Collection<Throwable> exceptions = Lists.newArrayList();
+        for (int i = 0; i < execTries; i++) {
+            try {
+                return executePsScriptNoRetry(psScript);
+            } catch (Exception e) {
+                Exceptions.propagateIfFatal(e);
+                if (i == (execTries+1)) {
+                    LOG.info("Propagating WinRM exception (attempt "+(i+1)+" of "+execTries+")", e);
+                } else if (i == 0) {
+                    LOG.warn("Ignoring WinRM exception and retrying after 5 seconds (attempt "+(i+1)+" of "+execTries+")", e);
+                    Time.sleep(Duration.FIVE_SECONDS);
+                } else {
+                    LOG.debug("Ignoring WinRM exception and retrying after 5 seconds (attempt "+(i+1)+" of "+execTries+")", e);
+                    Time.sleep(Duration.FIVE_SECONDS);
+                }
+                exceptions.add(e);
+            }
+        }
+        throw Exceptions.propagate("failed to execute powershell script", exceptions);
+    }
+
+    public WinRmToolResponse executePsScriptNoRetry(List<String> psScript) {
+        WinRmTool winRmTool = WinRmTool.connect(getHostAndPort(), getUser(), getPassword());
+        WinRmToolResponse response = winRmTool.executePs(psScript);
+        return response;
+    }
+
+    public int copyTo(File source, String destination) {
+        FileInputStream sourceStream = null;
+        try {
+            sourceStream = new FileInputStream(source);
+            return copyTo(sourceStream, destination);
+        } catch (FileNotFoundException e) {
+            throw Exceptions.propagate(e);
+        } finally {
+            if (sourceStream != null) {
+                Streams.closeQuietly(sourceStream);
+            }
+        }
+    }
+
+    public int copyTo(InputStream source, String destination) {
+        executePsScript(ImmutableList.of("rm -ErrorAction SilentlyContinue " + destination));
+        try {
+            int chunkSize = getConfig(COPY_FILE_CHUNK_SIZE_BYTES);
+            byte[] inputData = new byte[chunkSize];
+            int bytesRead;
+            int expectedFileSize = 0;
+            while ((bytesRead = source.read(inputData)) > 0) {
+                byte[] chunk;
+                if (bytesRead == chunkSize) {
+                    chunk = inputData;
+                } else {
+                    chunk = Arrays.copyOf(inputData, bytesRead);
+                }
+                executePsScript(ImmutableList.of("If ((!(Test-Path " + destination + ")) -or ((Get-Item '" + destination + "').length -eq " +
+                        expectedFileSize + ")) {Add-Content -Encoding Byte -path " + destination +
+                        " -value ([System.Convert]::FromBase64String(\"" + new String(Base64.encodeBase64(chunk)) + "\"))}"));
+                expectedFileSize += bytesRead;
+            }
+
+            return 0;
+        } catch (java.io.IOException e) {
+            throw Exceptions.propagate(e);
+        }
+    }
+
+    @Override
+    public void init() {
+        super.init();
+
+        // Register any pre-existing port-mappings with the PortForwardManager
+        Map<Integer, String> tcpPortMappings = getConfig(TCP_PORT_MAPPINGS);
+        if (tcpPortMappings != null) {
+            PortForwardManager pfm = (PortForwardManager) getManagementContext().getLocationRegistry().resolve("portForwardManager(scope=global)");
+            for (Map.Entry<Integer, String> entry : tcpPortMappings.entrySet()) {
+                int targetPort = entry.getKey();
+                HostAndPort publicEndpoint = HostAndPort.fromString(entry.getValue());
+                if (!publicEndpoint.hasPort()) {
+                    throw new IllegalArgumentException("Invalid portMapping ('"+entry.getValue()+"') for port "+targetPort+" in machine "+this);
+                }
+                pfm.associate(publicEndpoint.getHostText(), publicEndpoint, this, targetPort);
+            }
+        }
+    }
+    public String getUser() {
+        return config().get(USER);
+    }
+
+    private String getPassword() {
+        return config().get(PASSWORD);
+    }
+
+    private <T> T getRequiredConfig(ConfigKey<T> key) {
+        return checkNotNull(getConfig(key), "key %s must be set", key);
+    }
+    
+    public static String getDefaultUserMetadataString() {
+        // Using an encoded command obviates the need to escape
+        String unencodePowershell = Joiner.on("\r\n").join(ImmutableList.of(
+                // Allow TS connections
+                "$RDP = Get-WmiObject -Class Win32_TerminalServiceSetting -ComputerName $env:computername -Namespace root\\CIMV2\\TerminalServices -Authentication PacketPrivacy",
+                "$RDP.SetAllowTSConnections(1,1)",
+                "Set-ExecutionPolicy Unrestricted -Force",
+                // Set unlimited values for remote execution limits
+                "Set-Item WSMan:\\localhost\\Shell\\MaxConcurrentUsers 100",
+                "Set-Item WSMan:\\localhost\\Shell\\MaxMemoryPerShellMB 0",
+                "Set-Item WSMan:\\localhost\\Shell\\MaxProcessesPerShell 0",
+                "Set-Item WSMan:\\localhost\\Shell\\MaxShellsPerUser 0",
+                "New-ItemProperty \"HKLM:\\System\\CurrentControlSet\\Control\\LSA\" -Name \"SuppressExtendedProtection\" -Value 1 -PropertyType \"DWord\"",
+                // The following allows scripts to re-authenticate with local credential - this is required
+                // as certain operations cannot be performed with remote credentials
+                "$allowed = @('WSMAN/*')",
+                "$key = 'hklm:\\SOFTWARE\\Policies\\Microsoft\\Windows\\CredentialsDelegation'",
+                "if (!(Test-Path $key)) {",
+                "    md $key",
+                "}",
+                "New-ItemProperty -Path $key -Name AllowFreshCredentials -Value 1 -PropertyType Dword -Force",
+                "New-ItemProperty -Path $key -Name AllowFreshCredentialsWhenNTLMOnly -Value 1 -PropertyType Dword -Force",
+                "$credKey = Join-Path $key 'AllowFreshCredentials'",
+                "if (!(Test-Path $credKey)) {",
+                "    md $credkey",
+                "}",
+                "$ntlmKey = Join-Path $key 'AllowFreshCredentialsWhenNTLMOnly'",
+                "if (!(Test-Path $ntlmKey)) {",
+                "    md $ntlmKey",
+                "}",
+                "$i = 1",
+                "$allowed |% {",
+                "    # Script does not take into account existing entries in this key",
+                "    New-ItemProperty -Path $credKey -Name $i -Value $_ -PropertyType String -Force",
+                "    New-ItemProperty -Path $ntlmKey -Name $i -Value $_ -PropertyType String -Force",
+                "    $i++",
+                "}"
+        ));
+
+        String encoded = new String(Base64.encodeBase64(unencodePowershell.getBytes(Charsets.UTF_16LE)));
+        return "winrm quickconfig -q & " +
+                "winrm set winrm/config/service/auth @{Basic=\"true\"} & " +
+                "winrm set winrm/config/service/auth @{CredSSP=\"true\"} & " +
+                "winrm set winrm/config/client/auth @{CredSSP=\"true\"} & " +
+                "winrm set winrm/config/client @{AllowUnencrypted=\"true\"} & " +
+                "winrm set winrm/config/service @{AllowUnencrypted=\"true\"} & " +
+                "winrm set winrm/config/winrs @{MaxConcurrentUsers=\"100\"} & " +
+                "winrm set winrm/config/winrs @{MaxMemoryPerShellMB=\"0\"} & " +
+                "winrm set winrm/config/winrs @{MaxProcessesPerShell=\"0\"} & " +
+                "winrm set winrm/config/winrs @{MaxShellsPerUser=\"0\"} & " +
+                "netsh advfirewall firewall add rule name=RDP dir=in protocol=tcp localport=3389 action=allow profile=any & " +
+                "netsh advfirewall firewall add rule name=WinRM dir=in protocol=tcp localport=5985 action=allow profile=any & " +
+                "powershell -EncodedCommand " + encoded;
+        /* TODO: Find out why scripts with new line characters aren't working on AWS. The following appears as if it *should*
+           work but doesn't - the script simply isn't run. By connecting to the machine via RDP, you can get the script
+           from 'http://169.254.169.254/latest/user-data', and running it at the command prompt works, but for some
+           reason the script isn't run when the VM is provisioned
+        */
+//        return Joiner.on("\r\n").join(ImmutableList.of(
+//                "winrm quickconfig -q",
+//                "winrm set winrm/config/service/auth @{Basic=\"true\"}",
+//                "winrm set winrm/config/client @{AllowUnencrypted=\"true\"}",
+//                "winrm set winrm/config/service @{AllowUnencrypted=\"true\"}",
+//                "netsh advfirewall firewall add rule name=RDP dir=in protocol=tcp localport=3389 action=allow profile=any",
+//                "netsh advfirewall firewall add rule name=WinRM dir=in protocol=tcp localport=5985 action=allow profile=any",
+//                // Using an encoded command necessitates the need to escape. The unencoded command is as follows:
+//                // $RDP = Get-WmiObject -Class Win32_TerminalServiceSetting -ComputerName $env:computername -Namespace root\CIMV2\TerminalServices -Authentication PacketPrivacy
+//                // $Result = $RDP.SetAllowTSConnections(1,1)
+//                "powershell -EncodedCommand JABSAEQAUAAgAD0AIABHAGUAdAAtAFcAbQBpAE8AYgBqAGUAYwB0ACAALQBDAGwAYQBzAHMAI" +
+//                        "ABXAGkAbgAzADIAXwBUAGUAcgBtAGkAbgBhAGwAUwBlAHIAdgBpAGMAZQBTAGUAdAB0AGkAbgBnACAALQBDAG8AbQBwA" +
+//                        "HUAdABlAHIATgBhAG0AZQAgACQAZQBuAHYAOgBjAG8AbQBwAHUAdABlAHIAbgBhAG0AZQAgAC0ATgBhAG0AZQBzAHAAY" +
+//                        "QBjAGUAIAByAG8AbwB0AFwAQwBJAE0AVgAyAFwAVABlAHIAbQBpAG4AYQBsAFMAZQByAHYAaQBjAGUAcwAgAC0AQQB1A" +
+//                        "HQAaABlAG4AdABpAGMAYQB0AGkAbwBuACAAUABhAGMAawBlAHQAUAByAGkAdgBhAGMAeQANAAoAJABSAGUAcwB1AGwAd" +
+//                        "AAgAD0AIAAkAFIARABQAC4AUwBlAHQAQQBsAGwAbwB3AFQAUwBDAG8AbgBuAGUAYwB0AGkAbwBuAHMAKAAxACwAMQApAA=="
+//        ));
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/sensor/core/HttpRequestSensor.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/sensor/core/HttpRequestSensor.java b/core/src/main/java/org/apache/brooklyn/sensor/core/HttpRequestSensor.java
index 2277d49..b786a3e 100644
--- a/core/src/main/java/org/apache/brooklyn/sensor/core/HttpRequestSensor.java
+++ b/core/src/main/java/org/apache/brooklyn/sensor/core/HttpRequestSensor.java
@@ -26,9 +26,6 @@ import org.apache.brooklyn.api.internal.EntityLocal;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.effector.core.AddSensor;
-import org.apache.brooklyn.entity.java.JmxAttributeSensor;
-import org.apache.brooklyn.entity.software.ssh.SshCommandSensor;
-import org.apache.brooklyn.sensor.core.HttpRequestSensor;
 import org.apache.brooklyn.sensor.feed.http.HttpFeed;
 import org.apache.brooklyn.sensor.feed.http.HttpPollConfig;
 import org.apache.brooklyn.sensor.feed.http.HttpValueFunctions;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/sensor/core/PortAttributeSensorAndConfigKey.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/sensor/core/PortAttributeSensorAndConfigKey.java b/core/src/main/java/org/apache/brooklyn/sensor/core/PortAttributeSensorAndConfigKey.java
index 58704bd..8102cb7 100644
--- a/core/src/main/java/org/apache/brooklyn/sensor/core/PortAttributeSensorAndConfigKey.java
+++ b/core/src/main/java/org/apache/brooklyn/sensor/core/PortAttributeSensorAndConfigKey.java
@@ -31,7 +31,7 @@ import org.apache.brooklyn.api.sensor.Sensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.internal.BrooklynInitialization;
 import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.location.basic.Locations;
+import org.apache.brooklyn.location.core.Locations;
 import org.apache.brooklyn.util.core.flags.TypeCoercions;
 import org.apache.brooklyn.util.guava.Maybe;
 import org.slf4j.Logger;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/sensor/feed/ssh/SshFeed.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/sensor/feed/ssh/SshFeed.java b/core/src/main/java/org/apache/brooklyn/sensor/feed/ssh/SshFeed.java
index 880e56c..4730db7 100644
--- a/core/src/main/java/org/apache/brooklyn/sensor/feed/ssh/SshFeed.java
+++ b/core/src/main/java/org/apache/brooklyn/sensor/feed/ssh/SshFeed.java
@@ -34,9 +34,9 @@ import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.location.basic.Machines;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.Locations;
+import org.apache.brooklyn.location.core.Machines;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.AbstractFeed;
 import org.apache.brooklyn.sensor.feed.AttributePollHandler;
 import org.apache.brooklyn.sensor.feed.DelegatingPollHandler;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/sensor/feed/ssh/SshPollValue.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/sensor/feed/ssh/SshPollValue.java b/core/src/main/java/org/apache/brooklyn/sensor/feed/ssh/SshPollValue.java
index a2d5178..8f1885d 100644
--- a/core/src/main/java/org/apache/brooklyn/sensor/feed/ssh/SshPollValue.java
+++ b/core/src/main/java/org/apache/brooklyn/sensor/feed/ssh/SshPollValue.java
@@ -20,7 +20,7 @@ package org.apache.brooklyn.sensor.feed.ssh;
 
 import javax.annotation.Nullable;
 
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 public class SshPollValue {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/sensor/feed/windows/WindowsPerformanceCounterFeed.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/sensor/feed/windows/WindowsPerformanceCounterFeed.java b/core/src/main/java/org/apache/brooklyn/sensor/feed/windows/WindowsPerformanceCounterFeed.java
index c0ae91c..7c485b8 100644
--- a/core/src/main/java/org/apache/brooklyn/sensor/feed/windows/WindowsPerformanceCounterFeed.java
+++ b/core/src/main/java/org/apache/brooklyn/sensor/feed/windows/WindowsPerformanceCounterFeed.java
@@ -44,7 +44,7 @@ import org.apache.brooklyn.effector.core.EffectorTasks;
 import org.apache.brooklyn.entity.core.EntityInternal;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.WinRmMachineLocation;
+import org.apache.brooklyn.location.winrm.WinRmMachineLocation;
 import org.apache.brooklyn.sensor.core.Sensors;
 import org.apache.brooklyn.sensor.feed.AbstractFeed;
 import org.apache.brooklyn.sensor.feed.PollHandler;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/util/core/ResourceUtils.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/util/core/ResourceUtils.java b/core/src/main/java/org/apache/brooklyn/util/core/ResourceUtils.java
index 031198c..d568cc3 100644
--- a/core/src/main/java/org/apache/brooklyn/util/core/ResourceUtils.java
+++ b/core/src/main/java/org/apache/brooklyn/util/core/ResourceUtils.java
@@ -53,7 +53,7 @@ import org.apache.http.client.methods.HttpGet;
 import org.apache.http.util.EntityUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.http.HttpTool;
 import org.apache.brooklyn.util.core.http.HttpTool.HttpClientBuilder;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/util/core/file/ArchiveTasks.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/util/core/file/ArchiveTasks.java b/core/src/main/java/org/apache/brooklyn/util/core/file/ArchiveTasks.java
index ad79d9e..d73526e 100644
--- a/core/src/main/java/org/apache/brooklyn/util/core/file/ArchiveTasks.java
+++ b/core/src/main/java/org/apache/brooklyn/util/core/file/ArchiveTasks.java
@@ -22,7 +22,7 @@ import java.util.Map;
 
 import org.apache.brooklyn.api.mgmt.TaskAdaptable;
 import org.apache.brooklyn.api.mgmt.TaskFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.ResourceUtils;
 import org.apache.brooklyn.util.core.task.Tasks;
 import org.apache.brooklyn.util.net.Urls;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/util/core/file/ArchiveUtils.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/util/core/file/ArchiveUtils.java b/core/src/main/java/org/apache/brooklyn/util/core/file/ArchiveUtils.java
index 74a95cb..b10d7ae 100644
--- a/core/src/main/java/org/apache/brooklyn/util/core/file/ArchiveUtils.java
+++ b/core/src/main/java/org/apache/brooklyn/util/core/file/ArchiveUtils.java
@@ -30,7 +30,7 @@ import java.util.Set;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.ResourceUtils;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshFetchTaskFactory.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshFetchTaskFactory.java b/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshFetchTaskFactory.java
index 5e180bd..707dd58 100644
--- a/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshFetchTaskFactory.java
+++ b/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshFetchTaskFactory.java
@@ -21,7 +21,7 @@ package org.apache.brooklyn.util.core.task.ssh;
 import org.apache.brooklyn.api.mgmt.TaskFactory;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 
 // cannot be (cleanly) instantiated due to nested generic self-referential type; however trivial subclasses do allow it 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshFetchTaskWrapper.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshFetchTaskWrapper.java b/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshFetchTaskWrapper.java
index 6dcfc4d..c667d03 100644
--- a/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshFetchTaskWrapper.java
+++ b/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshFetchTaskWrapper.java
@@ -26,7 +26,7 @@ import org.apache.brooklyn.api.mgmt.Task;
 import org.apache.brooklyn.api.mgmt.TaskWrapper;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.io.FilenameUtils;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 import org.apache.brooklyn.util.core.task.TaskBuilder;
 import org.apache.brooklyn.util.core.task.Tasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshPutTaskFactory.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshPutTaskFactory.java b/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshPutTaskFactory.java
index 9a93778..7909df5 100644
--- a/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshPutTaskFactory.java
+++ b/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshPutTaskFactory.java
@@ -24,7 +24,7 @@ import java.io.Reader;
 import org.apache.brooklyn.api.mgmt.TaskFactory;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.stream.KnownSizeInputStream;
 import org.apache.brooklyn.util.stream.ReaderInputStream;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshPutTaskStub.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshPutTaskStub.java b/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshPutTaskStub.java
index e838ad1..63ee96d 100644
--- a/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshPutTaskStub.java
+++ b/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshPutTaskStub.java
@@ -20,7 +20,7 @@ package org.apache.brooklyn.util.core.task.ssh;
 
 import java.io.InputStream;
 
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 
 import com.google.common.base.Supplier;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshTasks.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshTasks.java b/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshTasks.java
index 49cab10..53d5e71 100644
--- a/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshTasks.java
+++ b/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/SshTasks.java
@@ -35,9 +35,9 @@ import org.apache.brooklyn.core.config.ConfigUtils;
 import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.AbstractLocation;
-import org.apache.brooklyn.location.basic.LocationInternal;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.ResourceUtils;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 import org.apache.brooklyn.util.core.internal.ssh.SshTool;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/internal/AbstractSshExecTaskFactory.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/internal/AbstractSshExecTaskFactory.java b/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/internal/AbstractSshExecTaskFactory.java
index 62556f3..444f9f4 100644
--- a/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/internal/AbstractSshExecTaskFactory.java
+++ b/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/internal/AbstractSshExecTaskFactory.java
@@ -20,7 +20,7 @@ package org.apache.brooklyn.util.core.task.ssh.internal;
 
 import com.google.common.base.Preconditions;
 
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 import org.apache.brooklyn.util.core.task.system.ProcessTaskFactory;
 import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/internal/PlainSshExecTaskFactory.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/internal/PlainSshExecTaskFactory.java b/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/internal/PlainSshExecTaskFactory.java
index a6810a3..92def17 100644
--- a/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/internal/PlainSshExecTaskFactory.java
+++ b/core/src/main/java/org/apache/brooklyn/util/core/task/ssh/internal/PlainSshExecTaskFactory.java
@@ -20,7 +20,7 @@ package org.apache.brooklyn.util.core.task.ssh.internal;
 
 import java.util.List;
 
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
 
 import com.google.common.base.Function;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/util/core/task/system/ProcessTaskFactory.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/util/core/task/system/ProcessTaskFactory.java b/core/src/main/java/org/apache/brooklyn/util/core/task/system/ProcessTaskFactory.java
index 0fd89cc..8042cc2 100644
--- a/core/src/main/java/org/apache/brooklyn/util/core/task/system/ProcessTaskFactory.java
+++ b/core/src/main/java/org/apache/brooklyn/util/core/task/system/ProcessTaskFactory.java
@@ -22,7 +22,7 @@ import java.util.Map;
 
 import org.apache.brooklyn.api.mgmt.TaskFactory;
 import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.internal.ssh.SshTool;
 import org.apache.brooklyn.util.core.task.system.ProcessTaskStub.ScriptReturnType;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/util/core/task/system/ProcessTaskStub.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/util/core/task/system/ProcessTaskStub.java b/core/src/main/java/org/apache/brooklyn/util/core/task/system/ProcessTaskStub.java
index 5dd1f1b..5514ccf 100644
--- a/core/src/main/java/org/apache/brooklyn/util/core/task/system/ProcessTaskStub.java
+++ b/core/src/main/java/org/apache/brooklyn/util/core/task/system/ProcessTaskStub.java
@@ -22,7 +22,7 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 import org.apache.brooklyn.util.text.Strings;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/util/core/task/system/internal/AbstractProcessTaskFactory.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/util/core/task/system/internal/AbstractProcessTaskFactory.java b/core/src/main/java/org/apache/brooklyn/util/core/task/system/internal/AbstractProcessTaskFactory.java
index 153dc59..6a98c4b 100644
--- a/core/src/main/java/org/apache/brooklyn/util/core/task/system/internal/AbstractProcessTaskFactory.java
+++ b/core/src/main/java/org/apache/brooklyn/util/core/task/system/internal/AbstractProcessTaskFactory.java
@@ -25,7 +25,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.task.TaskBuilder;
 import org.apache.brooklyn.util.core.task.system.ProcessTaskFactory;
 import org.apache.brooklyn.util.core.task.system.ProcessTaskStub;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/util/core/task/system/internal/ExecWithLoggingHelpers.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/util/core/task/system/internal/ExecWithLoggingHelpers.java b/core/src/main/java/org/apache/brooklyn/util/core/task/system/internal/ExecWithLoggingHelpers.java
index 064c740..e96dce9 100644
--- a/core/src/main/java/org/apache/brooklyn/util/core/task/system/internal/ExecWithLoggingHelpers.java
+++ b/core/src/main/java/org/apache/brooklyn/util/core/task/system/internal/ExecWithLoggingHelpers.java
@@ -27,7 +27,7 @@ import java.util.Map;
 
 import org.slf4j.Logger;
 import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 import org.apache.brooklyn.util.core.flags.TypeCoercions;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/util/core/task/system/internal/SystemProcessTaskFactory.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/util/core/task/system/internal/SystemProcessTaskFactory.java b/core/src/main/java/org/apache/brooklyn/util/core/task/system/internal/SystemProcessTaskFactory.java
index 2dd6fa9..ab87480 100644
--- a/core/src/main/java/org/apache/brooklyn/util/core/task/system/internal/SystemProcessTaskFactory.java
+++ b/core/src/main/java/org/apache/brooklyn/util/core/task/system/internal/SystemProcessTaskFactory.java
@@ -22,7 +22,7 @@ import java.io.File;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 import org.apache.brooklyn.util.core.internal.ssh.ShellTool;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/resources/META-INF/services/org.apache.brooklyn.api.location.LocationResolver
----------------------------------------------------------------------
diff --git a/core/src/main/resources/META-INF/services/org.apache.brooklyn.api.location.LocationResolver b/core/src/main/resources/META-INF/services/org.apache.brooklyn.api.location.LocationResolver
index ec34011..ec64955 100644
--- a/core/src/main/resources/META-INF/services/org.apache.brooklyn.api.location.LocationResolver
+++ b/core/src/main/resources/META-INF/services/org.apache.brooklyn.api.location.LocationResolver
@@ -16,12 +16,12 @@
 # specific language governing permissions and limitations
 # under the License.
 #
-org.apache.brooklyn.location.basic.DefinedLocationByIdResolver
-org.apache.brooklyn.location.basic.NamedLocationResolver
-org.apache.brooklyn.location.basic.CatalogLocationResolver
-org.apache.brooklyn.location.basic.LocalhostLocationResolver
-org.apache.brooklyn.location.basic.ByonLocationResolver
-org.apache.brooklyn.location.basic.SingleMachineLocationResolver
-org.apache.brooklyn.location.basic.HostLocationResolver
-org.apache.brooklyn.location.basic.MultiLocationResolver
+org.apache.brooklyn.location.core.DefinedLocationByIdResolver
+org.apache.brooklyn.location.core.NamedLocationResolver
+org.apache.brooklyn.location.core.CatalogLocationResolver
+org.apache.brooklyn.location.localhost.LocalhostLocationResolver
+org.apache.brooklyn.location.byon.ByonLocationResolver
+org.apache.brooklyn.location.byon.SingleMachineLocationResolver
+org.apache.brooklyn.location.byon.HostLocationResolver
+org.apache.brooklyn.location.core.MultiLocationResolver
 org.apache.brooklyn.location.access.PortForwardManagerLocationResolver

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/config/MapListAndOtherStructuredConfigKeyTest.groovy
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/config/MapListAndOtherStructuredConfigKeyTest.groovy b/core/src/test/java/org/apache/brooklyn/core/config/MapListAndOtherStructuredConfigKeyTest.groovy
index df2167b..d3dc84b 100644
--- a/core/src/test/java/org/apache/brooklyn/core/config/MapListAndOtherStructuredConfigKeyTest.groovy
+++ b/core/src/test/java/org/apache/brooklyn/core/config/MapListAndOtherStructuredConfigKeyTest.groovy
@@ -32,7 +32,7 @@ import org.apache.brooklyn.core.config.SetConfigKey.SetModifications
 import org.apache.brooklyn.core.test.entity.TestApplication
 import org.apache.brooklyn.core.test.entity.TestEntity
 import org.apache.brooklyn.entity.core.Entities
-import org.apache.brooklyn.location.basic.SimulatedLocation
+import org.apache.brooklyn.location.core.SimulatedLocation
 import org.apache.brooklyn.sensor.core.DependentConfiguration
 import org.apache.brooklyn.util.collections.MutableMap
 import org.apache.brooklyn.util.core.task.DeferredSupplier

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerFileBasedTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerFileBasedTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerFileBasedTest.java
index 98f429d..85e0e29 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerFileBasedTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerFileBasedTest.java
@@ -20,7 +20,7 @@ package org.apache.brooklyn.core.mgmt.ha;
 
 import java.io.File;
 
-import org.apache.brooklyn.core.mgmt.rebind.persister.FileBasedObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.FileBasedObjectStore;
 import org.apache.brooklyn.util.os.Os;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.Test;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerInMemoryIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerInMemoryIntegrationTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerInMemoryIntegrationTest.java
index 6eea03b..a8c532a 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerInMemoryIntegrationTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerInMemoryIntegrationTest.java
@@ -18,8 +18,8 @@
  */
 package org.apache.brooklyn.core.mgmt.ha;
 
-import org.apache.brooklyn.core.mgmt.rebind.persister.InMemoryObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.InMemoryObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
 import org.apache.brooklyn.util.time.Duration;
 import org.apache.brooklyn.util.time.Time;
 import org.slf4j.Logger;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerInMemoryTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerInMemoryTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerInMemoryTest.java
index c82f9cf..6970c2e 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerInMemoryTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerInMemoryTest.java
@@ -28,8 +28,8 @@ import org.apache.brooklyn.api.location.NoMachinesAvailableException;
 import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
 import org.apache.brooklyn.core.mgmt.ha.HighAvailabilityManagerImpl;
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.mgmt.rebind.persister.InMemoryObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.InMemoryObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.core.test.entity.TestEntity;
 import org.apache.brooklyn.entity.core.EntityInternal;
@@ -38,8 +38,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.collect.Iterables;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerSplitBrainTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerSplitBrainTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerSplitBrainTest.java
index 71c7f94..fa90cbd 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerSplitBrainTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerSplitBrainTest.java
@@ -39,12 +39,12 @@ import org.apache.brooklyn.core.mgmt.ha.HighAvailabilityManagerImpl;
 import org.apache.brooklyn.core.mgmt.ha.ManagementPlaneSyncRecordPersisterToObjectStore;
 import org.apache.brooklyn.core.mgmt.ha.TestEntityFailingRebind.RebindException;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.InMemoryObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.ListeningObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
 import org.apache.brooklyn.core.mgmt.rebind.PersistenceExceptionHandlerImpl;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynMementoPersisterToObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.InMemoryObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.ListeningObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.entity.core.Entities;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerTestFixture.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerTestFixture.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerTestFixture.java
index 1fb71ed..5130a58 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerTestFixture.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerTestFixture.java
@@ -37,13 +37,13 @@ import org.apache.brooklyn.core.mgmt.ha.HighAvailabilityManagerImpl;
 import org.apache.brooklyn.core.mgmt.ha.ManagementPlaneSyncRecordDeltaImpl;
 import org.apache.brooklyn.core.mgmt.ha.ManagementPlaneSyncRecordPersisterToObjectStore;
 import org.apache.brooklyn.core.mgmt.ha.HighAvailabilityManagerImpl.PromotionListener;
+import org.apache.brooklyn.core.mgmt.ha.dto.BasicManagementNodeSyncRecord;
+import org.apache.brooklyn.core.mgmt.ha.dto.BasicManagementNodeSyncRecord.Builder;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
 import org.apache.brooklyn.core.mgmt.rebind.PersistenceExceptionHandlerImpl;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynMementoPersisterToObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.plane.dto.BasicManagementNodeSyncRecord;
-import org.apache.brooklyn.core.mgmt.rebind.plane.dto.BasicManagementNodeSyncRecord.Builder;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.test.Asserts;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HotStandbyTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HotStandbyTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HotStandbyTest.java
index 2d5b3d2..89a0889 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HotStandbyTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/HotStandbyTest.java
@@ -42,16 +42,16 @@ import org.apache.brooklyn.core.mgmt.ha.HighAvailabilityManagerImpl;
 import org.apache.brooklyn.core.mgmt.ha.ManagementPlaneSyncRecordPersisterToObjectStore;
 import org.apache.brooklyn.core.mgmt.internal.AbstractManagementContext;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.InMemoryObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.ListeningObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
 import org.apache.brooklyn.core.mgmt.rebind.PersistenceExceptionHandlerImpl;
 import org.apache.brooklyn.core.mgmt.rebind.RebindManagerImpl;
 import org.apache.brooklyn.core.mgmt.rebind.RebindTestFixture;
 import org.apache.brooklyn.core.mgmt.rebind.RebindFeedTest.MyEntityWithFunctionFeedImpl;
 import org.apache.brooklyn.core.mgmt.rebind.RebindFeedTest.MyEntityWithNewFeedsEachTimeImpl;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynMementoPersisterToObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.InMemoryObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.ListeningObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.core.test.entity.TestEntity;
@@ -70,7 +70,7 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation.LocalhostMachine;
 
 import com.google.common.collect.Iterables;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/ManagementPlaneSyncRecordPersisterInMemory.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/ManagementPlaneSyncRecordPersisterInMemory.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/ManagementPlaneSyncRecordPersisterInMemory.java
index 4696ce9..208a3d0 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/ManagementPlaneSyncRecordPersisterInMemory.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/ManagementPlaneSyncRecordPersisterInMemory.java
@@ -27,7 +27,7 @@ import org.apache.brooklyn.api.mgmt.ha.ManagementNodeSyncRecord;
 import org.apache.brooklyn.api.mgmt.ha.ManagementPlaneSyncRecord;
 import org.apache.brooklyn.api.mgmt.ha.ManagementPlaneSyncRecordPersister;
 import org.apache.brooklyn.core.mgmt.ha.ManagementPlaneSyncRecordPersisterToObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.InMemoryObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.InMemoryObjectStore;
 import org.apache.brooklyn.util.time.Duration;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/MasterChooserTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/MasterChooserTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/MasterChooserTest.java
index da3f826..1ffbe1b 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/MasterChooserTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/MasterChooserTest.java
@@ -28,7 +28,7 @@ import org.apache.brooklyn.api.mgmt.ha.ManagementNodeSyncRecord;
 import org.apache.brooklyn.core.BrooklynVersion;
 import org.apache.brooklyn.core.mgmt.ha.BasicMasterChooser.AlphabeticMasterChooser;
 import org.apache.brooklyn.core.mgmt.ha.BasicMasterChooser.ScoredRecord;
-import org.apache.brooklyn.core.mgmt.rebind.plane.dto.BasicManagementNodeSyncRecord;
+import org.apache.brooklyn.core.mgmt.ha.dto.BasicManagementNodeSyncRecord;
 import org.apache.brooklyn.entity.core.EntityFunctions;
 import org.apache.brooklyn.util.time.Duration;
 import org.testng.annotations.BeforeMethod;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/WarmStandbyTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/WarmStandbyTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/WarmStandbyTest.java
index d1c99d6..ab76e19 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/WarmStandbyTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/WarmStandbyTest.java
@@ -31,12 +31,12 @@ import org.apache.brooklyn.api.mgmt.ha.ManagementPlaneSyncRecordPersister;
 import org.apache.brooklyn.core.mgmt.ha.HighAvailabilityManagerImpl;
 import org.apache.brooklyn.core.mgmt.ha.ManagementPlaneSyncRecordPersisterToObjectStore;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.InMemoryObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.ListeningObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
 import org.apache.brooklyn.core.mgmt.rebind.PersistenceExceptionHandlerImpl;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynMementoPersisterToObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.InMemoryObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.ListeningObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.entity.core.Entities;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/internal/AccessManagerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/internal/AccessManagerTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/internal/AccessManagerTest.java
index 3fd4e24..74dbe56 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/internal/AccessManagerTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/internal/AccessManagerTest.java
@@ -36,7 +36,7 @@ import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableSet;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterFileBasedTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterFileBasedTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterFileBasedTest.java
new file mode 100644
index 0000000..e663f05
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterFileBasedTest.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import java.io.File;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.mgmt.persist.FileBasedObjectStore;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
+import org.apache.brooklyn.util.javalang.JavaClassNames;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.time.Duration;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.Test;
+
+/**
+ * @author Andrea Turli
+ */
+@Test
+public class BrooklynMementoPersisterFileBasedTest extends BrooklynMementoPersisterTestFixture {
+
+    protected File mementoDir;
+    
+    @Override
+    protected ManagementContext newPersistingManagementContext() {
+        mementoDir = Os.newTempDir(JavaClassNames.cleanSimpleClassName(this));
+        Os.deleteOnExitRecursively(mementoDir);
+        return RebindTestUtils.managementContextBuilder(classLoader, new FileBasedObjectStore(mementoDir))
+            .persistPeriod(Duration.millis(10)).buildStarted();
+    }
+
+    @Override
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        super.tearDown();
+        mementoDir = Os.deleteRecursively(mementoDir).asNullOrThrowing();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterInMemorySizeIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterInMemorySizeIntegrationTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterInMemorySizeIntegrationTest.java
new file mode 100644
index 0000000..0c49d12
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterInMemorySizeIntegrationTest.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import java.io.IOException;
+import java.util.concurrent.TimeoutException;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.mgmt.persist.ListeningObjectStore.RecordingTransactionListener;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+/** uses recorder to ensure not too much data is written */
+@Test
+public class BrooklynMementoPersisterInMemorySizeIntegrationTest extends BrooklynMementoPersisterTestFixture {
+
+    protected RecordingTransactionListener recorder;
+    
+    protected ManagementContext newPersistingManagementContext() {
+        recorder = new RecordingTransactionListener("in-mem-test-"+Identifiers.makeRandomId(4));
+        return RebindTestUtils.managementContextBuilder(classLoader, 
+            new ListeningObjectStore(new InMemoryObjectStore(), recorder))
+            .persistPeriod(Duration.millis(100)).buildStarted();
+    }
+    
+    public void testPersistenceVolumeFast() throws IOException, TimeoutException, InterruptedException {
+        doTestPersistenceVolume(50*1000, false, true);
+    }
+    @Test(groups="Integration",invocationCount=20)
+    public void testPersistenceVolumeFastManyTimes() throws IOException, TimeoutException, InterruptedException {
+        doTestPersistenceVolume(50*1000, false, true);
+    }
+    @Test(groups="Integration")
+    public void testPersistenceVolumeWaiting() throws IOException, TimeoutException, InterruptedException {
+        // by waiting we ensure there aren't extra writes going on
+        doTestPersistenceVolume(50*1000, true, true);
+    }
+    public void testPersistenceVolumeFastNoTrigger() throws IOException, TimeoutException, InterruptedException {
+        doTestPersistenceVolume(50*1000, false, false);
+    }
+    @Test(groups="Integration",invocationCount=20)
+    public void testPersistenceVolumeFastNoTriggerManyTimes() throws IOException, TimeoutException, InterruptedException {
+        doTestPersistenceVolume(50*1000, false, false);
+    }
+    
+    protected void doTestPersistenceVolume(int bigBlockSize, boolean forceDelay, boolean canTrigger) throws IOException, TimeoutException, InterruptedException {
+        if (forceDelay) Time.sleep(Duration.FIVE_SECONDS);
+        else recorder.blockUntilDataWrittenExceeds(512, Duration.FIVE_SECONDS);
+        localManagementContext.getRebindManager().waitForPendingComplete(Duration.FIVE_SECONDS, canTrigger);
+        
+        long out1 = recorder.getBytesOut();
+        int filesOut1 = recorder.getCountDataOut();
+        Assert.assertTrue(out1>512, "should have written at least 0.5k, only wrote "+out1);
+        Assert.assertTrue(out1<30*1000, "should have written less than 30k, wrote "+out1);
+        Assert.assertTrue(filesOut1<30, "should have written fewer than 30 files, wrote "+out1);
+        
+        ((EntityInternal)app).setAttribute(TestEntity.NAME, "hello world");
+        if (forceDelay) Time.sleep(Duration.FIVE_SECONDS);
+        else recorder.blockUntilDataWrittenExceeds(out1+10, Duration.FIVE_SECONDS);
+        localManagementContext.getRebindManager().waitForPendingComplete(Duration.FIVE_SECONDS, canTrigger);
+        
+        long out2 = recorder.getBytesOut();
+        Assert.assertTrue(out2-out1>10, "should have written more data");
+        int filesOut2 = recorder.getCountDataOut();
+        Assert.assertTrue(filesOut2>filesOut1, "should have written more files");
+        
+        Assert.assertTrue(out2<50*1000, "should have written less than 50k, wrote "+out1);
+        Assert.assertTrue(filesOut2<40, "should have written fewer than 40 files, wrote "+out1);
+        
+        ((EntityInternal)entity).setAttribute(TestEntity.NAME, Identifiers.makeRandomId(bigBlockSize));
+        if (forceDelay) Time.sleep(Duration.FIVE_SECONDS);
+        else recorder.blockUntilDataWrittenExceeds(out2+bigBlockSize, Duration.FIVE_SECONDS);
+        localManagementContext.getRebindManager().waitForPendingComplete(Duration.FIVE_SECONDS, canTrigger);
+
+        long out3 = recorder.getBytesOut();
+        Assert.assertTrue(out3-out2 > bigBlockSize, "should have written 50k more data, only wrote "+out3+" compared with "+out2);
+        int filesOut3 = recorder.getCountDataOut();
+        Assert.assertTrue(filesOut3>filesOut2, "should have written more files");
+        
+        Assert.assertTrue(out2<100*1000+bigBlockSize, "should have written less than 100k+block, wrote "+out1);
+        Assert.assertTrue(filesOut2<60, "should have written fewer than 60 files, wrote "+out1);
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterInMemoryTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterInMemoryTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterInMemoryTest.java
new file mode 100644
index 0000000..461ec99
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterInMemoryTest.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
+import org.apache.brooklyn.util.time.Duration;
+import org.testng.annotations.Test;
+
+@Test
+public class BrooklynMementoPersisterInMemoryTest extends BrooklynMementoPersisterTestFixture {
+
+    protected ManagementContext newPersistingManagementContext() {
+        return RebindTestUtils.managementContextBuilder(classLoader, new InMemoryObjectStore())
+            .persistPeriod(Duration.millis(10)).buildStarted();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterTestFixture.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterTestFixture.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterTestFixture.java
new file mode 100644
index 0000000..a715d2e
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterTestFixture.java
@@ -0,0 +1,165 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+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 org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.rebind.PersistenceExceptionHandler;
+import org.apache.brooklyn.api.mgmt.rebind.RebindManager.RebindFailureMode;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMemento;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoPersister;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
+import org.apache.brooklyn.api.policy.Policy;
+import org.apache.brooklyn.api.sensor.Enricher;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
+import org.apache.brooklyn.core.mgmt.rebind.PersistenceExceptionHandlerImpl;
+import org.apache.brooklyn.core.mgmt.rebind.RebindContextImpl;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
+import org.apache.brooklyn.core.mgmt.rebind.RecordingRebindExceptionHandler;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.core.test.policy.TestPolicy;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.apache.brooklyn.sensor.enricher.Enrichers;
+import org.testng.SkipException;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+
+import com.google.common.collect.Iterables;
+
+/**
+ * @author Andrea Turli
+ */
+public abstract class BrooklynMementoPersisterTestFixture {
+
+    protected ClassLoader classLoader = getClass().getClassLoader();
+    protected BrooklynMementoPersister persister;
+    protected TestApplication app;
+    protected Entity entity;
+    protected Location location;
+    protected ManagementContext localManagementContext;
+    protected Enricher enricher;
+    protected Policy policy;
+    
+    protected PersistenceObjectStore objectStore;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        localManagementContext = newPersistingManagementContext();
+        if (persister==null) {
+            persister = localManagementContext.getRebindManager().getPersister();
+        }
+        if (objectStore==null && persister instanceof BrooklynMementoPersisterToObjectStore) {
+            objectStore = ((BrooklynMementoPersisterToObjectStore)persister).getObjectStore();
+        }
+        app = ApplicationBuilder.newManagedApp(EntitySpec.create(TestApplication.class), localManagementContext);
+        location =  localManagementContext.getLocationManager()
+            .createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure("address", "localhost"));
+        entity = app.createAndManageChild(EntitySpec.create(TestEntity.class).location(location));
+        enricher = app.addEnricher(Enrichers.builder().propagatingAll().from(entity).build());
+        app.addPolicy(policy = new TestPolicy());
+    }
+
+    protected abstract ManagementContext newPersistingManagementContext();
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (localManagementContext != null) Entities.destroyAll(localManagementContext);
+        if (app != null) Entities.destroyAll(app.getManagementContext());
+        if (persister != null) persister.stop(false);
+        if (objectStore!=null) objectStore.deleteCompletely();
+        persister = null;
+    }
+
+    protected BrooklynMemento loadMemento() throws Exception {
+        RebindTestUtils.waitForPersisted(localManagementContext);
+        
+        RecordingRebindExceptionHandler failFast = new RecordingRebindExceptionHandler(RebindFailureMode.FAIL_FAST, RebindFailureMode.FAIL_FAST);
+        RebindContextImpl rebindContext = new RebindContextImpl(localManagementContext, failFast, classLoader);
+        // here we force these two to be reegistered in order to resolve the enricher and policy
+        // (normally rebind will do that after loading the manifests, but in this test we are just looking at persistence/manifest)
+        rebindContext.registerEntity(app.getId(), app);
+        rebindContext.registerEntity(entity.getId(), entity);
+        
+        BrooklynMemento reloadedMemento = persister.loadMemento(null, rebindContext.lookup(), failFast);
+        return reloadedMemento;
+    }
+    
+    protected BrooklynMementoRawData loadRawMemento(BrooklynMementoPersisterToObjectStore persister) throws Exception {
+        RebindTestUtils.waitForPersisted(localManagementContext);
+        
+        RecordingRebindExceptionHandler failFast = new RecordingRebindExceptionHandler(RebindFailureMode.FAIL_FAST, RebindFailureMode.FAIL_FAST);
+        BrooklynMementoRawData rawMemento = persister.loadMementoRawData(failFast);
+        return rawMemento;
+    }
+    
+    @Test
+    public void testCheckPointAndLoadMemento() throws Exception {
+        BrooklynMemento reloadedMemento = loadMemento();
+        
+        assertNotNull(reloadedMemento);
+        assertTrue(Iterables.contains(reloadedMemento.getEntityIds(), entity.getId()));
+        assertEquals(Iterables.getOnlyElement(reloadedMemento.getLocationIds()), location.getId());
+        assertEquals(Iterables.getOnlyElement(reloadedMemento.getPolicyIds()), policy.getId());
+        assertTrue(reloadedMemento.getEnricherIds().contains(enricher.getId()));
+    }
+
+    @Test
+    public void testDeleteAndLoadMemento() throws Exception {
+        Entities.destroy(entity);
+
+        BrooklynMemento reloadedMemento = loadMemento();
+        
+        assertNotNull(reloadedMemento);
+        assertFalse(Iterables.contains(reloadedMemento.getEntityIds(), entity.getId()));
+        assertEquals(Iterables.getOnlyElement(reloadedMemento.getLocationIds()), location.getId());
+    }
+    
+    @Test
+    public void testLoadAndCheckpointRawMemento() throws Exception {
+        if (persister instanceof BrooklynMementoPersisterToObjectStore) {
+            // Test loading
+            BrooklynMementoRawData rawMemento = loadRawMemento((BrooklynMementoPersisterToObjectStore)persister);
+            assertNotNull(rawMemento);
+            assertTrue(Iterables.contains(rawMemento.getEntities().keySet(), entity.getId()));
+            assertEquals(Iterables.getOnlyElement(rawMemento.getLocations().keySet()), location.getId());
+            assertEquals(Iterables.getOnlyElement(rawMemento.getPolicies().keySet()), policy.getId());
+            assertTrue(rawMemento.getEnrichers().keySet().contains(enricher.getId()));
+            
+            // And test persisting
+            PersistenceExceptionHandler exceptionHandler = PersistenceExceptionHandlerImpl.builder().build();
+            ((BrooklynMementoPersisterToObjectStore) persister).checkpoint(rawMemento, exceptionHandler);
+        } else {
+            throw new SkipException("Persister "+persister+" not a "+BrooklynMementoPersisterToObjectStore.class.getSimpleName());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/FileBasedObjectStoreTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/FileBasedObjectStoreTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/FileBasedObjectStoreTest.java
new file mode 100644
index 0000000..05ac078
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/FileBasedObjectStoreTest.java
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.core.mgmt.persist.FileBasedObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.util.io.FileUtil;
+import org.apache.brooklyn.util.os.Os;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.io.Files;
+
+public class FileBasedObjectStoreTest {
+
+    private LocalManagementContextForTests mgmt;
+    private File parentdir;
+    private File basedir;
+    private FileBasedObjectStore store;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        mgmt = new LocalManagementContextForTests();
+        parentdir = Files.createTempDir();
+        basedir = new File(parentdir, "mystore");
+        store = new FileBasedObjectStore(basedir);
+        store.injectManagementContext(mgmt);
+        store.prepareForSharedUse(PersistMode.AUTO, HighAvailabilityMode.DISABLED);
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (store != null) store.close();
+        if (parentdir != null) Os.deleteRecursively(basedir);
+        if (mgmt != null) Entities.destroyAll(mgmt);
+    }
+    
+    @Test(groups="Integration")
+    public void testSubPathCreatedWithPermission700() throws Exception {
+        store.createSubPath("mysubdir");
+        File subdir = new File(basedir, "mysubdir");
+        
+        assertFilePermission700(basedir);
+        assertFilePermission700(subdir);
+    }
+    
+    @Test
+    public void testIsMementoDirExistsButEmpty() throws Exception {
+        basedir = new File(parentdir, "testIsMementoDirExistsButEmpty");
+        assertFalse(FileBasedObjectStore.isMementoDirExistButEmpty(basedir));
+        assertFalse(FileBasedObjectStore.isMementoDirExistButEmpty(basedir.getAbsolutePath()));
+        
+        basedir.mkdir();
+        assertTrue(FileBasedObjectStore.isMementoDirExistButEmpty(basedir));
+        assertTrue(FileBasedObjectStore.isMementoDirExistButEmpty(basedir.getAbsolutePath()));
+        
+        new File(basedir, "entities").mkdir();
+        new File(basedir, "locations").mkdir();
+        assertTrue(FileBasedObjectStore.isMementoDirExistButEmpty(basedir));
+        assertTrue(FileBasedObjectStore.isMementoDirExistButEmpty(basedir.getAbsolutePath()));
+        
+        new File(new File(basedir, "locations"), "afile").createNewFile();
+        assertFalse(FileBasedObjectStore.isMementoDirExistButEmpty(basedir));
+        assertFalse(FileBasedObjectStore.isMementoDirExistButEmpty(basedir.getAbsolutePath()));
+    }
+    
+    static void assertFilePermission700(File file) throws FileNotFoundException {
+        assertEquals(FileUtil.getFilePermissions(file).get().substring(1), "rwx------");
+    }
+    
+    static void assertFilePermission600(File file) throws Exception {
+        assertEquals(FileUtil.getFilePermissions(file).get().substring(1), "rw-------");
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/FileBasedStoreObjectAccessorWriterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/FileBasedStoreObjectAccessorWriterTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/FileBasedStoreObjectAccessorWriterTest.java
new file mode 100644
index 0000000..3ee71df
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/FileBasedStoreObjectAccessorWriterTest.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import static org.testng.Assert.assertEquals;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.apache.brooklyn.core.mgmt.persist.FileBasedStoreObjectAccessor;
+import org.apache.brooklyn.core.mgmt.persist.StoreObjectAccessorLocking;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore.StoreObjectAccessorWithLock;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.time.Duration;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Charsets;
+import com.google.common.collect.ImmutableList;
+import com.google.common.io.Files;
+
+@Test
+public class FileBasedStoreObjectAccessorWriterTest extends PersistenceStoreObjectAccessorWriterTestFixture {
+
+    private File file;
+    
+    protected StoreObjectAccessorWithLock newPersistenceStoreObjectAccessor() throws IOException {
+        file = Os.newTempFile(getClass(), "txt");
+        return new StoreObjectAccessorLocking(new FileBasedStoreObjectAccessor(file, ".tmp"));
+    }
+    
+    @Override
+    protected Duration getLastModifiedResolution() {
+        // OSX is 1s, Windows FAT is 2s !
+        return Duration.seconds(2);
+    }
+    
+    @Test(groups="Integration")
+    public void testLastModifiedTime() throws Exception {
+        super.testLastModifiedTime();
+    }
+    
+    @Test(groups="Integration")
+    public void testFilePermissions600() throws Exception {
+        accessor.put("abc");
+        assertEquals(Files.readLines(file, Charsets.UTF_8), ImmutableList.of("abc"));
+        
+        FileBasedObjectStoreTest.assertFilePermission600(file);
+    }
+}


[21/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcess.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcess.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcess.java
new file mode 100644
index 0000000..573bc00
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcess.java
@@ -0,0 +1,362 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import java.util.Collection;
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.config.MapConfigKey;
+import org.apache.brooklyn.entity.annotation.Effector;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle.Transition;
+import org.apache.brooklyn.entity.trait.Startable;
+import org.apache.brooklyn.sensor.core.AttributeSensorAndConfigKey;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+import org.apache.brooklyn.util.time.Duration;
+
+import com.google.common.annotations.Beta;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.reflect.TypeToken;
+
+public interface SoftwareProcess extends Entity, Startable {
+
+    AttributeSensor<String> HOSTNAME = Attributes.HOSTNAME;
+    AttributeSensor<String> ADDRESS = Attributes.ADDRESS;
+    AttributeSensor<String> SUBNET_HOSTNAME = Attributes.SUBNET_HOSTNAME;
+    AttributeSensor<String> SUBNET_ADDRESS = Attributes.SUBNET_ADDRESS;
+
+    @SuppressWarnings("serial")
+    ConfigKey<Collection<Integer>> REQUIRED_OPEN_LOGIN_PORTS = ConfigKeys.newConfigKey(
+            new TypeToken<Collection<Integer>>() {},
+            "requiredOpenLoginPorts",
+            "The port(s) to be opened, to allow login",
+            ImmutableSet.of(22));
+
+    @SetFromFlag("startTimeout")
+    ConfigKey<Duration> START_TIMEOUT = BrooklynConfigKeys.START_TIMEOUT;
+
+    @SetFromFlag("startLatch")
+    ConfigKey<Boolean> START_LATCH = BrooklynConfigKeys.START_LATCH;
+
+    @SetFromFlag("setupLatch")
+    ConfigKey<Boolean> SETUP_LATCH = BrooklynConfigKeys.SETUP_LATCH;
+
+    @SetFromFlag("installResourcesLatch")
+    ConfigKey<Boolean> INSTALL_RESOURCES_LATCH = BrooklynConfigKeys.INSTALL_RESOURCES_LATCH;
+
+    @SetFromFlag("installLatch")
+    ConfigKey<Boolean> INSTALL_LATCH = BrooklynConfigKeys.INSTALL_LATCH;
+
+    @SetFromFlag("runtimeResourcesLatch")
+    ConfigKey<Boolean> RUNTIME_RESOURCES_LATCH = BrooklynConfigKeys.RUNTIME_RESOURCES_LATCH;
+
+    @SetFromFlag("customizeLatch")
+    ConfigKey<Boolean> CUSTOMIZE_LATCH = BrooklynConfigKeys.CUSTOMIZE_LATCH;
+
+    @SetFromFlag("launchLatch")
+    ConfigKey<Boolean> LAUNCH_LATCH = BrooklynConfigKeys.LAUNCH_LATCH;
+
+    @SetFromFlag("skipStart")
+    ConfigKey<Boolean> ENTITY_STARTED = BrooklynConfigKeys.SKIP_ENTITY_START;
+
+    @SetFromFlag("skipStartIfRunning")
+    ConfigKey<Boolean> SKIP_ENTITY_START_IF_RUNNING = BrooklynConfigKeys.SKIP_ENTITY_START_IF_RUNNING;
+
+    @SetFromFlag("skipInstall")
+    ConfigKey<Boolean> SKIP_INSTALLATION = BrooklynConfigKeys.SKIP_ENTITY_INSTALLATION;
+
+    @SetFromFlag("preInstallCommand")
+    ConfigKey<String> PRE_INSTALL_COMMAND = BrooklynConfigKeys.PRE_INSTALL_COMMAND;
+
+    @SetFromFlag("postInstallCommand")
+    ConfigKey<String> POST_INSTALL_COMMAND = BrooklynConfigKeys.POST_INSTALL_COMMAND;
+
+    @SetFromFlag("preLaunchCommand")
+    ConfigKey<String> PRE_LAUNCH_COMMAND = BrooklynConfigKeys.PRE_LAUNCH_COMMAND;
+
+    @SetFromFlag("postLaunchCommand")
+    ConfigKey<String> POST_LAUNCH_COMMAND = BrooklynConfigKeys.POST_LAUNCH_COMMAND;
+
+    @SetFromFlag("version")
+    ConfigKey<String> SUGGESTED_VERSION = BrooklynConfigKeys.SUGGESTED_VERSION;
+
+    @SetFromFlag("downloadUrl")
+    AttributeSensorAndConfigKey<String,String> DOWNLOAD_URL = Attributes.DOWNLOAD_URL;
+
+    @SetFromFlag("downloadAddonUrls")
+    AttributeSensorAndConfigKey<Map<String,String>,Map<String,String>> DOWNLOAD_ADDON_URLS = Attributes.DOWNLOAD_ADDON_URLS;
+
+    @SetFromFlag("installLabel")
+    ConfigKey<String> INSTALL_UNIQUE_LABEL = BrooklynConfigKeys.INSTALL_UNIQUE_LABEL;
+
+    @SetFromFlag("expandedInstallDir")
+    AttributeSensorAndConfigKey<String,String> EXPANDED_INSTALL_DIR = BrooklynConfigKeys.EXPANDED_INSTALL_DIR;
+
+    @SetFromFlag("installDir")
+    AttributeSensorAndConfigKey<String,String> INSTALL_DIR = BrooklynConfigKeys.INSTALL_DIR;
+    @Deprecated
+    ConfigKey<String> SUGGESTED_INSTALL_DIR = BrooklynConfigKeys.SUGGESTED_INSTALL_DIR;
+
+    @SetFromFlag("runDir")
+    AttributeSensorAndConfigKey<String,String> RUN_DIR = BrooklynConfigKeys.RUN_DIR;
+    @Deprecated
+    ConfigKey<String> SUGGESTED_RUN_DIR = BrooklynConfigKeys.SUGGESTED_RUN_DIR;
+
+    public static final ConfigKey<Boolean> OPEN_IPTABLES = ConfigKeys.newBooleanConfigKey("openIptables", 
+            "Whether to open the INBOUND_PORTS via iptables rules; " +
+            "if true then ssh in to run iptables commands, as part of machine provisioning", false);
+
+    public static final ConfigKey<Boolean> STOP_IPTABLES = ConfigKeys.newBooleanConfigKey("stopIptables", 
+            "Whether to stop iptables entirely; " +
+            "if true then ssh in to stop the iptables service, as part of machine provisioning", false);
+
+    public static final ConfigKey<Boolean> DONT_REQUIRE_TTY_FOR_SUDO = ConfigKeys.newBooleanConfigKey("dontRequireTtyForSudo", 
+            "Whether to explicitly set /etc/sudoers, so don't need tty (will leave unchanged if 'false'); " +
+            "some machines require a tty for sudo; brooklyn by default does not use a tty " +
+            "(so that it can get separate error+stdout streams); you can enable a tty as an " +
+            "option to every ssh command, or you can do it once and " +
+            "modify the machine so that a tty is not subsequently required.",
+            false);
+    
+    /**
+     * Files to be copied to the server before pre-install.
+     * <p>
+     * Map of {@code classpath://foo/file.txt} (or other url) source to destination path,
+     * as {@code subdir/file} relative to installation directory or {@code /absolute/path/to/file}.
+     *
+     * @see #PRE_INSTALL_TEMPLATES
+     */
+    @Beta
+    @SuppressWarnings("serial")
+    @SetFromFlag("preInstallFiles")
+    ConfigKey<Map<String, String>> PRE_INSTALL_FILES = ConfigKeys.newConfigKey(new TypeToken<Map<String, String>>() { },
+            "files.preinstall", "Mapping of files, to be copied before install, to destination name relative to installDir");
+
+    /**
+     * Templates to be filled in and then copied to the server before install.
+     *
+     * @see #PRE_INSTALL_FILES
+     */
+    @Beta
+    @SuppressWarnings("serial")
+    @SetFromFlag("preInstallTemplates")
+    ConfigKey<Map<String, String>> PRE_INSTALL_TEMPLATES = ConfigKeys.newConfigKey(new TypeToken<Map<String, String>>() { },
+            "templates.preinstall", "Mapping of templates, to be filled in and copied before pre-install, to destination name relative to installDir");
+
+    /**
+     * Files to be copied to the server before install.
+     * <p>
+     * Map of {@code classpath://foo/file.txt} (or other url) source to destination path,
+     * as {@code subdir/file} relative to installation directory or {@code /absolute/path/to/file}.
+     *
+     * @see #INSTALL_TEMPLATES
+     */
+    @Beta
+    @SuppressWarnings("serial")
+    @SetFromFlag("installFiles")
+    ConfigKey<Map<String, String>> INSTALL_FILES = ConfigKeys.newConfigKey(new TypeToken<Map<String, String>>() { },
+            "files.install", "Mapping of files, to be copied before install, to destination name relative to installDir");
+
+    /**
+     * Templates to be filled in and then copied to the server before install.
+     *
+     * @see #INSTALL_FILES
+     */
+    @Beta
+    @SuppressWarnings("serial")
+    @SetFromFlag("installTemplates")
+    ConfigKey<Map<String, String>> INSTALL_TEMPLATES = ConfigKeys.newConfigKey(new TypeToken<Map<String, String>>() { },
+            "templates.install", "Mapping of templates, to be filled in and copied before install, to destination name relative to installDir");
+
+    /**
+     * Files to be copied to the server after customisation.
+     * <p>
+     * Map of {@code classpath://foo/file.txt} (or other url) source to destination path,
+     * as {@code subdir/file} relative to runtime directory or {@code /absolute/path/to/file}.
+     *
+     * @see #RUNTIME_TEMPLATES
+     */
+    @Beta
+    @SuppressWarnings("serial")
+    @SetFromFlag("runtimeFiles")
+    ConfigKey<Map<String, String>> RUNTIME_FILES = ConfigKeys.newConfigKey(new TypeToken<Map<String, String>>() { },
+            "files.runtime", "Mapping of files, to be copied before customisation, to destination name relative to runDir");
+
+    /**
+     * Templates to be filled in and then copied to the server after customisation.
+     *
+     * @see #RUNTIME_FILES
+     */
+    @Beta
+    @SuppressWarnings("serial")
+    @SetFromFlag("runtimeTemplates")
+    ConfigKey<Map<String, String>> RUNTIME_TEMPLATES = ConfigKeys.newConfigKey(new TypeToken<Map<String, String>>() { },
+            "templates.runtime", "Mapping of templates, to be filled in and copied before customisation, to destination name relative to runDir");
+
+    @SetFromFlag("env")
+    MapConfigKey<Object> SHELL_ENVIRONMENT = new MapConfigKey<Object>(Object.class,
+            "shell.env", "Map of environment variables to pass to the runtime shell", MutableMap.<String,Object>of());
+
+    @SetFromFlag("provisioningProperties")
+    MapConfigKey<Object> PROVISIONING_PROPERTIES = new MapConfigKey<Object>(Object.class,
+            "provisioning.properties", "Custom properties to be passed in when provisioning a new machine", MutableMap.<String,Object>of());
+
+    @SetFromFlag("maxRebindSensorsDelay")
+    ConfigKey<Duration> MAXIMUM_REBIND_SENSOR_CONNECT_DELAY = ConfigKeys.newConfigKey(Duration.class,
+            "softwareProcess.maxSensorRebindDelay",
+            "The maximum delay to apply when reconnecting sensors when rebinding to this entity. " +
+                    "Brooklyn will wait a random amount of time, up to the value of this config key, to " +
+                    "avoid a thundering herd problem when the entity shares its machine with " +
+                    "several others. Set to null or to 0 to disable any delay.",
+            Duration.TEN_SECONDS);
+
+    /**
+     * Sets the object that manages the sequence of calls of the entity's driver.
+     */
+    @Beta
+    @SetFromFlag("lifecycleEffectorTasks")
+    ConfigKey<SoftwareProcessDriverLifecycleEffectorTasks> LIFECYCLE_EFFECTOR_TASKS = ConfigKeys.newConfigKey(SoftwareProcessDriverLifecycleEffectorTasks.class,
+            "softwareProcess.lifecycleTasks", "An object that handles lifecycle of an entity's associated machine.",
+            new SoftwareProcessDriverLifecycleEffectorTasks());
+
+    ConfigKey<Boolean> RETRIEVE_USAGE_METRICS = ConfigKeys.newBooleanConfigKey(
+            "metrics.usage.retrieve",
+            "Whether to retrieve the usage (e.g. performance) metrics",
+            true);
+
+    /** Controls the behavior when starting (stop, restart) {@link Startable} children as part of the start (stop, restart) effector on this entity
+     * <p>
+     * (NB: restarts are currently not propagated to children in the default {@link SoftwareProcess}
+     * due to the various semantics which may be desired; this may change, but if entities have specific requirements for restart,
+     * developers should either subclass the {@link SoftwareProcessDriverLifecycleEffectorTasks} and/or lean on sensors from the parent */
+    enum ChildStartableMode {
+        /** do nothing with {@link Startable} children */
+        NONE(true, false, false),
+        /** start (stop) {@link Startable} children concurrent with *driver* start (stop),
+         * in foreground, so invoking entity will wait for children to complete.
+         * <p>
+         * if the child requires the parent to reach a particular state before acting,
+         * when running in foreground the parent should communicate its state using sensors
+         * which the child listens for.
+         * note that often sensors at the parent are not activated until it is started,
+         * so the usual sensors connected at an entity may not be available when running in this mode */
+        FOREGROUND(false, false, false),
+        /** as {@link #FOREGROUND} but {@link ChildStartableMode#isLate} */
+        FOREGROUND_LATE(false, false, true),
+        /** start {@link Startable} children concurrent with *driver* start (stop, restart),
+         * but in background, ie disassociated from the effector task at this entity
+         * (so that this entity can complete start/stop independent of children) */
+        BACKGROUND(false, true, false),
+        /** as {@link #BACKGROUND} but {@link ChildStartableMode#isLate} */
+        BACKGROUND_LATE(false, true, true);
+
+        /** whether starting (stopping, restarting) children is disabled */
+        public final boolean isDisabled;
+        /** whether starting (stopping, restarting) children is backgrounded, so parent should not wait on them */
+        public final boolean isBackground;
+        /** whether starting (stopping, restarting) children should be nested, so start occurs after the driver is started,
+         * and stop before the driver is stopped (if false the children operations are concurrent with the parent),
+         * (with restart always being done in parallel though this behaviour may change) */
+        public final boolean isLate;
+
+        private ChildStartableMode(boolean isDisabled, boolean isBackground, boolean isLate) {
+            this.isDisabled = isDisabled;
+            this.isBackground = isBackground;
+            this.isLate = isLate;
+        }
+
+    }
+
+    @SetFromFlag("childStartMode")
+    ConfigKey<ChildStartableMode> CHILDREN_STARTABLE_MODE = ConfigKeys.newConfigKey(ChildStartableMode.class,
+            "children.startable.mode", "Controls behaviour when starting Startable children as part of this entity's lifecycle.",
+            ChildStartableMode.NONE);
+
+    @SuppressWarnings("rawtypes")
+    AttributeSensor<MachineProvisioningLocation> PROVISIONING_LOCATION = Sensors.newSensor(
+            MachineProvisioningLocation.class, "softwareservice.provisioningLocation", "Location used to provision a machine where this is running");
+
+    AttributeSensor<Boolean> SERVICE_PROCESS_IS_RUNNING = Sensors.newBooleanSensor("service.process.isRunning", 
+            "Whether the process for the service is confirmed as running");
+    
+    AttributeSensor<Lifecycle> SERVICE_STATE_ACTUAL = Attributes.SERVICE_STATE_ACTUAL;
+    AttributeSensor<Transition> SERVICE_STATE_EXPECTED = Attributes.SERVICE_STATE_EXPECTED;
+ 
+    AttributeSensor<String> PID_FILE = Sensors.newStringSensor("softwareprocess.pid.file", "PID file");
+
+    @Beta
+    public static class RestartSoftwareParameters {
+        @Beta /** @since 0.7.0 semantics of parameters to restart being explored */
+        public static final ConfigKey<Boolean> RESTART_CHILDREN = ConfigKeys.newConfigKey(Boolean.class, "restartChildren",
+            "Whether to restart children; default false", false);
+
+        @Beta /** @since 0.7.0 semantics of parameters to restart being explored */
+        public static final ConfigKey<Object> RESTART_MACHINE = ConfigKeys.newConfigKey(Object.class, "restartMachine",
+            "Whether to restart/replace the machine provisioned for this entity:  'true', 'false', or 'auto' are supported, "
+            + "with the default being 'auto' which means to restart or reprovision the machine if there is no simpler way known to restart the entity "
+            + "(for example, if the machine is unhealthy, it would not be possible to restart the process, not even via a stop-then-start sequence); "
+            + "if the machine was not provisioned for this entity, this parameter has no effect", 
+            RestartMachineMode.AUTO.toString().toLowerCase());
+        
+        // we supply a typed variant for retrieval; we want the untyped (above) to use lower case as the default in the GUI
+        // (very hard if using enum, since enum takes the name, and RendererHints do not apply to parameters) 
+        @Beta /** @since 0.7.0 semantics of parameters to restart being explored */
+        public static final ConfigKey<RestartMachineMode> RESTART_MACHINE_TYPED = ConfigKeys.newConfigKey(RestartMachineMode.class, "restartMachine");
+            
+        public enum RestartMachineMode { TRUE, FALSE, AUTO }
+    }
+
+    @Beta
+    public static class StopSoftwareParameters {
+        //IF_NOT_STOPPED includes STARTING, STOPPING, RUNNING
+        public enum StopMode { ALWAYS, IF_NOT_STOPPED, NEVER };
+
+        @Beta /** @since 0.7.0 semantics of parameters to restart being explored */
+        public static final ConfigKey<StopMode> STOP_PROCESS_MODE = ConfigKeys.newConfigKey(StopMode.class, "stopProcessMode",
+                "When to stop the process with regard to the entity state. " +
+                "ALWAYS will try to stop the process even if the entity is marked as stopped, " +
+                "IF_NOT_STOPPED stops the process only if the entity is not marked as stopped, " +
+                "NEVER doesn't stop the process.", StopMode.IF_NOT_STOPPED);
+
+        @Beta /** @since 0.7.0 semantics of parameters to restart being explored */
+        public static final ConfigKey<StopMode> STOP_MACHINE_MODE = ConfigKeys.newConfigKey(StopMode.class, "stopMachineMode",
+                "When to stop the machine with regard to the entity state. " +
+                "ALWAYS will try to stop the machine even if the entity is marked as stopped, " +
+                "IF_NOT_STOPPED stops the machine only if the entity is not marked as stopped, " +
+                "NEVER doesn't stop the machine.", StopMode.IF_NOT_STOPPED);
+    }
+    
+    // NB: the START, STOP, and RESTART effectors themselves are (re)defined by MachineLifecycleEffectorTasks
+
+    /**
+     * @since 0.8.0
+     */
+    @Effector(description="Populates the attribute service.notUp.diagnostics, with any available health indicators")
+    @Beta
+    void populateServiceNotUpDiagnostics();
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessDriver.java
new file mode 100644
index 0000000..8221282
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessDriver.java
@@ -0,0 +1,75 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import org.apache.brooklyn.api.entity.drivers.EntityDriver;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.entity.trait.Startable;
+
+/**
+ * The {@link EntityDriver} for a {@link SoftwareProcess}.
+ *
+ * <p/>
+ * In many cases it is cleaner to store entity lifecycle effectors (and sometimes other implementations) in a class to
+ * which the entity delegates.  Classes implementing this interface provide this delegate, often inheriting utilities
+ * specific to a particular transport (e.g. ssh) shared among many different entities.
+ * <p/>
+ * In this way, it is also possible for entities to cleanly support multiple mechanisms for start/stop and other methods.
+ */
+public interface SoftwareProcessDriver extends EntityDriver {
+
+    /**
+     * The entity whose components we are controlling.
+     */
+    EntityLocal getEntity();
+
+    /**
+     * Whether the entity components have started.
+     */
+    boolean isRunning();
+
+    /**
+     * Rebinds the driver to a pre-existing software process.
+     */
+    void rebind();
+
+    /**
+     * Performs software start (or queues tasks to do this)
+     */
+    void start();
+
+    /**
+     * Performs software restart (or queues tasks to do this).
+     * Unlike stop/start implementations here are expected to update SERVICE_STATE for STOPPING and STARTING
+     * as appropriate (but framework will set RUNNING afterwards, after detecting it is running).
+     * @see Startable#restart()
+     */
+    void restart();
+
+    /**
+     * Performs software stop (or queues tasks to do this) 
+     * @see Startable#stop()
+     */
+    void stop();
+
+    /**
+     * Kills the process, ungracefully and immediately where possible (e.g. with `kill -9`).
+     */
+    void kill();
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessDriverLifecycleEffectorTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessDriverLifecycleEffectorTasks.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessDriverLifecycleEffectorTasks.java
new file mode 100644
index 0000000..56dfcb2
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessDriverLifecycleEffectorTasks.java
@@ -0,0 +1,261 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.mgmt.TaskAdaptable;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.ChildStartableMode;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.RestartSoftwareParameters;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.RestartSoftwareParameters.RestartMachineMode;
+import org.apache.brooklyn.entity.software.base.lifecycle.MachineLifecycleEffectorTasks;
+import org.apache.brooklyn.entity.trait.StartableMethods;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.text.Strings;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Supplier;
+
+/** Thin shim delegating to driver to do start/stop/restart, wrapping as tasks,
+ * with common code pulled up to {@link MachineLifecycleEffectorTasks} for non-driver usage 
+ * @since 0.6.0 */
+@Beta
+public class SoftwareProcessDriverLifecycleEffectorTasks extends MachineLifecycleEffectorTasks {
+    
+    private static final Logger log = LoggerFactory.getLogger(SoftwareProcessDriverLifecycleEffectorTasks.class);
+    
+    public void restart(ConfigBag parameters) {
+        RestartMachineMode isRestartMachine = parameters.get(RestartSoftwareParameters.RESTART_MACHINE_TYPED);
+        if (isRestartMachine==null) 
+            isRestartMachine=RestartMachineMode.AUTO;
+        if (isRestartMachine==RestartMachineMode.AUTO) 
+            isRestartMachine = getDefaultRestartStopsMachine() ? RestartMachineMode.TRUE : RestartMachineMode.FALSE; 
+
+        if (isRestartMachine==RestartMachineMode.TRUE) {
+            log.debug("restart of "+entity()+" requested be applied at machine level");
+            super.restart(parameters);
+            return;
+        }
+        
+        DynamicTasks.queue("pre-restart", new PreRestartTask());
+
+        log.debug("restart of "+entity()+" appears to have driver and hostname - doing driver-level restart");
+        entity().getDriver().restart();
+        
+        restartChildren(parameters);
+        
+        DynamicTasks.queue("post-restart", new PostRestartTask());
+    }
+
+    private class PreRestartTask implements Runnable {
+        @Override
+        public void run() {
+            preRestartCustom();
+        }
+    }
+
+    private class PostRestartTask implements Runnable {
+        @Override
+        public void run() {
+            postStartCustom();
+            postRestartCustom();
+            ServiceStateLogic.setExpectedState(entity(), Lifecycle.RUNNING);
+        }
+    }
+    
+    @Override
+    protected boolean getDefaultRestartStopsMachine() {
+        if (entity().getDriver() == null) {
+            log.debug("restart of "+entity()+" has no driver - doing machine-level restart");
+            return true;
+        }
+
+        if (Strings.isEmpty(entity().getAttribute(Attributes.HOSTNAME))) {
+            log.debug("restart of "+entity()+" has no hostname - doing machine-level restart");
+            return true;
+        }
+        
+        return false;
+    }
+    
+    @Override
+    protected SoftwareProcessImpl entity() {
+        return (SoftwareProcessImpl) super.entity();
+    }
+    
+    @Override
+    protected Map<String, Object> obtainProvisioningFlags(final MachineProvisioningLocation<?> location) {
+        return entity().obtainProvisioningFlags(location);
+    }
+     
+    @Override
+    protected void preStartCustom(MachineLocation machine) {
+        entity().initDriver(machine);
+
+        // Note: must only apply config-sensors after adding to locations and creating driver; 
+        // otherwise can't do things like acquire free port from location, or allowing driver to set up ports
+        super.preStartCustom(machine);
+        
+        entity().preStart();
+    }
+
+    /** returns how children startables should be handled (reporting none for efficiency if there are no children) */
+    protected ChildStartableMode getChildrenStartableModeEffective() {
+        if (entity().getChildren().isEmpty()) return ChildStartableMode.NONE;
+        ChildStartableMode result = entity().getConfig(SoftwareProcess.CHILDREN_STARTABLE_MODE);
+        if (result!=null) return result;
+        return ChildStartableMode.NONE;
+    }
+
+    @Override
+    protected String startProcessesAtMachine(final Supplier<MachineLocation> machineS) {
+        ChildStartableMode mode = getChildrenStartableModeEffective();
+        TaskAdaptable<?> children = null;
+        if (!mode.isDisabled) {
+            children = StartableMethods.startingChildren(entity(), machineS.get());
+            // submit rather than queue so it runs in parallel
+            // (could also wrap as parallel task with driver.start() -
+            // but only benefit is that child starts show as child task,
+            // rather than bg task, so not worth the code complexity)
+            if (!mode.isLate) Entities.submit(entity(), children);
+        }
+        
+        entity().getDriver().start();
+        String result = "Started with driver "+entity().getDriver();
+        
+        if (!mode.isDisabled) {
+            if (mode.isLate) {
+                DynamicTasks.waitForLast();
+                if (mode.isBackground) {
+                    Entities.submit(entity(), children);
+                } else {
+                    // when running foreground late, there is no harm here in queueing
+                    DynamicTasks.queue(children);
+                }
+            }
+            if (!mode.isBackground) children.asTask().getUnchecked();
+            result += "; children started "+mode;
+        }
+        return result;
+    }
+
+    @Override
+    protected void postStartCustom() {
+        entity().postDriverStart();
+        if (entity().connectedSensors) {
+            // many impls aren't idempotent - though they should be!
+            log.debug("skipping connecting sensors for "+entity()+" in driver-tasks postStartCustom because already connected (e.g. restarting)");
+        } else {
+            log.debug("connecting sensors for "+entity()+" in driver-tasks postStartCustom because already connected (e.g. restarting)");
+            entity().connectSensors();
+        }
+        entity().waitForServiceUp();
+        entity().postStart();
+    }
+    
+    @Override
+    protected void preStopConfirmCustom() {
+        super.preStopConfirmCustom();
+        
+        entity().preStopConfirmCustom();
+    }
+    
+    @Override
+    protected void preStopCustom() {
+        super.preStopCustom();
+        
+        entity().preStop();
+    }
+
+    @Override
+    protected void preRestartCustom() {
+        super.preRestartCustom();
+        
+        entity().preRestart();
+    }
+
+    @Override
+    protected void postRestartCustom() {
+        super.postRestartCustom();
+        
+        entity().postRestart();
+    }
+
+    @Override
+    protected String stopProcessesAtMachine() {
+        String result;
+        
+        ChildStartableMode mode = getChildrenStartableModeEffective();
+        TaskAdaptable<?> children = null;
+        Exception childException = null;
+        
+        if (!mode.isDisabled) {
+            children = StartableMethods.stoppingChildren(entity());
+            
+            if (mode.isBackground || !mode.isLate) Entities.submit(entity(), children);
+            else {
+                DynamicTasks.queue(children);
+                try {
+                    DynamicTasks.waitForLast();
+                } catch (Exception e) {
+                    childException = e;
+                }
+            }
+        }
+        
+        if (entity().getDriver() != null) { 
+            entity().getDriver().stop();
+            result = "Driver stop completed";
+        } else {
+            result = "No driver (nothing to do here)";
+        }
+
+        if (!mode.isDisabled && !mode.isBackground) {
+            try {
+                children.asTask().get();
+            } catch (Exception e) {
+                childException = e;
+                log.debug("Error stopping children; continuing and will rethrow if no other errors", e);
+            }            
+        }
+        
+        if (childException!=null)
+            throw new IllegalStateException(result+"; but error stopping child: "+childException, childException);
+
+        return result;
+    }
+    
+    @Override
+    protected void postStopCustom() {
+        super.postStopCustom();
+        
+        entity().postStop();
+    }
+
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessImpl.java
new file mode 100644
index 0000000..a3e8bcd
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SoftwareProcessImpl.java
@@ -0,0 +1,651 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import groovy.time.TimeDuration;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.Callable;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.drivers.DriverDependentEntity;
+import org.apache.brooklyn.api.entity.drivers.EntityDriverManager;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.location.PortRange;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.api.sensor.EnricherSpec;
+import org.apache.brooklyn.api.sensor.SensorEvent;
+import org.apache.brooklyn.api.sensor.SensorEventListener;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.entity.core.AbstractEntity;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle.Transition;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic.ServiceNotUpLogic;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.location.basic.LocationConfigKeys;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.cloud.CloudLocationConfig;
+import org.apache.brooklyn.sensor.enricher.AbstractEnricher;
+import org.apache.brooklyn.sensor.feed.function.FunctionFeed;
+import org.apache.brooklyn.sensor.feed.function.FunctionPollConfig;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.collections.MutableSet;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.flags.TypeCoercions;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.guava.Maybe;
+import org.apache.brooklyn.util.time.CountdownTimer;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+
+import com.google.common.base.Functions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Sets;
+import com.google.common.reflect.TypeToken;
+
+/**
+ * An {@link Entity} representing a piece of software which can be installed, run, and controlled.
+ * A single such entity can only run on a single {@link MachineLocation} at a time (you can have multiple on the machine). 
+ * It typically takes config keys for suggested versions, filesystem locations to use, and environment variables to set.
+ * <p>
+ * It exposes sensors for service state (Lifecycle) and status (String), and for host info, log file location.
+ */
+public abstract class SoftwareProcessImpl extends AbstractEntity implements SoftwareProcess, DriverDependentEntity {
+    private static final Logger log = LoggerFactory.getLogger(SoftwareProcessImpl.class);
+    
+    private transient SoftwareProcessDriver driver;
+
+    /** @see #connectServiceUpIsRunning() */
+    private volatile FunctionFeed serviceProcessIsRunning;
+
+    protected boolean connectedSensors = false;
+    
+    public SoftwareProcessImpl() {
+        super(MutableMap.of(), null);
+    }
+    public SoftwareProcessImpl(Entity parent) {
+        this(MutableMap.of(), parent);
+    }
+    public SoftwareProcessImpl(Map properties) {
+        this(properties, null);
+    }
+    public SoftwareProcessImpl(Map properties, Entity parent) {
+        super(properties, parent);
+    }
+
+    protected void setProvisioningLocation(MachineProvisioningLocation val) {
+        if (getAttribute(PROVISIONING_LOCATION) != null) throw new IllegalStateException("Cannot change provisioning location: existing="+getAttribute(PROVISIONING_LOCATION)+"; new="+val);
+        setAttribute(PROVISIONING_LOCATION, val);
+    }
+    
+    protected MachineProvisioningLocation getProvisioningLocation() {
+        return getAttribute(PROVISIONING_LOCATION);
+    }
+    
+    @Override
+    public SoftwareProcessDriver getDriver() {
+        return driver;
+    }
+
+    protected SoftwareProcessDriver newDriver(MachineLocation loc){
+        EntityDriverManager entityDriverManager = getManagementContext().getEntityDriverManager();
+        return (SoftwareProcessDriver)entityDriverManager.build(this, loc);
+    }
+
+    protected MachineLocation getMachineOrNull() {
+        return Iterables.get(Iterables.filter(getLocations(), MachineLocation.class), 0, null);
+    }
+
+    @Override
+    public void init() {
+        super.init();
+        getLifecycleEffectorTasks().attachLifecycleEffectors(this);
+    }
+    
+    @Override
+    protected void initEnrichers() {
+        super.initEnrichers();
+        ServiceNotUpLogic.updateNotUpIndicator(this, SERVICE_PROCESS_IS_RUNNING, "No information yet on whether this service is running");
+        // add an indicator above so that if is_running comes through, the map is cleared and an update is guaranteed
+        addEnricher(EnricherSpec.create(UpdatingNotUpFromServiceProcessIsRunning.class).uniqueTag("service-process-is-running-updating-not-up"));
+        addEnricher(EnricherSpec.create(ServiceNotUpDiagnosticsCollector.class).uniqueTag("service-not-up-diagnostics-collector"));
+    }
+    
+    /**
+     * @since 0.8.0
+     */
+    protected static class ServiceNotUpDiagnosticsCollector extends AbstractEnricher implements SensorEventListener<Object> {
+        public ServiceNotUpDiagnosticsCollector() {
+        }
+        
+        @Override
+        public void setEntity(EntityLocal entity) {
+            super.setEntity(entity);
+            if (!(entity instanceof SoftwareProcess)) {
+                throw new IllegalArgumentException("Expected SoftwareProcess, but got entity "+entity);
+            }
+            subscribe(entity, Attributes.SERVICE_UP, this);
+            onUpdated();
+        }
+
+        @Override
+        public void onEvent(SensorEvent<Object> event) {
+            onUpdated();
+        }
+
+        protected void onUpdated() {
+            Boolean up = entity.getAttribute(SERVICE_UP);
+            if (up == null || up) {
+                entity.setAttribute(ServiceStateLogic.SERVICE_NOT_UP_DIAGNOSTICS, ImmutableMap.<String, Object>of());
+            } else {
+                ((SoftwareProcess)entity).populateServiceNotUpDiagnostics();
+            }
+        }
+    }
+    
+    @Override
+    public void populateServiceNotUpDiagnostics() {
+        if (getDriver() == null) {
+            ServiceStateLogic.updateMapSensorEntry(this, ServiceStateLogic.SERVICE_NOT_UP_DIAGNOSTICS, "driver", "No driver");
+            return;
+        }
+
+        Location loc = getDriver().getLocation();
+        if (loc instanceof SshMachineLocation) {
+            if (!((SshMachineLocation)loc).isSshable()) {
+                ServiceStateLogic.updateMapSensorEntry(
+                        this, 
+                        ServiceStateLogic.SERVICE_NOT_UP_DIAGNOSTICS, 
+                        "sshable", 
+                        "The machine for this entity does not appear to be sshable");
+            }
+            return;
+        }
+
+        boolean processIsRunning = getDriver().isRunning();
+        if (!processIsRunning) {
+            ServiceStateLogic.updateMapSensorEntry(
+                    this, 
+                    ServiceStateLogic.SERVICE_NOT_UP_DIAGNOSTICS, 
+                    SERVICE_PROCESS_IS_RUNNING.getName(), 
+                    "The software process for this entity does not appear to be running");
+        }
+    }
+
+    /** subscribes to SERVICE_PROCESS_IS_RUNNING and SERVICE_UP; the latter has no effect if the former is set,
+     * but to support entities which set SERVICE_UP directly we want to make sure that the absence of 
+     * SERVICE_PROCESS_IS_RUNNING does not trigger any not-up indicators */
+    protected static class UpdatingNotUpFromServiceProcessIsRunning extends AbstractEnricher implements SensorEventListener<Object> {
+        public UpdatingNotUpFromServiceProcessIsRunning() {}
+        
+        @Override
+        public void setEntity(EntityLocal entity) {
+            super.setEntity(entity);
+            subscribe(entity, SERVICE_PROCESS_IS_RUNNING, this);
+            subscribe(entity, Attributes.SERVICE_UP, this);
+            onUpdated();
+        }
+
+        @Override
+        public void onEvent(SensorEvent<Object> event) {
+            onUpdated();
+        }
+
+        protected void onUpdated() {
+            Boolean isRunning = entity.getAttribute(SERVICE_PROCESS_IS_RUNNING);
+            if (Boolean.FALSE.equals(isRunning)) {
+                ServiceNotUpLogic.updateNotUpIndicator(entity, SERVICE_PROCESS_IS_RUNNING, "The software process for this entity does not appear to be running");
+                return;
+            }
+            if (Boolean.TRUE.equals(isRunning)) {
+                ServiceNotUpLogic.clearNotUpIndicator(entity, SERVICE_PROCESS_IS_RUNNING);
+                return;
+            }
+            // no info on "isRunning"
+            Boolean isUp = entity.getAttribute(Attributes.SERVICE_UP);
+            if (Boolean.TRUE.equals(isUp)) {
+                // if service explicitly set up, then don't apply our rule
+                ServiceNotUpLogic.clearNotUpIndicator(entity, SERVICE_PROCESS_IS_RUNNING);
+                return;
+            }
+            // service not up, or no info
+            ServiceNotUpLogic.updateNotUpIndicator(entity, SERVICE_PROCESS_IS_RUNNING, "No information on whether this service is running");
+        }
+    }
+    
+    /**
+     * Called before driver.start; guarantees the driver will exist, and locations will have been set.
+     */
+    protected void preStart() {
+    }
+    
+    /**
+     * Called after driver.start(). Default implementation is to wait to confirm the driver 
+     * definitely started the process.
+     */
+    protected void postDriverStart() {
+        waitForEntityStart();
+    }
+
+    /**
+     * For binding to the running app (e.g. connecting sensors to registry). Will be called
+     * on start() and on rebind().
+     * <p>
+     * Implementations should be idempotent (ie tell whether sensors already connected),
+     * though the framework is pretty good about not calling when already connected. 
+     * TODO improve the framework's feed system to detect duplicate additions
+     */
+    protected void connectSensors() {
+        connectedSensors = true;
+    }
+
+    /**
+     * For connecting the {@link #SERVICE_UP} sensor to the value of the {@code getDriver().isRunning()} expression.
+     * <p>
+     * Should be called inside {@link #connectSensors()}.
+     *
+     * @see #disconnectServiceUpIsRunning()
+     */
+    protected void connectServiceUpIsRunning() {
+        serviceProcessIsRunning = FunctionFeed.builder()
+                .entity(this)
+                .period(Duration.FIVE_SECONDS)
+                .poll(new FunctionPollConfig<Boolean, Boolean>(SERVICE_PROCESS_IS_RUNNING)
+                        .suppressDuplicates(true)
+                        .onException(Functions.constant(Boolean.FALSE))
+                        .callable(new Callable<Boolean>() {
+                            public Boolean call() {
+                                return getDriver().isRunning();
+                            }
+                        }))
+                .build();
+    }
+
+    /**
+     * For disconnecting the {@link #SERVICE_UP} feed.
+     * <p>
+     * Should be called from {@link #disconnectSensors()}.
+     *
+     * @see #connectServiceUpIsRunning()
+     */
+    protected void disconnectServiceUpIsRunning() {
+        if (serviceProcessIsRunning != null) serviceProcessIsRunning.stop();
+        // set null so the SERVICE_UP enricher runs (possibly removing it), then remove so everything is removed
+        // TODO race because the is-running check may be mid-task
+        setAttribute(SERVICE_PROCESS_IS_RUNNING, null);
+        removeAttribute(SERVICE_PROCESS_IS_RUNNING);
+    }
+
+    /**
+     * Called after the rest of start has completed (after {@link #connectSensors()} and {@link #waitForServiceUp()})
+     */
+    protected void postStart() {
+    }
+    
+    protected void preStopConfirmCustom() {
+    }
+    
+    protected void preStop() {
+        // note asymmetry that disconnectSensors is done in the entity not the driver
+        // whereas on start the *driver* calls connectSensors, before calling postStart,
+        // ie waiting for the entity truly to be started before calling postStart;
+        // TODO feels like that confusion could be eliminated with a single place for pre/post logic!)
+        log.debug("disconnecting sensors for "+this+" in entity.preStop");
+        disconnectSensors();
+        
+        // Must set the serviceProcessIsRunning explicitly to false - we've disconnected the sensors
+        // so nothing else will.
+        // Otherwise, if restarted, there will be no change to serviceProcessIsRunning, so the
+        // serviceUpIndicators will not change, so serviceUp will not be reset.
+        // TODO Is there a race where disconnectSensors could leave a task of the feeds still running
+        // which could set serviceProcessIsRunning to true again before the task completes and the feed
+        // is fully terminated?
+        setAttribute(SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, false);
+    }
+
+    /**
+     * Called after the rest of stop has completed (after VM deprovisioned, but before state set to STOPPED)
+     */
+    protected void postStop() {
+    }
+
+    /**
+     * Called before driver.restart; guarantees the driver will exist, and locations will have been set.
+     */
+    protected void preRestart() {
+    }
+
+    protected void postRestart() {
+    }
+
+    /**
+     * For disconnecting from the running app. Will be called on stop.
+     */
+    protected void disconnectSensors() {
+        connectedSensors = false;
+    }
+
+    /**
+     * Called after this entity is fully rebound (i.e. it is fully managed).
+     */
+    protected void postRebind() {
+    }
+    
+    protected void callRebindHooks() {
+        Duration configuredMaxDelay = getConfig(MAXIMUM_REBIND_SENSOR_CONNECT_DELAY);
+        if (configuredMaxDelay == null || Duration.ZERO.equals(configuredMaxDelay)) {
+            connectSensors();
+        } else {
+            long delay = (long) (Math.random() * configuredMaxDelay.toMilliseconds());
+            log.debug("Scheduled reconnection of sensors on {} in {}ms", this, delay);
+            Timer timer = new Timer();
+            timer.schedule(new TimerTask() {
+                @Override public void run() {
+                    try {
+                        if (getManagementSupport().isNoLongerManaged()) {
+                            log.debug("Entity {} no longer managed; ignoring scheduled connect sensors on rebind", SoftwareProcessImpl.this);
+                            return;
+                        }
+                        connectSensors();
+                    } catch (Throwable e) {
+                        log.warn("Problem connecting sensors on rebind of "+SoftwareProcessImpl.this, e);
+                        Exceptions.propagateIfFatal(e);
+                    }
+                }
+            }, delay);
+        }
+        // don't wait here - it may be long-running, e.g. if remote entity has died, and we don't want to block rebind waiting or cause it to fail
+        // the service will subsequently show service not up and thus failure
+//        waitForServiceUp();
+    }
+
+    @Override 
+    public void onManagementStarting() {
+        super.onManagementStarting();
+        
+        Lifecycle state = getAttribute(SERVICE_STATE_ACTUAL);
+        if (state == null || state == Lifecycle.CREATED) {
+            // Expect this is a normal start() sequence (i.e. start() will subsequently be called)
+            setAttribute(SERVICE_UP, false);
+            ServiceStateLogic.setExpectedState(this, Lifecycle.CREATED);
+            // force actual to be created because this is expected subsequently
+            setAttribute(SERVICE_STATE_ACTUAL, Lifecycle.CREATED);
+        }
+    }
+    
+    @Override 
+    public void onManagementStarted() {
+        super.onManagementStarted();
+        
+        Lifecycle state = getAttribute(SERVICE_STATE_ACTUAL);
+        if (state != null && state != Lifecycle.CREATED) {
+            postRebind();
+        }
+    }
+    
+    @Override
+    public void rebind() {
+        //SERVICE_STATE_ACTUAL might be ON_FIRE due to a temporary condition (problems map non-empty)
+        //Only if the expected state is ON_FIRE then the entity has permanently failed.
+        Transition expectedState = getAttribute(SERVICE_STATE_EXPECTED);
+        if (expectedState == null || expectedState.getState() != Lifecycle.RUNNING) {
+            log.warn("On rebind of {}, not calling software process rebind hooks because expected state is {}", this, expectedState);
+            return;
+        }
+
+        Lifecycle actualState = getAttribute(SERVICE_STATE_ACTUAL);
+        if (actualState == null || actualState != Lifecycle.RUNNING) {
+            log.warn("Rebinding entity {}, even though actual state is {}. Expected state is {}", new Object[] {this, actualState, expectedState});
+        }
+
+        // e.g. rebinding to a running instance
+        // FIXME For rebind, what to do about things in STARTING or STOPPING state?
+        // FIXME What if location not set?
+        log.info("Rebind {} connecting to pre-running service", this);
+        
+        MachineLocation machine = getMachineOrNull();
+        if (machine != null) {
+            initDriver(machine);
+            driver.rebind();
+            if (log.isDebugEnabled()) log.debug("On rebind of {}, re-created driver {}", this, driver);
+        } else {
+            log.info("On rebind of {}, no MachineLocation found (with locations {}) so not generating driver",
+                    this, getLocations());
+        }
+        
+        callRebindHooks();
+    }
+    
+    public void waitForServiceUp() {
+        Duration timeout = getConfig(BrooklynConfigKeys.START_TIMEOUT);
+        waitForServiceUp(timeout);
+    }
+    public void waitForServiceUp(Duration duration) {
+        Entities.waitForServiceUp(this, duration);
+    }
+    public void waitForServiceUp(TimeDuration duration) {
+        waitForServiceUp(duration.toMilliseconds(), TimeUnit.MILLISECONDS);
+    }
+    public void waitForServiceUp(long duration, TimeUnit units) {
+        Entities.waitForServiceUp(this, Duration.of(duration, units));
+    }
+
+    protected Map<String,Object> obtainProvisioningFlags(MachineProvisioningLocation location) {
+        ConfigBag result = ConfigBag.newInstance(location.getProvisioningFlags(ImmutableList.of(getClass().getName())));
+        result.putAll(getConfig(PROVISIONING_PROPERTIES));
+        if (result.get(CloudLocationConfig.INBOUND_PORTS) == null) {
+            Collection<Integer> ports = getRequiredOpenPorts();
+            Object requiredPorts = result.get(CloudLocationConfig.ADDITIONAL_INBOUND_PORTS);
+            if (requiredPorts instanceof Integer) {
+                ports.add((Integer) requiredPorts);
+            } else if (requiredPorts instanceof Iterable) {
+                for (Object o : (Iterable<?>) requiredPorts) {
+                    if (o instanceof Integer) ports.add((Integer) o);
+                }
+            }
+            if (ports != null && ports.size() > 0) result.put(CloudLocationConfig.INBOUND_PORTS, ports);
+        }
+        result.put(LocationConfigKeys.CALLER_CONTEXT, this);
+        return result.getAllConfigMutable();
+    }
+
+    /** returns the ports that this entity wants to use;
+     * default implementation returns {@link SoftwareProcess#REQUIRED_OPEN_LOGIN_PORTS} plus first value 
+     * for each {@link org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey} config key {@link PortRange}
+     * plus any ports defined with a config keys ending in {@code .port}.
+     */
+    protected Collection<Integer> getRequiredOpenPorts() {
+        Set<Integer> ports = MutableSet.copyOf(getConfig(REQUIRED_OPEN_LOGIN_PORTS));
+        Map<ConfigKey<?>, ?> allConfig = config().getBag().getAllConfigAsConfigKeyMap();
+        Set<ConfigKey<?>> configKeys = Sets.newHashSet(allConfig.keySet());
+        configKeys.addAll(getEntityType().getConfigKeys());
+
+        /* TODO: This won't work if there's a port collision, which will cause the corresponding port attribute
+           to be incremented until a free port is found. In that case the entity will use the free port, but the
+           firewall will open the initial port instead. Mostly a problem for SameServerEntity, localhost location.
+         */
+        for (ConfigKey<?> k: configKeys) {
+            Object value;
+            if (PortRange.class.isAssignableFrom(k.getType()) || k.getName().matches(".*\\.port")) {
+                value = config().get(k);
+            } else {
+                // config().get() will cause this to block until all config has been resolved
+                // using config().getRaw(k) means that we won't be able to use e.g. 'http.port: $brooklyn:component("x").attributeWhenReady("foo")'
+                // but that's unlikely to be used
+                Maybe<Object> maybeValue = config().getRaw(k);
+                value = maybeValue.isPresent() ? maybeValue.get() : null;
+            }
+
+            Maybe<PortRange> maybePortRange = TypeCoercions.tryCoerce(value, new TypeToken<PortRange>() {});
+
+            if (maybePortRange.isPresentAndNonNull()) {
+                PortRange p = maybePortRange.get();
+                if (p != null && !p.isEmpty()) ports.add(p.iterator().next());
+            }
+        }        
+        
+        log.debug("getRequiredOpenPorts detected default {} for {}", ports, this);
+        return ports;
+    }
+
+    protected void initDriver(MachineLocation machine) {
+        SoftwareProcessDriver newDriver = doInitDriver(machine);
+        if (newDriver == null) {
+            throw new UnsupportedOperationException("cannot start "+this+" on "+machine+": no driver available");
+        }
+        driver = newDriver;
+    }
+
+    /**
+     * Creates the driver (if does not already exist or needs replaced for some reason). Returns either the existing driver
+     * or a new driver. Must not return null.
+     */
+    protected SoftwareProcessDriver doInitDriver(MachineLocation machine) {
+        if (driver!=null) {
+            if ((driver instanceof AbstractSoftwareProcessDriver) && machine.equals(((AbstractSoftwareProcessDriver)driver).getLocation())) {
+                return driver; //just reuse
+            } else {
+                log.warn("driver/location change is untested for {} at {}; changing driver and continuing", this, machine);
+                return newDriver(machine);
+            }
+        } else {
+            return newDriver(machine);
+        }
+    }
+    
+    // TODO Find a better way to detect early death of process.
+    public void waitForEntityStart() {
+        if (log.isDebugEnabled()) log.debug("waiting to ensure {} doesn't abort prematurely", this);
+        Duration startTimeout = getConfig(START_TIMEOUT);
+        CountdownTimer timer = startTimeout.countdownTimer();
+        boolean isRunningResult = false;
+        long delay = 100;
+        Exception firstFailure = null;
+        while (!isRunningResult && !timer.isExpired()) {
+            Time.sleep(delay);
+            try {
+                isRunningResult = driver.isRunning();
+                if (log.isDebugEnabled()) log.debug("checked {}, 'is running' returned: {}", this, isRunningResult);
+            } catch (Exception  e) {
+                Exceptions.propagateIfFatal(e);
+
+                isRunningResult = false;
+                if (driver != null) {
+                    String msg = "checked " + this + ", 'is running' threw an exception; logging subsequent exceptions at debug level";
+                    if (firstFailure == null) {
+                        log.error(msg, e);
+                    } else {
+                        log.debug(msg, e);
+                    }
+                } else {
+                    // provide extra context info, as we're seeing this happen in strange circumstances
+                    log.error(this+" concurrent start and shutdown detected", e);
+                }
+                if (firstFailure == null) {
+                    firstFailure = e;
+                }
+            }
+            // slow exponential delay -- 1.1^N means after 40 tries and 50s elapsed, it reaches the max of 5s intervals
+            // TODO use Repeater 
+            delay = Math.min(delay*11/10, 5000);
+        }
+        if (!isRunningResult) {
+            String msg = "Software process entity "+this+" did not pass is-running check within "+
+                    "the required "+startTimeout+" limit ("+timer.getDurationElapsed().toStringRounded()+" elapsed)";
+            if (firstFailure != null) {
+                msg += "; check failed at least once with exception: " + firstFailure.getMessage() + ", see logs for details";
+            }
+            log.warn(msg+" (throwing)");
+            ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
+            throw new IllegalStateException(msg, firstFailure);
+        }
+    }
+
+    /**
+     * If custom behaviour is required by sub-classes, consider overriding {@link #preStart()} or {@link #postStart()})}.
+     * Also consider adding additional work via tasks, executed using {@link DynamicTasks#queue(String, Callable)}.
+     */
+    @Override
+    public final void start(final Collection<? extends Location> locations) {
+        if (DynamicTasks.getTaskQueuingContext() != null) {
+            getLifecycleEffectorTasks().start(locations);
+        } else {
+            Task<?> task = Tasks.builder().name("start (sequential)").body(new Runnable() { public void run() { getLifecycleEffectorTasks().start(locations); } }).build();
+            Entities.submit(this, task).getUnchecked();
+        }
+    }
+
+    /**
+     * If custom behaviour is required by sub-classes, consider overriding  {@link #preStop()} or {@link #postStop()}.
+     * Also consider adding additional work via tasks, executed using {@link DynamicTasks#queue(String, Callable)}.
+     */
+    @Override
+    public final void stop() {
+        // TODO There is a race where we set SERVICE_UP=false while sensor-adapter threads may still be polling.
+        // The other thread might reset SERVICE_UP to true immediately after we set it to false here.
+        // Deactivating adapters before setting SERVICE_UP reduces the race, and it is reduced further by setting
+        // SERVICE_UP to false at the end of stop as well.
+        
+        // Perhaps we should wait until all feeds have completed here, 
+        // or do a SERVICE_STATE check before setting SERVICE_UP to true in a feed (?).
+
+        if (DynamicTasks.getTaskQueuingContext() != null) {
+            getLifecycleEffectorTasks().stop(ConfigBag.EMPTY);
+        } else {
+            Task<?> task = Tasks.builder().name("stop").body(new Runnable() { public void run() { getLifecycleEffectorTasks().stop(ConfigBag.EMPTY); } }).build();
+            Entities.submit(this, task).getUnchecked();
+        }
+    }
+
+    /**
+     * If custom behaviour is required by sub-classes, consider overriding {@link #preRestart()} or {@link #postRestart()}.
+     * Also consider adding additional work via tasks, executed using {@link DynamicTasks#queue(String, Callable)}.
+     */
+    @Override
+    public final void restart() {
+        if (DynamicTasks.getTaskQueuingContext() != null) {
+            getLifecycleEffectorTasks().restart(ConfigBag.EMPTY);
+        } else {
+            Task<?> task = Tasks.builder().name("restart").body(new Runnable() { public void run() { getLifecycleEffectorTasks().restart(ConfigBag.EMPTY); } }).build();
+            Entities.submit(this, task).getUnchecked();
+        }
+    }
+    
+    protected SoftwareProcessDriverLifecycleEffectorTasks getLifecycleEffectorTasks() {
+        return getConfig(LIFECYCLE_EFFECTOR_TASKS);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcess.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcess.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcess.java
new file mode 100644
index 0000000..1c55ddd
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcess.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import org.apache.brooklyn.api.catalog.Catalog;
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+
+/** 
+ * A {@link SoftwareProcess} entity that runs commands from an archive.
+ * <p>
+ * Downloads and unpacks the archive indicated (optionally) then runs the management commands (scripts) indicated
+ * (relative to the root of the archive if supplied, otherwise in a tmp working dir) to manage. Uses config keys
+ * to identify the files or commands to use.
+ * <p>
+ * In the simplest mode, simply provide either:
+ * <ul>
+ * <li> an archive in {@link #DOWNLOAD_URL} containing a <code>./start.sh</code>
+ * <li> a start command to invoke in {@link #LAUNCH_COMMAND}
+ * </ul>
+ * The only constraint is that the start command must write the PID into the file pointed to by the injected environment
+ * variable {@code PID_FILE} unless one of the options below is supported.
+ * <p>
+ * The start command can be a complex bash command, downloading and unpacking files, and handling the {@code PID_FILE} requirement.
+ * For example {@code export MY_PID_FILE=$PID_FILE ; ./my_start.sh} or {@code nohup ./start.sh & ; echo $! > $PID_FILE ; sleep 5}.
+ * </pre>
+ * You can supply both {@link #DOWNLOAD_URL} and {@link #LAUNCH_COMMAND} configuration as well..
+ * <p>
+ * In addition, you can supply an {@link #INSTALL_COMMAND} and / or a {@link #CUSTOMIZE_COMMAND} to reduce the complexity
+ * of the {@link #LAUNCH_COMMAND}, and to avoid repeating actions that are unnecessary in subsequent launches.
+ * <p>
+ * By default the PID is used to stop the process using {@code kill} followed by {@code kill -9} if needed and restart
+ * is implemented by stopping the process and then running {@link VanillaSoftwareProcessSshDriver#launch()}, but it is
+ * possible to override this behavior through config keys:
+ * <ul>
+ * <li> A custom {@link #CHECK_RUNNING_COMMAND}
+ * <li> A custom {@link #STOP_COMMAND}
+ * <li> A different {@link SoftwareProcess#PID_FILE} to use
+ * <li>
+ */
+@Catalog(name="Vanilla Software Process", description="A software process configured with scripts, e.g. for launch, check-running and stop")
+@ImplementedBy(VanillaSoftwareProcessImpl.class)
+public interface VanillaSoftwareProcess extends AbstractVanillaProcess {
+    ConfigKey<String> LAUNCH_COMMAND = ConfigKeys.newConfigKeyWithDefault(AbstractVanillaProcess.LAUNCH_COMMAND, "./start.sh");
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessDriver.java
new file mode 100644
index 0000000..6fee1d2
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessDriver.java
@@ -0,0 +1,23 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+public interface VanillaSoftwareProcessDriver extends SoftwareProcessDriver {
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessImpl.java
new file mode 100644
index 0000000..6f1aec0
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessImpl.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+
+public class VanillaSoftwareProcessImpl extends SoftwareProcessImpl implements VanillaSoftwareProcess {
+    @Override
+    public Class<?> getDriverInterface() {
+        return VanillaSoftwareProcessDriver.class;
+    }
+    @Override
+    protected void connectSensors() {
+        super.connectSensors();
+        connectServiceUpIsRunning();
+    }
+    @Override
+    protected void disconnectSensors() {
+        disconnectServiceUpIsRunning();
+        super.disconnectSensors();
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessSshDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessSshDriver.java
new file mode 100644
index 0000000..7edb047
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessSshDriver.java
@@ -0,0 +1,162 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.drivers.downloads.DownloadResolver;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelper;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.file.ArchiveUtils;
+import org.apache.brooklyn.util.guava.Maybe;
+import org.apache.brooklyn.util.net.Urls;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.ssh.BashCommands;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.apache.brooklyn.util.text.Strings;
+
+public class VanillaSoftwareProcessSshDriver extends AbstractSoftwareProcessSshDriver implements VanillaSoftwareProcessDriver {
+
+    public VanillaSoftwareProcessSshDriver(EntityLocal entity, SshMachineLocation machine) {
+        super(entity, machine);
+    }
+
+    String downloadedFilename = null;
+
+    /** needed because the download url might be different! */
+    @Override
+    protected String getInstallLabelExtraSalt() {
+        Maybe<Object> url = getEntity().getConfigRaw(SoftwareProcess.DOWNLOAD_URL, true);
+        if (url.isAbsent()) return null;
+        // TODO a user-friendly hash would be nice, but tricky since we don't want it to be too long or contain path chars
+        return Identifiers.makeIdFromHash( url.get().hashCode() );
+    }
+    
+    @Override
+    public void install() {
+        Maybe<Object> url = getEntity().getConfigRaw(SoftwareProcess.DOWNLOAD_URL, true);
+        if (url.isPresentAndNonNull()) {
+            DownloadResolver resolver = Entities.newDownloader(this);
+            List<String> urls = resolver.getTargets();
+            downloadedFilename = resolver.getFilename();
+
+            List<String> commands = new LinkedList<String>();
+            commands.addAll(BashCommands.commandsToDownloadUrlsAs(urls, downloadedFilename));
+            commands.addAll(ArchiveUtils.installCommands(downloadedFilename));
+
+            int result = newScript(INSTALLING)
+                    .failOnNonZeroResultCode(false)
+                    .body.append(commands)
+                    .execute();
+            
+            if (result!=0) {
+                // could not install at remote machine; try resolving URL here and copying across
+                for (String urlI: urls) {
+                    result = ArchiveUtils.install(getMachine(), urlI, Urls.mergePaths(getInstallDir(), downloadedFilename));
+                    if (result==0) 
+                        break;
+                }
+                if (result != 0) 
+                    throw new IllegalStateException("Error installing archive: " + downloadedFilename);
+            }
+        }
+        
+        String installCommand = getEntity().getConfig(VanillaSoftwareProcess.INSTALL_COMMAND);
+        
+        if (Strings.isNonBlank(installCommand)) {
+            newScript(INSTALLING)
+                .failOnNonZeroResultCode()
+                .environmentVariablesReset(getShellEnvironment())
+                .body.append(installCommand)
+                .execute();
+        }
+    }
+
+    @Override
+    public void customize() {
+        if (downloadedFilename != null) {
+            newScript(CUSTOMIZING)
+                    .failOnNonZeroResultCode()
+                    // don't set vars yet -- it resolves dependencies (e.g. DB) which we don't want until we start
+                    .environmentVariablesReset()
+                    .body.append(ArchiveUtils.extractCommands(downloadedFilename, getInstallDir()))
+                    .execute();
+        }
+        
+        String customizeCommand = getEntity().getConfig(VanillaSoftwareProcess.CUSTOMIZE_COMMAND);
+        
+        if (Strings.isNonBlank(customizeCommand)) {
+            newScript(CUSTOMIZING)
+                .failOnNonZeroResultCode()
+                .body.append(customizeCommand)
+                .execute();
+        }
+    }
+
+    @Override
+    public Map<String, String> getShellEnvironment() {
+        return MutableMap.copyOf(super.getShellEnvironment()).add("PID_FILE", getPidFile());
+    }
+
+    public String getPidFile() {
+        // TODO see note in VanillaSoftwareProcess about PID_FILE as a config key
+        // if (getEntity().getConfigRaw(PID_FILE, includeInherited)) ...
+        return Os.mergePathsUnix(getRunDir(), PID_FILENAME);
+    }
+
+    @Override
+    public void launch() {
+        newScript(LAUNCHING)
+            .failOnNonZeroResultCode()
+            .body.append(getEntity().getConfig(VanillaSoftwareProcess.LAUNCH_COMMAND))
+            .execute();
+    }
+
+    @Override
+    public boolean isRunning() {
+        String customCommand = getEntity().getConfig(VanillaSoftwareProcess.CHECK_RUNNING_COMMAND);
+        ScriptHelper script = null;
+        if (customCommand == null) {
+            script = newScript(MutableMap.of(USE_PID_FILE, getPidFile()), CHECK_RUNNING);
+        } else {
+            // TODO: template substitutions?
+            script = newScript(CHECK_RUNNING).body.append(customCommand);
+        }
+        return script.execute() == 0;
+    }
+
+    @Override
+    public void stop() {
+        String customCommand = getEntity().getConfig(VanillaSoftwareProcess.STOP_COMMAND);
+        ScriptHelper script = null;
+        if (customCommand == null) {
+            script = newScript(MutableMap.of(USE_PID_FILE, getPidFile()), STOPPING);
+        } else {
+            // TODO: template substitutions?
+            script = newScript(STOPPING).body.append(customCommand);
+        }
+        script.execute();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcess.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcess.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcess.java
new file mode 100644
index 0000000..1354b03
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcess.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import java.util.Collection;
+
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.util.time.Duration;
+
+import com.google.common.collect.ImmutableSet;
+
+@ImplementedBy(VanillaWindowsProcessImpl.class)
+public interface VanillaWindowsProcess extends AbstractVanillaProcess {
+    // 3389 is RDP; 5985 is WinRM (3389 isn't used by Brooklyn, but useful for the end-user subsequently)
+    ConfigKey<Collection<Integer>> REQUIRED_OPEN_LOGIN_PORTS = ConfigKeys.newConfigKeyWithDefault(
+            SoftwareProcess.REQUIRED_OPEN_LOGIN_PORTS,
+            ImmutableSet.of(5985, 3389));
+    ConfigKey<String> PRE_INSTALL_POWERSHELL_COMMAND = ConfigKeys.newStringConfigKey("pre.install.powershell.command",
+            "powershell command to run during the pre-install phase");
+    ConfigKey<Boolean> PRE_INSTALL_REBOOT_REQUIRED = ConfigKeys.newBooleanConfigKey("pre.install.reboot.required",
+            "indicates that a reboot should be performed after the pre-install command is run", false);
+    ConfigKey<Boolean> INSTALL_REBOOT_REQUIRED = ConfigKeys.newBooleanConfigKey("install.reboot.required",
+            "indicates that a reboot should be performed after the install command is run", false);
+    ConfigKey<Boolean> CUSTOMIZE_REBOOT_REQUIRED = ConfigKeys.newBooleanConfigKey("customize.reboot.required",
+            "indicates that a reboot should be performed after the customize command is run", false);
+    ConfigKey<String> LAUNCH_POWERSHELL_COMMAND = ConfigKeys.newStringConfigKey("launch.powershell.command",
+            "command to run to launch the process");
+    ConfigKey<String> CHECK_RUNNING_POWERSHELL_COMMAND = ConfigKeys.newStringConfigKey("checkRunning.powershell.command",
+            "command to determine whether the process is running");
+    ConfigKey<String> STOP_POWERSHELL_COMMAND = ConfigKeys.newStringConfigKey("stop.powershell.command",
+            "command to run to stop the process");
+    ConfigKey<String> CUSTOMIZE_POWERSHELL_COMMAND = ConfigKeys.newStringConfigKey("customize.powershell.command",
+            "powershell command to run during the customization phase");
+    ConfigKey<String> INSTALL_POWERSHELL_COMMAND = ConfigKeys.newStringConfigKey("install.powershell.command",
+            "powershell command to run during the install phase");
+    ConfigKey<Duration> REBOOT_BEGUN_TIMEOUT = ConfigKeys.newDurationConfigKey("reboot.begun.timeout",
+            "duration to wait whilst waiting for a machine to begin rebooting, and thus become unavailable", Duration.TWO_MINUTES);
+    // TODO If automatic updates are enabled and there are updates waiting to be installed, thirty minutes may not be sufficient...
+    ConfigKey<Duration> REBOOT_COMPLETED_TIMEOUT = ConfigKeys.newDurationConfigKey("reboot.completed.timeout",
+            "duration to wait whilst waiting for a machine to finish rebooting, and thus to become available again", Duration.minutes(30));
+    
+    AttributeSensor<Integer> RDP_PORT = Sensors.newIntegerSensor("rdpPort");
+    AttributeSensor<Integer> WINRM_PORT = Sensors.newIntegerSensor("winrmPort");
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessDriver.java
new file mode 100644
index 0000000..a6083ff
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessDriver.java
@@ -0,0 +1,23 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+public interface VanillaWindowsProcessDriver extends SoftwareProcessDriver {
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessImpl.java
new file mode 100644
index 0000000..b3b9f83
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessImpl.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+
+public class VanillaWindowsProcessImpl extends SoftwareProcessImpl implements VanillaWindowsProcess {
+    @Override
+    public Class getDriverInterface() {
+        return VanillaWindowsProcessDriver.class;
+    }
+
+    @Override
+    protected void preStart() {
+        super.preStart();
+        setAttribute(RDP_PORT, 3389);
+        setAttribute(WINRM_PORT, 5985);
+    }
+    
+    @Override
+    protected void connectSensors() {
+        super.connectSensors();
+        connectServiceUpIsRunning();
+    }
+
+    @Override
+    protected void disconnectSensors() {
+        disconnectServiceUpIsRunning();
+        super.disconnectSensors();
+    }
+
+}


[70/72] [abbrv] incubator-brooklyn git commit: Add missing lib\ segment to library ‘patch’ and ‘droppins’ dirs

Posted by he...@apache.org.
Add missing lib\ segment to library ‘patch’ and ‘droppins’ dirs

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

Branch: refs/heads/master
Commit: 3fdd120793dbe8e110d178516df9e2e5dfa6fbcc
Parents: ce5ddaf
Author: Alasdair Hodge <gi...@alasdairhodge.co.uk>
Authored: Wed Aug 19 10:33:26 2015 +0100
Committer: Alasdair Hodge <gi...@alasdairhodge.co.uk>
Committed: Wed Aug 19 11:13:33 2015 +0100

----------------------------------------------------------------------
 usage/dist/src/main/dist/bin/brooklyn.ps1 | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/3fdd1207/usage/dist/src/main/dist/bin/brooklyn.ps1
----------------------------------------------------------------------
diff --git a/usage/dist/src/main/dist/bin/brooklyn.ps1 b/usage/dist/src/main/dist/bin/brooklyn.ps1
index 209517d..6780ed2 100644
--- a/usage/dist/src/main/dist/bin/brooklyn.ps1
+++ b/usage/dist/src/main/dist/bin/brooklyn.ps1
@@ -81,14 +81,14 @@ if ( $javabin -eq $null ) {
 # set up the classpath
 $cp = Get-ChildItem ${BROOKLYN_HOME}\conf | Select-Object -ExpandProperty FullName
 
-if ( Test-Path ${BROOKLYN_HOME}\patch ) {
-    $cp += Get-ChildItem ${BROOKLYN_HOME}\patch | Select-Object -ExpandProperty FullName
+if ( Test-Path ${BROOKLYN_HOME}\lib\patch ) {
+    $cp += Get-ChildItem ${BROOKLYN_HOME}\lib\patch | Select-Object -ExpandProperty FullName
 }
 
 $cp += Get-ChildItem ${BROOKLYN_HOME}\lib\brooklyn | Select-Object -ExpandProperty FullName
 
-if ( Test-Path ${BROOKLYN_HOME}\dropins ) {
-    $cp += Get-ChildItem ${BROOKLYN_HOME}\dropins | Select-Object -ExpandProperty FullName
+if ( Test-Path ${BROOKLYN_HOME}\lib\dropins ) {
+    $cp += Get-ChildItem ${BROOKLYN_HOME}\lib\dropins | Select-Object -ExpandProperty FullName
 }
 
 $INITIAL_CLASSPATH = $cp -join ';'


[56/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/LocationPredicates.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/LocationPredicates.java b/core/src/main/java/org/apache/brooklyn/location/core/LocationPredicates.java
new file mode 100644
index 0000000..3491dc4
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/LocationPredicates.java
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.config.ConfigKey.HasConfigKey;
+
+import com.google.common.base.Objects;
+import com.google.common.base.Predicate;
+
+public class LocationPredicates {
+
+    public static <T> Predicate<Location> idEqualTo(final T val) {
+        return new Predicate<Location>() {
+            @Override
+            public boolean apply(@Nullable Location input) {
+                return (input != null) && Objects.equal(input.getId(), val);
+            }
+        };
+    }
+    
+    public static <T> Predicate<Location> displayNameEqualTo(final T val) {
+        return new Predicate<Location>() {
+            @Override
+            public boolean apply(@Nullable Location input) {
+                return (input != null) && Objects.equal(input.getDisplayName(), val);
+            }
+        };
+    }
+    
+    public static <T> Predicate<Location> configEqualTo(final ConfigKey<T> configKey, final T val) {
+        return new Predicate<Location>() {
+            @Override
+            public boolean apply(@Nullable Location input) {
+                return (input != null) && Objects.equal(input.getConfig(configKey), val);
+            }
+        };
+    }
+
+    public static <T> Predicate<Location> configEqualTo(final HasConfigKey<T> configKey, final T val) {
+        return new Predicate<Location>() {
+            @Override
+            public boolean apply(@Nullable Location input) {
+                return (input != null) && Objects.equal(input.getConfig(configKey), val);
+            }
+        };
+    }
+
+    /**
+     * Returns a predicate that determines if a given location is a direct child of this {@code parent}.
+     */
+    public static <T> Predicate<Location> isChildOf(final Location parent) {
+        return new Predicate<Location>() {
+            @Override
+            public boolean apply(@Nullable Location input) {
+                return (input != null) && Objects.equal(input.getParent(), parent);
+            }
+        };
+    }
+
+    /**
+     * Returns a predicate that determines if a given location is a descendant of this {@code ancestor}.
+     */
+    public static <T> Predicate<Location> isDescendantOf(final Location ancestor) {
+        return new Predicate<Location>() {
+            @Override
+            public boolean apply(@Nullable Location input) {
+                // assumes impossible to have cycles in location-hierarchy
+                Location contenderAncestor = (input == null) ? input : input.getParent();
+                while (contenderAncestor != null) {
+                    if (Objects.equal(contenderAncestor, ancestor)) {
+                        return true;
+                    }
+                    contenderAncestor = contenderAncestor.getParent();
+                }
+                return false;
+            }
+        };
+    }
+
+    public static <T> Predicate<Location> managed() {
+        return new Predicate<Location>() {
+            @Override
+            public boolean apply(@Nullable Location input) {
+                return (input != null) && Locations.isManaged(input);
+            }
+        };
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/LocationPropertiesFromBrooklynProperties.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/LocationPropertiesFromBrooklynProperties.java b/core/src/main/java/org/apache/brooklyn/location/core/LocationPropertiesFromBrooklynProperties.java
new file mode 100644
index 0000000..fd1b92a
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/LocationPropertiesFromBrooklynProperties.java
@@ -0,0 +1,223 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+import java.io.File;
+import java.util.Map;
+
+import org.apache.brooklyn.core.config.ConfigUtils;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.server.BrooklynServerConfig;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.internal.ssh.SshTool;
+import org.apache.brooklyn.util.os.Os;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Predicates;
+import com.google.common.base.Strings;
+import com.google.common.collect.Maps;
+
+/**
+ * The properties to use for locations, loaded from brooklyn.properties file.
+ * 
+ * @author aledsage
+ **/
+public class LocationPropertiesFromBrooklynProperties {
+
+    private static final Logger LOG = LoggerFactory.getLogger(LocationPropertiesFromBrooklynProperties.class);
+
+    @SuppressWarnings("deprecation")
+    protected static final Map<String, String> DEPRECATED_KEYS_MAPPING = new DeprecatedKeysMappingBuilder(LOG)
+            .camelToHyphen(LocationConfigKeys.DISPLAY_NAME)
+            .camelToHyphen(LocationConfigKeys.PRIVATE_KEY_FILE)
+            .camelToHyphen(LocationConfigKeys.PRIVATE_KEY_DATA)
+            .camelToHyphen(LocationConfigKeys.PRIVATE_KEY_PASSPHRASE)
+            .camelToHyphen(LocationConfigKeys.PUBLIC_KEY_FILE)
+            .camelToHyphen(LocationConfigKeys.PUBLIC_KEY_DATA)
+            .camelToHyphen(LocationConfigKeys.CALLER_CONTEXT)
+            .build();
+    
+    /**
+     * Finds the properties that apply to location, stripping off the prefixes.
+     * 
+     * Order of preference (in ascending order) is:
+     * <ol>
+     * <li>brooklyn.location.*
+     * <li>brooklyn.location.provider.*
+     * <li>brooklyn.location.named.namedlocation.*
+     * </ol>
+     * <p>
+     * Converts deprecated hyphenated properties to the non-deprecated camelCase format. 
+     */
+    public Map<String, Object> getLocationProperties(String provider, String namedLocation, Map<String, ?> properties) {
+        ConfigBag result = ConfigBag.newInstance();
+        
+        if (!Strings.isNullOrEmpty(provider)) 
+            result.put(LocationConfigKeys.CLOUD_PROVIDER, provider);
+        // named properties are preferred over providerOrApi properties
+        result.putAll(transformDeprecated(getGenericLocationSingleWordProperties(properties)));
+        if (!Strings.isNullOrEmpty(provider)) result.putAll(transformDeprecated(getScopedLocationProperties(provider, properties)));
+        if (!Strings.isNullOrEmpty(namedLocation)) result.putAll(transformDeprecated(getNamedLocationProperties(namedLocation, properties)));
+        
+        setLocalTempDir(properties, result);
+        
+        return result.getAllConfigRaw();
+    }
+
+    /** allow the temp dir where ssh temporary files on the brooklyn server side are placed */
+    public static void setLocalTempDir(Map<String,?> source, ConfigBag target) {
+        // TODO better would be to use BrooklynServerConfig, requiring management passed in
+        String brooklynDataDir = (String) source.get(BrooklynServerConfig.getMgmtBaseDir(source));
+        if (brooklynDataDir != null && brooklynDataDir.length() > 0) {
+            String tempDir = Os.mergePaths(brooklynDataDir, "tmp", "ssh");
+            target.putIfAbsentAndNotNull(SshTool.PROP_LOCAL_TEMP_DIR, tempDir);
+            Os.deleteOnExitEmptyParentsUpTo(new File(tempDir), new File(brooklynDataDir));
+        }
+    }
+    
+    /**
+     * Gets the named provider (e.g. if using a property like {@code brooklyn.location.named.myfavourite=localhost}, then
+     * {@code getNamedProvider("myfavourite", properties)} will return {@code "localhost"}).
+     */
+    protected String getNamedProvider(String namedLocation, Map<String, ?> properties) {
+        String key = String.format("brooklyn.location.named.%s", namedLocation);
+        return (String) properties.get(key);
+    }
+    
+    /**
+     * Returns those properties in the form "brooklyn.location.xyz", where "xyz" is any
+     * key that does not contain dots. We do this special (sub-optimal!) filtering
+     * because we want to exclude brooklyn.location.named.*, brooklyn.location.jclouds.*, etc.
+     * We only want those properties that are to be generic for all locations.
+     * 
+     * Strips off the prefix in the returned map.
+     */
+    protected Map<String, Object> getGenericLocationSingleWordProperties(Map<String, ?> properties) {
+        return getMatchingSingleWordProperties("brooklyn.location.", properties);
+    }
+
+    /**
+     * Gets all properties that start with {@code "brooklyn.location."+scopeSuffix+"."}, stripping off
+     * the prefix in the returned map.
+     */
+    protected Map<String, Object> getScopedLocationProperties(String scopeSuffix, Map<String, ?> properties) {
+        checkArgument(!scopeSuffix.startsWith("."), "scopeSuffix \"%s\" should not start with \".\"", scopeSuffix);
+        checkArgument(!scopeSuffix.endsWith("."), "scopeSuffix \"%s\" should not end with \".\"", scopeSuffix);
+        String prefix = String.format("brooklyn.location.%s.", scopeSuffix);
+        return ConfigUtils.filterForPrefixAndStrip(properties, prefix).asMapWithStringKeys();
+    }
+
+    /**
+     * Gets all properties that start with the given {@code fullPrefix}, stripping off
+     * the prefix in the returned map.
+     */
+    protected Map<String, Object> getMatchingProperties(String fullPrefix, Map<String, ?> properties) {
+        return ConfigUtils.filterForPrefixAndStrip(properties, fullPrefix).asMapWithStringKeys();
+    }
+
+    /**
+     * Gets all properties that start with either of the given prefixes. The {@code fullPreferredPrefix} 
+     * properties will override any duplicates in {@code fullDeprecatedPrefix}. If there are any
+     * properties that match the {@code fullDeprecatedPrefix}, then a warning will be logged.
+     * 
+     * @see #getMatchingProperties(String, Map)
+     */
+    protected Map<String, Object> getMatchingProperties(String fullPreferredPrefix, String fullDeprecatedPrefix, Map<String, ?> properties) {
+        Map<String, Object> deprecatedResults = getMatchingProperties(fullDeprecatedPrefix, properties);
+        Map<String, Object> results = getMatchingProperties(fullPreferredPrefix, properties);
+        
+        if (deprecatedResults.size() > 0) {
+            LOG.warn("Deprecated use of properties prefix "+fullDeprecatedPrefix+"; instead use "+fullPreferredPrefix);
+            return MutableMap.<String, Object>builder()
+                    .putAll(deprecatedResults)
+                    .putAll(results)
+                    .build();
+        } else {
+            return results;
+        }
+    }
+
+    /**
+     * Gets all properties that start with the given {@code fullPrefix}, stripping off
+     * the prefix in the returned map.
+     * 
+     * Returns only those properties whose key suffix is a single word (i.e. contains no dots).
+     * We do this special (sub-optimal!) filtering because we want sub-scoped things 
+     * (e.g. could want brooklyn.location.privateKeyFile, but not brooklyn.location.named.*). 
+     */
+    protected Map<String, Object> getMatchingSingleWordProperties(String fullPrefix, Map<String, ?> properties) {
+        BrooklynProperties filteredProperties = ConfigUtils.filterForPrefixAndStrip(properties, fullPrefix);
+        return ConfigUtils.filterFor(filteredProperties, Predicates.not(Predicates.containsPattern("\\."))).asMapWithStringKeys();
+    }
+
+    /**
+     * Gets all single-word properties that start with either of the given prefixes. The {@code fullPreferredPrefix} 
+     * properties will override any duplicates in {@code fullDeprecatedPrefix}. If there are any
+     * properties that match the {@code fullDeprecatedPrefix}, then a warning will be logged.
+     * 
+     * @see #getMatchingSingleWordProperties(String, Map)
+     */
+    protected Map<String, Object> getMatchingSingleWordProperties(String fullPreferredPrefix, String fullDeprecatedPrefix, Map<String, ?> properties) {
+        Map<String, Object> deprecatedResults = getMatchingSingleWordProperties(fullDeprecatedPrefix, properties);
+        Map<String, Object> results = getMatchingSingleWordProperties(fullPreferredPrefix, properties);
+        
+        if (deprecatedResults.size() > 0) {
+            LOG.warn("Deprecated use of properties prefix "+fullDeprecatedPrefix+"; instead use "+fullPreferredPrefix);
+            return MutableMap.<String, Object>builder()
+                    .putAll(deprecatedResults)
+                    .putAll(results)
+                    .build();
+        } else {
+            return results;
+        }
+    }
+
+    protected Map<String, Object> getNamedLocationProperties(String locationName, Map<String, ?> properties) {
+        checkArgument(!Strings.isNullOrEmpty(locationName), "locationName should not be blank");
+        String prefix = String.format("brooklyn.location.named.%s.", locationName);
+        return ConfigUtils.filterForPrefixAndStrip(properties, prefix).asMapWithStringKeys();
+    }
+
+    protected Map<String, Object> transformDeprecated(Map<String, ?> properties) {
+        Map<String,Object> result = Maps.newLinkedHashMap();
+        Map<String, String> deprecatedKeysMapping = getDeprecatedKeysMapping();
+        
+        for (Map.Entry<String,?> entry : properties.entrySet()) {
+            String key = entry.getKey();
+            Object value = entry.getValue();
+            if (deprecatedKeysMapping.containsKey(key)) {
+                String transformedKey = deprecatedKeysMapping.get(key);
+                LOG.warn("Deprecated key {}, transformed to {}; will not be supported in future versions", new Object[] {key, transformedKey});
+                result.put(transformedKey, value);
+            } else {
+                result.put(key, value);
+            }
+        }
+        
+        return result;
+    }
+    
+    protected Map<String,String> getDeprecatedKeysMapping() {
+        return DEPRECATED_KEYS_MAPPING;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/Locations.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/Locations.java b/core/src/main/java/org/apache/brooklyn/location/core/Locations.java
new file mode 100644
index 0000000..663624f
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/Locations.java
@@ -0,0 +1,160 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.mgmt.LocationManager;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.guava.Maybe;
+import org.apache.brooklyn.util.yaml.Yamls;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.ImmutableList;
+
+public class Locations {
+
+    private static final Logger log = LoggerFactory.getLogger(Locations.class);
+
+    public static final LocationsFilter USE_FIRST_LOCATION = new LocationsFilter() {
+        private static final long serialVersionUID = 3100091615409115890L;
+
+        @Override
+        public List<Location> filterForContext(List<Location> locations, Object context) {
+            if (locations.size()<=1) return locations;
+            return ImmutableList.of(locations.get(0));
+        }
+    };
+
+    public interface LocationsFilter extends Serializable {
+        public List<Location> filterForContext(List<Location> locations, Object context);
+    }
+    
+    /** as {@link Machines#findUniqueMachineLocation(Iterable)} */
+    public static Maybe<MachineLocation> findUniqueMachineLocation(Iterable<? extends Location> locations) {
+        return Machines.findUniqueMachineLocation(locations);
+    }
+    
+    /** as {@link Machines#findUniqueSshMachineLocation(Iterable)} */
+    public static Maybe<SshMachineLocation> findUniqueSshMachineLocation(Iterable<? extends Location> locations) {
+        return Machines.findUniqueSshMachineLocation(locations);
+    }
+
+    /** if no locations are supplied, returns locations on the entity, or in the ancestors, until it finds a non-empty set,
+     * or ultimately the empty set if no locations are anywhere */ 
+    public static Collection<? extends Location> getLocationsCheckingAncestors(Collection<? extends Location> locations, Entity entity) {
+        // look in ancestors if location not set here
+        Entity ancestor = entity;
+        while ((locations==null || locations.isEmpty()) && ancestor!=null) {
+            locations = ancestor.getLocations();
+            ancestor = ancestor.getParent();
+        }
+        return locations;
+    }
+    
+    public static boolean isManaged(Location loc) {
+        ManagementContext mgmt = ((LocationInternal)loc).getManagementContext();
+        return (mgmt != null) && mgmt.isRunning() && mgmt.getLocationManager().isManaged(loc);
+    }
+
+    public static void unmanage(Location loc) {
+        if (isManaged(loc)) {
+            ManagementContext mgmt = ((LocationInternal)loc).getManagementContext();
+            mgmt.getLocationManager().unmanage(loc);
+        }
+    }
+    
+    /**
+     * Registers the given location (and all its children) with the management context. 
+     * @throws IllegalStateException if the parent location is not already managed
+     * 
+     * @since 0.6.0 (added only for backwards compatibility, where locations are being created directly; previously in {@link Entities}).
+     * @deprecated in 0.6.0; use {@link LocationManager#createLocation(LocationSpec)} instead.
+     */
+    public static void manage(Location loc, ManagementContext managementContext) {
+        if (!managementContext.getLocationManager().isManaged(loc)) {
+            log.warn("Deprecated use of unmanaged location ("+loc+"); will be managed automatically now but not supported in future versions");
+            // FIXME this occurs MOST OF THE TIME e.g. including BrooklynLauncher.location(locationString)
+            // not sure what is the recommend way to convert from locationString to locationSpec, or the API we want to expose;
+            // deprecating some of the LocationRegistry methods seems sensible?
+            log.debug("Stack trace for location of: Deprecated use of unmanaged location; will be managed automatically now but not supported in future versions", new Exception("TRACE for: Deprecated use of unmanaged location"));
+            managementContext.getLocationManager().manage(loc);
+        }
+    }
+
+    public static Location coerce(ManagementContext mgmt, Object rawO) {
+        if (rawO==null)
+            return null;
+        if (rawO instanceof Location)
+            return (Location)rawO;
+        
+        Object raw = rawO;
+        if (raw instanceof String)
+            raw = Yamls.parseAll((String)raw).iterator().next();
+        
+        String name;
+        Map<?, ?> flags = null;
+        if (raw instanceof Map) {
+            // for yaml, take the key, and merge with locationFlags
+            Map<?,?> tm = ((Map<?,?>)raw);
+            if (tm.size()!=1) {
+                throw new IllegalArgumentException("Location "+rawO+" is invalid; maps must have only one key, being the location spec string");
+            }
+            name = (String) tm.keySet().iterator().next();
+            flags = (Map<?, ?>) tm.values().iterator().next();
+            
+        } else if (raw instanceof String) {
+            name = (String)raw;
+            
+        } else {
+            throw new IllegalArgumentException("Location "+rawO+" is invalid; can only parse strings or maps");
+        }
+        return mgmt.getLocationRegistry().resolve(name, flags);
+    }
+    
+    public static Collection<? extends Location> coerceToCollection(ManagementContext mgmt, Object rawO) {
+        if (rawO==null) return null;
+        Object raw = rawO;
+        if (raw instanceof Collection) {
+            List<Location> result = MutableList.<Location>of();
+            for (Object o: (Collection<?>)raw)
+                result.add(coerce(mgmt, o));
+            return result;
+        }
+        if (raw instanceof String) {
+            raw = Yamls.parseAll((String)raw).iterator().next();
+            if (raw instanceof Collection)
+                return coerceToCollection(mgmt, raw);
+        }
+        return Collections.singletonList( coerce(mgmt, raw) );
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/Machines.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/Machines.java b/core/src/main/java/org/apache/brooklyn/location/core/Machines.java
new file mode 100644
index 0000000..164e4ae
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/Machines.java
@@ -0,0 +1,191 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import java.net.InetAddress;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Iterables;
+
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation.LocalhostMachine;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.location.winrm.WinRmMachineLocation;
+import org.apache.brooklyn.util.guava.Maybe;
+import org.apache.brooklyn.util.net.HasNetworkAddresses;
+
+/** utilities for working with MachineLocations */
+public class Machines {
+
+    private static final Logger log = LoggerFactory.getLogger(Machines.class);
+    
+    public static Maybe<String> getSubnetHostname(Location where) {
+        // TODO Should we look at HasNetworkAddresses? But that's not a hostname.
+        String hostname = null;
+        if (where instanceof HasSubnetHostname) {
+            hostname = ((HasSubnetHostname) where).getSubnetHostname();
+        }
+        if (hostname == null && where instanceof MachineLocation) {
+            InetAddress addr = ((MachineLocation) where).getAddress();
+            if (addr != null) hostname = addr.getHostAddress();
+        }
+        log.debug("computed subnet hostname {} for {}", hostname, where);
+        // TODO if Maybe.absent(message) appears, could/should use that
+        // TODO If no machine available, should we throw new IllegalStateException("Cannot find hostname for "+where);
+        return Maybe.fromNullable(hostname);
+    }
+
+    public static Maybe<String> getSubnetIp(Location where) {
+        // TODO Too much duplication between the ip and hostname methods
+        String result = null;
+        if (where instanceof HasSubnetHostname) {
+            result = ((HasSubnetHostname) where).getSubnetIp();
+        }
+        if (where instanceof HasNetworkAddresses) {
+            Set<String> privateAddrs = ((HasNetworkAddresses) where).getPrivateAddresses();
+            if (privateAddrs.size() > 0) {
+                result = Iterables.get(privateAddrs, 0);
+            }
+        }
+        if (result == null && where instanceof MachineLocation) {
+            InetAddress addr = ((MachineLocation) where).getAddress();
+            if (addr != null) result = addr.getHostAddress();
+        }
+        log.debug("computed subnet host ip {} for {}", result, where);
+        return Maybe.fromNullable(result);
+    }
+
+    @SuppressWarnings("unchecked")
+    public static <T> Maybe<T> findUniqueElement(Iterable<?> items, Class<T> type) {
+        if (items==null) return null;
+        Iterator<?> i = items.iterator();
+        T result = null;
+        while (i.hasNext()) {
+            Object candidate = i.next();
+            if (type.isInstance(candidate)) {
+                if (result==null) result = (T)candidate;
+                else {
+                    if (log.isTraceEnabled())
+                        log.trace("Multiple instances of "+type+" in "+items+"; ignoring");
+                    return Maybe.absent(new IllegalStateException("Multiple instances of "+type+" in "+items+"; expected a single one"));
+                }
+            }
+        }
+        if (result==null) 
+            return Maybe.absent(new IllegalStateException("No instances of "+type+" available (in "+items+")"));
+        return Maybe.of(result);
+    }
+    
+    public static Maybe<MachineLocation> findUniqueMachineLocation(Iterable<? extends Location> locations) {
+        return findUniqueElement(locations, MachineLocation.class);
+    }
+
+    public static Maybe<SshMachineLocation> findUniqueSshMachineLocation(Iterable<? extends Location> locations) {
+        return findUniqueElement(locations, SshMachineLocation.class);
+    }
+
+    public static Maybe<WinRmMachineLocation> findUniqueWinRmMachineLocation(Iterable<? extends Location> locations) {
+        return findUniqueElement(locations, WinRmMachineLocation.class);
+    }
+
+    public static Maybe<String> findSubnetHostname(Iterable<? extends Location> ll) {
+        Maybe<MachineLocation> l = findUniqueMachineLocation(ll);
+        if (!l.isPresent()) {
+            return Maybe.absent();
+//            throw new IllegalStateException("Cannot find hostname for among "+ll);
+        }
+        return Machines.getSubnetHostname(l.get());
+    }
+
+    public static Maybe<String> findSubnetHostname(Entity entity) {
+        String sh = entity.getAttribute(Attributes.SUBNET_HOSTNAME);
+        if (sh!=null) return Maybe.of(sh);
+        return findSubnetHostname(entity.getLocations());
+    }
+    
+    public static Maybe<String> findSubnetOrPublicHostname(Entity entity) {
+        String hn = entity.getAttribute(Attributes.HOSTNAME);
+        if (hn!=null) {
+            // attributes already set, see if there was a SUBNET_HOSTNAME set
+            // note we rely on (public) hostname being set _after_ subnet_hostname,
+            // to prevent tiny possibility of races resulting in hostname being returned
+            // becasue subnet is still being looked up -- see MachineLifecycleEffectorTasks
+            Maybe<String> sn = findSubnetHostname(entity);
+            if (sn.isPresent()) return sn;
+            // short-circuit discovery if attributes have been set already
+            return Maybe.of(hn);
+        }
+        
+        Maybe<MachineLocation> l = findUniqueMachineLocation(entity.getLocations());
+        if (!l.isPresent()) return Maybe.absent();
+        InetAddress addr = l.get().getAddress();
+        if (addr==null) return Maybe.absent();
+        return Maybe.fromNullable(addr.getHostName());
+    }
+
+    public static Maybe<String> findSubnetOrPrivateIp(Entity entity) {
+        // see comments in findSubnetOrPrivateHostname
+        String hn = entity.getAttribute(Attributes.ADDRESS);
+        if (hn!=null) {
+            Maybe<String> sn = findSubnetIp(entity);
+            if (sn.isPresent()) return sn;
+            return Maybe.of(hn);
+        }
+        
+        Maybe<MachineLocation> l = findUniqueMachineLocation(entity.getLocations());
+        if (!l.isPresent()) return Maybe.absent();
+        InetAddress addr = l.get().getAddress();
+        if (addr==null) return Maybe.absent();
+        return Maybe.fromNullable(addr.getHostAddress());
+    }
+
+    public static Maybe<String> findSubnetIp(Entity entity) {
+        String sh = entity.getAttribute(Attributes.SUBNET_ADDRESS);
+        if (sh!=null) return Maybe.of(sh);
+        return findSubnetIp(entity.getLocations());
+    }
+    
+    public static Maybe<String> findSubnetIp(Iterable<? extends Location> ll) {
+        // TODO Or if can't find MachineLocation, should we throw new IllegalStateException("Cannot find hostname for among "+ll);
+        Maybe<MachineLocation> l = findUniqueMachineLocation(ll);
+        return (l.isPresent()) ? Machines.getSubnetIp(l.get()) : Maybe.<String>absent();
+    }
+
+    /** returns whether it is localhost (and has warned) */
+    public static boolean warnIfLocalhost(Collection<? extends Location> locations, String message) {
+        if (locations.size()==1) {
+            Location l = locations.iterator().next();
+            if (l instanceof LocalhostMachineProvisioningLocation || l instanceof LocalhostMachine) {
+                log.warn(message);
+                return true;
+            }
+        }
+        return false;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/MultiLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/MultiLocation.java b/core/src/main/java/org/apache/brooklyn/location/core/MultiLocation.java
new file mode 100644
index 0000000..9f52244
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/MultiLocation.java
@@ -0,0 +1,166 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static com.google.common.base.Preconditions.checkState;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.location.cloud.AbstractAvailabilityZoneExtension;
+import org.apache.brooklyn.location.cloud.AvailabilityZoneExtension;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+import org.apache.brooklyn.util.exceptions.CompoundRuntimeException;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.text.Strings;
+
+import com.google.common.base.Predicate;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Maps;
+import com.google.common.reflect.TypeToken;
+
+/** A location which consists of multiple locations stitched together to form availability zones.
+ * The first location will be used by default, but if an {@link AvailabilityZoneExtension}-aware entity
+ * is used, it may stripe across each of the locations.  See notes at {@link AvailabilityZoneExtension}. */
+public class MultiLocation<T extends MachineLocation> extends AbstractLocation implements MachineProvisioningLocation<T> {
+
+    private static final long serialVersionUID = 7993091317970457862L;
+    
+    @SuppressWarnings("serial")
+    @SetFromFlag("subLocations")
+    public static final ConfigKey<List<MachineProvisioningLocation<?>>> SUB_LOCATIONS = ConfigKeys.newConfigKey(
+            new TypeToken<List<MachineProvisioningLocation<?>>>() {},
+            "subLocations", 
+            "The sub-machines that this location can delegate to");
+    
+    @Override
+    public void init() {
+        super.init();
+        List<MachineProvisioningLocation<?>> subLocs = getSubLocations();
+        checkState(subLocs.size() >= 1, "sub-locations must not be empty");
+        AvailabilityZoneExtension azExtension = new AvailabilityZoneExtensionImpl(getManagementContext(), subLocs);
+        addExtension(AvailabilityZoneExtension.class, azExtension);
+    }
+
+    public T obtain() throws NoMachinesAvailableException {
+        return obtain(MutableMap.of());
+    }
+    
+    /** finds (creates) and returns a {@link MachineLocation}; 
+     * this always tries the first sub-location, moving on the second and subsequent if the first throws {@link NoMachinesAvailableException}.
+     * (if you want striping across locations, see notes in {@link AvailabilityZoneExtension}.) */
+    @SuppressWarnings("unchecked")
+    @Override
+    public T obtain(Map<?, ?> flags) throws NoMachinesAvailableException {
+        List<MachineProvisioningLocation<?>> sublocsList = getSubLocations();
+        Iterator<MachineProvisioningLocation<?>> sublocs = sublocsList.iterator();
+        List<NoMachinesAvailableException> errors = MutableList.of();
+        while (sublocs.hasNext()) {
+            try {
+                return (T) sublocs.next().obtain(flags);
+            } catch (NoMachinesAvailableException e) {
+                errors.add(e);
+            }
+        }
+        Exception wrapped;
+        String msg;
+        if (errors.size()>1) {
+            wrapped = new CompoundRuntimeException(errors.size()+" sublocation exceptions, including: "+
+                Exceptions.collapseText(errors.get(0)), errors);
+            msg = Exceptions.collapseText(wrapped);
+        } else if (errors.size()==1) {
+            wrapped = errors.get(0);
+            msg = wrapped.getMessage();
+            if (Strings.isBlank(msg)) msg = wrapped.toString();
+        } else {
+            msg = "no sub-locations set for this multi-location";
+            wrapped = null;
+        }
+        throw new NoMachinesAvailableException("No machines available in any of the "+sublocsList.size()+" location"+Strings.s(sublocsList.size())+
+            " configured here: "+msg, wrapped);
+    }
+
+    public List<MachineProvisioningLocation<?>> getSubLocations() {
+        return getRequiredConfig(SUB_LOCATIONS);
+    }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public MachineProvisioningLocation<T> newSubLocation(Map<?, ?> newFlags) {
+        // TODO shouldn't have to copy config bag as it should be inherited (but currently it is not used inherited everywhere; just most places)
+        return getManagementContext().getLocationManager().createLocation(LocationSpec.create(getClass())
+                .parent(this)
+                .configure(config().getLocalBag().getAllConfig())  // FIXME Should this just be inherited?
+                .configure(newFlags));
+    }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public void release(T machine) {
+        ((MachineProvisioningLocation<T>)machine.getParent()).release(machine);
+    }
+
+    @Override
+    public Map<String, Object> getProvisioningFlags(Collection<String> tags) {
+        return Maps.<String,Object>newLinkedHashMap();
+    }
+
+    @SuppressWarnings("unchecked")
+    protected MachineProvisioningLocation<T> firstSubLoc() {
+        return (MachineProvisioningLocation<T>) Iterables.get(getSubLocations(), 0);
+    }
+
+    protected <K> K getRequiredConfig(ConfigKey<K> key) {
+        return checkNotNull(getConfig(key), key.getName());
+    }
+
+    public static class AvailabilityZoneExtensionImpl extends AbstractAvailabilityZoneExtension implements AvailabilityZoneExtension {
+
+        private final List<MachineProvisioningLocation<?>> subLocations;
+        
+        public AvailabilityZoneExtensionImpl(ManagementContext managementContext, List<MachineProvisioningLocation<?>> subLocations) {
+            super(managementContext);
+            this.subLocations = ImmutableList.copyOf(subLocations);
+        }
+        
+        @Override
+        protected List<Location> doGetAllSubLocations() {
+            return ImmutableList.<Location>copyOf(subLocations);
+        }
+        
+        @Override
+        protected boolean isNameMatch(Location loc, Predicate<? super String> namePredicate) {
+            return namePredicate.apply(loc.getDisplayName());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/MultiLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/MultiLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/core/MultiLocationResolver.java
new file mode 100644
index 0000000..e20661f
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/MultiLocationResolver.java
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationRegistry;
+import org.apache.brooklyn.api.location.LocationResolver;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.text.KeyValueParser;
+import org.apache.brooklyn.util.text.StringEscapes.JavaStringEscapes;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Lists;
+
+public class MultiLocationResolver implements LocationResolver {
+
+    private static final Logger LOG = LoggerFactory.getLogger(MultiLocationResolver.class);
+
+    private static final String MULTI = "multi";
+    
+    private static final Pattern PATTERN = Pattern.compile("(" + MULTI + "|" + MULTI.toUpperCase() + ")" + ":" + "\\((.*)\\)$");
+    
+    private volatile ManagementContext managementContext;
+
+    @Override
+    public void init(ManagementContext managementContext) {
+        this.managementContext = checkNotNull(managementContext, "managementContext");
+    }
+
+    @Override
+    public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
+        // FIXME pass all flags into the location
+        
+        Map globalProperties = registry.getProperties();
+        Map<String,?> locationArgs;
+        if (spec.equalsIgnoreCase(MULTI)) {
+            locationArgs = MutableMap.copyOf(locationFlags);
+        } else {
+            Matcher matcher = PATTERN.matcher(spec);
+            if (!matcher.matches()) {
+                throw new IllegalArgumentException("Invalid location '" + spec + "'; must specify something like multi(targets=named:foo)");
+            }
+            String args = matcher.group(2);
+            // TODO we are ignoring locationFlags after this (apart from named), looking only at these args
+            locationArgs = KeyValueParser.parseMap(args);
+        }
+        String namedLocation = (String) locationFlags.get("named");
+
+        Map<String, Object> filteredProperties = new LocationPropertiesFromBrooklynProperties().getLocationProperties(null, namedLocation, globalProperties);
+        MutableMap<String, Object> flags = MutableMap.<String, Object>builder()
+                .putAll(filteredProperties)
+                .putAll(locationFlags)
+                .removeAll("named")
+                .putAll(locationArgs).build();
+        
+        if (locationArgs.get("targets") == null) {
+            throw new IllegalArgumentException("target must be specified in single-machine spec");
+        }
+        
+        // TODO do we need to pass location flags etc into the children to ensure they are inherited?
+        List<Location> targets = Lists.newArrayList();
+        Object targetSpecs = locationArgs.remove("targets");
+        try {
+            if (targetSpecs instanceof String) {
+                for (String targetSpec : JavaStringEscapes.unwrapJsonishListIfPossible((String)targetSpecs)) {
+                    targets.add(managementContext.getLocationRegistry().resolve(targetSpec));
+                }
+            } else if (targetSpecs instanceof Iterable) {
+                for (Object targetSpec: (Iterable<?>)targetSpecs) {
+                    if (targetSpec instanceof String) {
+                        targets.add(managementContext.getLocationRegistry().resolve((String)targetSpec));
+                    } else {
+                        Set<?> keys = ((Map<?,?>)targetSpec).keySet();
+                        if (keys.size()!=1) 
+                            throw new IllegalArgumentException("targets supplied to MultiLocation must be a list of single-entry maps (got map of size "+keys.size()+": "+targetSpec+")");
+                        Object key = keys.iterator().next();
+                        Object flagsS = ((Map<?,?>)targetSpec).get(key);
+                        targets.add(managementContext.getLocationRegistry().resolve((String)key, (Map<?,?>)flagsS));
+                    }
+                }
+            } else throw new IllegalArgumentException("targets must be supplied to MultiLocation, either as string spec or list of single-entry maps each being a location spec");
+            
+            MultiLocation result = managementContext.getLocationManager().createLocation(LocationSpec.create(MultiLocation.class)
+                    .configure(flags)
+                    .configure("subLocations", targets)
+                    .configure(LocationConfigUtils.finalAndOriginalSpecs(spec, locationFlags, globalProperties, namedLocation)));
+
+            // TODO Important workaround for BasicLocationRegistry.resolveForPeeking.
+            // That creates a location (from the resolver) and immediately unmanages it.
+            // The unmanage *must* remove all the targets created here; otherwise we have a leak.
+            // Adding the targets as children achieves this.
+            for (Location target : targets) {
+                target.setParent(result);
+            }
+            return result;
+
+        } catch (Exception e) {
+            // Must clean up after ourselves: don't leak sub-locations on error
+            if (LOG.isDebugEnabled()) LOG.debug("Problem resolving MultiLocation; cleaning up any sub-locations and rethrowing: "+e);
+            for (Location target : targets) {
+                Locations.unmanage(target);
+            }
+            throw Exceptions.propagate(e);
+        }
+    }
+
+    @Override
+    public String getPrefix() {
+        return MULTI;
+    }
+
+    @Override
+    public boolean accepts(String spec, LocationRegistry registry) {
+        return BasicLocationRegistry.isResolverPrefixForSpec(this, spec, true);
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/NamedLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/NamedLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/core/NamedLocationResolver.java
new file mode 100644
index 0000000..08976de
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/NamedLocationResolver.java
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.util.Map;
+import java.util.NoSuchElementException;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationDefinition;
+import org.apache.brooklyn.api.location.LocationRegistry;
+import org.apache.brooklyn.api.location.LocationResolver;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.text.Strings;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Allows you to say, in your brooklyn.properties:
+ * 
+ * brooklyn.location.named.foo=localhost
+ * brooklyn.location.named.foo.user=bob
+ * brooklyn.location.named.foo.privateKeyFile=~/.ssh/custom-key-for-bob
+ * brooklyn.location.named.foo.privateKeyPassphrase=WithAPassphrase
+ * <p>
+ * or
+ * <p>
+ * brooklyn.location.named.bob-aws-east=jclouds:aws-ec2:us-east-1
+ * brooklyn.location.named.bob-aws-east.identity=BobId
+ * brooklyn.location.named.bob-aws-east.credential=BobCred
+ * <p>
+ * then you can simply refer to:   foo   or   named:foo   (or bob-aws-east or named:bob-aws-east)   in any location spec
+ */
+public class NamedLocationResolver implements LocationResolver {
+
+    public static final Logger log = LoggerFactory.getLogger(NamedLocationResolver.class);
+
+    public static final String NAMED = "named";
+    
+    @SuppressWarnings("unused")
+    private ManagementContext managementContext;
+
+    @Override
+    public void init(ManagementContext managementContext) {
+        this.managementContext = checkNotNull(managementContext, "managementContext");
+    }
+    
+    @Override
+    @SuppressWarnings({ "rawtypes" })
+    public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
+        String name = spec;
+        ConfigBag lfBag = ConfigBag.newInstance(locationFlags).putIfAbsent(LocationInternal.ORIGINAL_SPEC, name);
+        name = Strings.removeFromStart(spec, getPrefix()+":");
+        if (name.toLowerCase().startsWith(NAMED+":")) {
+            // since 0.7.0
+            log.warn("Deprecated use of 'named:' prefix with wrong case ("+spec+"); support may be removed in future versions");
+            name = spec.substring( (NAMED+":").length() );
+        }
+        
+        LocationDefinition ld = registry.getDefinedLocationByName(name);
+        if (ld==null) throw new NoSuchElementException("No named location defined matching '"+name+"'");
+        return ((BasicLocationRegistry)registry).resolveLocationDefinition(ld, lfBag.getAllConfig(), name);
+    }
+
+    @Override
+    public String getPrefix() {
+        return NAMED;
+    }
+    
+    /** accepts anything starting  named:xxx  or  xxx where xxx is a defined location name */
+    @Override
+    public boolean accepts(String spec, LocationRegistry registry) {
+        if (BasicLocationRegistry.isResolverPrefixForSpec(this, spec, false)) return true;
+        if (registry.getDefinedLocationByName(spec)!=null) return true;
+        return false;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/PortRanges.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/PortRanges.java b/core/src/main/java/org/apache/brooklyn/location/core/PortRanges.java
new file mode 100644
index 0000000..72346f1
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/PortRanges.java
@@ -0,0 +1,257 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.brooklyn.api.location.PortRange;
+import org.apache.brooklyn.util.core.flags.TypeCoercions;
+
+import com.google.common.base.Function;
+import com.google.common.base.Objects;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+
+public class PortRanges {
+
+    public static final int MAX_PORT = 65535;
+    public static final PortRange ANY_HIGH_PORT = new LinearPortRange(1024, MAX_PORT);
+    
+    public static class SinglePort implements PortRange, Serializable {
+        private static final long serialVersionUID = 7446781416534230401L;
+        
+        final int port;
+        private SinglePort(int port) { this.port = port; }
+        
+        @Override
+        public Iterator<Integer> iterator() {
+            return Collections.singletonList(port).iterator();
+        }
+        @Override
+        public boolean isEmpty() {
+            return false;
+        }
+        @Override
+        public boolean asBoolean() {
+            return true;
+        }
+        @Override
+        public String toString() {
+            return //getClass().getName()+"["+
+                    ""+port; //+"]";
+        }
+        public int hashCode() {
+            return Objects.hashCode(port);
+        }
+        @Override
+        public boolean equals(Object obj) {
+            return (obj instanceof SinglePort) && port == ((SinglePort)obj).port;
+        }
+    }
+
+    public static class LinearPortRange implements PortRange, Serializable {
+        private static final long serialVersionUID = -9165280509363743508L;
+        
+        final int start, end, delta;
+        private LinearPortRange(int start, int end, int delta) {
+            this.start = start;
+            this.end = end;
+            this.delta = delta;
+            checkArgument(start > 0 && start <= MAX_PORT, "start port %s out of range", start);
+            checkArgument(end > 0 && end <= MAX_PORT, "end port %s out of range", end);
+            checkArgument(delta > 0 ? start <= end : start >= end, "start and end out of order: %s to %s, delta %s", start, end, delta);
+            checkArgument(delta != 0, "delta must be non-zero");
+        }
+        public LinearPortRange(int start, int end) {
+            this(start, end, (start<=end?1:-1));
+        }
+        
+        @Override
+        public Iterator<Integer> iterator() {
+            return new Iterator<Integer>() {
+                int next = start;
+                boolean hasNext = true;
+                
+                @Override
+                public boolean hasNext() {
+                    return hasNext;
+                }
+
+                @Override
+                public Integer next() {
+                    if (!hasNext)
+                        throw new NoSuchElementException("Exhausted available ports");
+                    int result = next;
+                    next += delta;
+                    if ((delta>0 && next>end) || (delta<0 && next<end)) hasNext = false;
+                    return result;
+                }
+                
+                @Override
+                public void remove() {
+                    throw new UnsupportedOperationException();
+                }
+            };
+        }
+        
+        @Override
+        public boolean isEmpty() {
+            return false;
+        }
+        @Override
+        public boolean asBoolean() {
+            return true;
+        }
+        @Override
+        public String toString() {
+            return //getClass().getName()+"["+
+                    start+"-"+end; //+"]";
+        }
+        @Override
+        public int hashCode() {
+            return Objects.hashCode(start, end, delta);
+        }
+        @Override
+        public boolean equals(Object obj) {
+            if (!(obj instanceof LinearPortRange)) return false;
+            LinearPortRange o = (LinearPortRange) obj;
+            return start == o.start && end == o.end && delta == o.delta;
+        }
+    }
+    
+    public static class AggregatePortRange implements PortRange, Serializable {
+        private static final long serialVersionUID = 7332682500816739660L;
+        
+        final List<PortRange> ranges;
+        private AggregatePortRange(List<PortRange> ranges) {
+            this.ranges = ImmutableList.copyOf(ranges);
+        }
+        @Override
+        public Iterator<Integer> iterator() {
+            return Iterables.concat(ranges).iterator();
+        }
+        @Override
+        public boolean isEmpty() {
+            for (PortRange r: ranges)
+                if (!r.isEmpty()) return false;
+            return true;
+        }
+        @Override
+        public boolean asBoolean() {
+            return !isEmpty();
+        }
+        @Override
+        public String toString() {
+            String s = "";
+            for (PortRange r: ranges) {
+                if (s.length()>0) s+=",";
+                s += r;
+            }
+            return //getClass().getName()+"["+
+                s; //+"]";
+        }
+        public int hashCode() {
+            return Objects.hashCode(ranges);
+        }
+        @Override
+        public boolean equals(Object obj) {
+            return (obj instanceof AggregatePortRange) && ranges.equals(((AggregatePortRange)obj).ranges);
+        }
+    }
+
+    public static PortRange fromInteger(int x) {
+        return new SinglePort(x);
+    }
+    
+    public static PortRange fromCollection(Collection<?> c) {
+        List<PortRange> l = new ArrayList<PortRange>();
+        for (Object o: c) {
+            if (o instanceof Integer) l.add(fromInteger((Integer)o));
+            else if (o instanceof String) l.add(fromString((String)o));
+            else if (o instanceof Collection) l.add(fromCollection((Collection<?>)o));
+            else l.add(TypeCoercions.coerce(o, PortRange.class));
+        }
+        return new AggregatePortRange(l);
+    }
+
+    /** parses a string representation of ports, as "80,8080,8000,8080-8099" */
+    public static PortRange fromString(String s) {
+        List<PortRange> l = new ArrayList<PortRange>();
+        for (String si: s.split(",")) {
+            si = si.trim();
+            int start, end;
+            if (si.endsWith("+")) {
+                String si2 = si.substring(0, si.length()-1).trim();
+                start = Integer.parseInt(si2);
+                end = MAX_PORT;
+            } else if (si.indexOf('-')>0) {
+                int v = si.indexOf('-');
+                start = Integer.parseInt(si.substring(0, v).trim());
+                end = Integer.parseInt(si.substring(v+1).trim());
+            } else if (si.length()==0) {
+                //nothing, ie empty range, just continue
+                continue;
+            } else {
+                //should be number on its own
+                l.add(new SinglePort(Integer.parseInt(si)));
+                continue;
+            }
+            l.add(new LinearPortRange(start, end));
+        }
+        if (l.size() == 1) {
+            return l.get(0);
+        } else {
+            return new AggregatePortRange(l);
+        }
+    }
+
+    private static AtomicBoolean initialized = new AtomicBoolean(false); 
+    /** performs the language extensions required for this project */
+    @SuppressWarnings("rawtypes")
+    public static void init() {
+        if (initialized.get()) return;
+        synchronized (initialized) {
+            if (initialized.get()) return;
+            TypeCoercions.registerAdapter(Integer.class, PortRange.class, new Function<Integer,PortRange>() {
+                public PortRange apply(Integer x) { return fromInteger(x); }
+            });
+            TypeCoercions.registerAdapter(String.class, PortRange.class, new Function<String,PortRange>() {
+                public PortRange apply(String x) { return fromString(x); }
+            });
+            TypeCoercions.registerAdapter(Collection.class, PortRange.class, new Function<Collection,PortRange>() {
+                public PortRange apply(Collection x) { return fromCollection(x); }
+            });
+            initialized.set(true);
+        }
+    }
+    
+    static {
+        init();
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/RegistryLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/RegistryLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/core/RegistryLocationResolver.java
new file mode 100644
index 0000000..9ac62d7
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/RegistryLocationResolver.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationRegistry;
+import org.apache.brooklyn.api.location.LocationResolver;
+
+/**
+ * Extension to LocationResolver which can take a registry.
+ * 
+ * @deprecated since 0.6; the LocationResolver always takes the LocationRegistry now
+ */
+@Deprecated
+public interface RegistryLocationResolver extends LocationResolver {
+
+    @Override
+    @SuppressWarnings("rawtypes")
+    Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry);
+
+    @Override
+    boolean accepts(String spec, LocationRegistry registry);
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/SupportsPortForwarding.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/SupportsPortForwarding.java b/core/src/main/java/org/apache/brooklyn/location/core/SupportsPortForwarding.java
new file mode 100644
index 0000000..d0af5a4
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/SupportsPortForwarding.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import org.apache.brooklyn.util.net.Cidr;
+
+import com.google.common.net.HostAndPort;
+
+public interface SupportsPortForwarding {
+
+    /** returns an endpoint suitable for contacting the indicated private port on this object,
+     * from the given Cidr, creating it if necessary and possible; 
+     * may return null if forwarding not available 
+     */
+    public HostAndPort getSocketEndpointFor(Cidr accessor, int privatePort);
+    
+    /** marker on a location to indicate that port forwarding should be done automatically
+     * for attempts to access from Brooklyn
+     */
+    public interface RequiresPortForwarding extends SupportsPortForwarding {
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/internal/LocationDynamicType.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/internal/LocationDynamicType.java b/core/src/main/java/org/apache/brooklyn/location/core/internal/LocationDynamicType.java
new file mode 100644
index 0000000..83316ec
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/internal/LocationDynamicType.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core.internal;
+
+import org.apache.brooklyn.core.objs.BrooklynDynamicType;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationType;
+
+public class LocationDynamicType extends BrooklynDynamicType<Location, AbstractLocation> {
+
+    public LocationDynamicType(AbstractLocation location) {
+        super(location);
+    }
+    
+    public LocationType getSnapshot() {
+        return (LocationType) super.getSnapshot();
+    }
+
+    @Override
+    protected LocationTypeSnapshot newSnapshot() {
+        return new LocationTypeSnapshot(name, value(configKeys));
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/internal/LocationInternal.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/internal/LocationInternal.java b/core/src/main/java/org/apache/brooklyn/location/core/internal/LocationInternal.java
new file mode 100644
index 0000000..9ec449b
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/internal/LocationInternal.java
@@ -0,0 +1,93 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core.internal;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.rebind.RebindSupport;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.LocationMemento;
+import org.apache.brooklyn.config.ConfigInheritance;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.objs.BrooklynObjectInternal;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+
+import com.google.common.annotations.Beta;
+
+/**
+ * Information about locations private to Brooklyn.
+ */
+public interface LocationInternal extends BrooklynObjectInternal, Location {
+
+    @Beta
+    public static final ConfigKey<String> ORIGINAL_SPEC = ConfigKeys.newStringConfigKey("spec.original", "The original spec used to instantiate a location");
+    @Beta
+    public static final ConfigKey<String> FINAL_SPEC = ConfigKeys.newStringConfigKey("spec.final", "The actual spec (in a chain) which instantiates a location");
+    @Beta
+    public static final ConfigKey<String> NAMED_SPEC_NAME = ConfigKeys.newStringConfigKey("spec.named.name", "The name on the (first) named spec in a chain");
+    
+    /**
+     * Registers the given extension for the given type. If an extension already existed for
+     * this type, then this will override it.
+     * 
+     * @throws NullPointerException if extensionType or extension are null
+     * @throws IllegalArgumentException if extension does not implement extensionType
+     */
+    <T> void addExtension(Class<T> extensionType, T extension);
+
+    /**
+     * Get a record of the metadata of this location.
+     * <p/>
+     * <p>Metadata records are used to record an audit trail of events relating to location usage
+     * (for billing purposes, for example). Implementations (and subclasses) should override this
+     * method to return information useful for this purpose.</p>
+     *
+     * @return
+     */
+    public Map<String, String> toMetadataRecord();
+
+    /**
+     * @deprecated since 0.7.0; use {@link #config()}, such as {@code ((LocationInternal)location).config().getLocalBag()}
+     */
+    @Deprecated
+    ConfigBag getLocalConfigBag();
+
+    /**
+     * Returns all config, including that inherited from parents.
+     * 
+     * This method does not respect {@link ConfigInheritance} and so usage is discouraged.
+     * 
+     * @deprecated since 0.7.0; use {@link #config()}, such as {@code ((LocationInternal)location).config().getBag()}
+     */
+    @Deprecated
+    ConfigBag getAllConfigBag();
+
+    /**
+     * Users are strongly discouraged from calling or overriding this method.
+     * It is for internal calls only, relating to persisting/rebinding entities.
+     * This method may change (or be removed) in a future release without notice.
+     */
+    @Override
+    @Beta
+    RebindSupport<LocationMemento> getRebindSupport();
+    
+    ManagementContext getManagementContext();
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/internal/LocationTypeSnapshot.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/internal/LocationTypeSnapshot.java b/core/src/main/java/org/apache/brooklyn/location/core/internal/LocationTypeSnapshot.java
new file mode 100644
index 0000000..b272b72
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/internal/LocationTypeSnapshot.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core.internal;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.sensor.EnricherType;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.objs.BrooklynTypeSnapshot;
+
+public class LocationTypeSnapshot extends BrooklynTypeSnapshot implements EnricherType {
+    
+    private static final long serialVersionUID = 9150132836104748237L;
+
+    LocationTypeSnapshot(String name, Map<String, ConfigKey<?>> configKeys) {
+        super(name, configKeys);
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) return true;
+        return (obj instanceof LocationTypeSnapshot) && super.equals(obj);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/geo/HostGeoInfo.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/geo/HostGeoInfo.java b/core/src/main/java/org/apache/brooklyn/location/geo/HostGeoInfo.java
index dde47a6..fc88cd2 100644
--- a/core/src/main/java/org/apache/brooklyn/location/geo/HostGeoInfo.java
+++ b/core/src/main/java/org/apache/brooklyn/location/geo/HostGeoInfo.java
@@ -26,8 +26,8 @@ import javax.annotation.Nullable;
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.location.AddressableLocation;
 import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.location.basic.AbstractLocation;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
 import org.apache.brooklyn.util.core.flags.TypeCoercions;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.apache.brooklyn.util.guava.Maybe;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/localhost/LocalhostLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/localhost/LocalhostLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/localhost/LocalhostLocationResolver.java
new file mode 100644
index 0000000..37d885d
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/localhost/LocalhostLocationResolver.java
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.localhost;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationRegistry;
+import org.apache.brooklyn.api.location.LocationResolver;
+import org.apache.brooklyn.location.core.AbstractLocationResolver;
+import org.apache.brooklyn.location.core.LocationConfigUtils;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+
+/**
+ * Examples of valid specs:
+ *   <ul>
+ *     <li>localhost
+ *     <li>localhost()
+ *     <li>localhost(name=abc)
+ *     <li>localhost(name="abc")
+ *   </ul>
+ * 
+ * @author alex, aled
+ */
+public class LocalhostLocationResolver extends AbstractLocationResolver implements LocationResolver.EnableableLocationResolver {
+
+    public static final String LOCALHOST = "localhost";
+
+    @Override
+    public String getPrefix() {
+        return LOCALHOST;
+    }
+
+    @Override
+    public boolean isEnabled() {
+        return LocationConfigUtils.isEnabled(managementContext, "brooklyn.location.localhost");
+    }
+
+    @Override
+    protected Class<? extends Location> getLocationType() {
+        return LocalhostMachineProvisioningLocation.class;
+    }
+
+    @Override
+    protected SpecParser getSpecParser() {
+        return new AbstractLocationResolver.SpecParser(getPrefix()).setExampleUsage("\"localhost\" or \"localhost(displayName=abc)\"");
+    }
+
+    @Override
+    protected Map<String, Object> getFilteredLocationProperties(String provider, String namedLocation, Map<String, ?> globalProperties) {
+        return new LocalhostPropertiesFromBrooklynProperties().getLocationProperties("localhost", namedLocation, globalProperties);
+    }
+
+    @Override
+    protected ConfigBag extractConfig(Map<?,?> locationFlags, String spec, LocationRegistry registry) {
+        ConfigBag config = super.extractConfig(locationFlags, spec, registry);
+        config.putAsStringKeyIfAbsent("name", "localhost");
+        return config;
+    }
+}


[30/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/pool/ServerPoolImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/pool/ServerPoolImpl.java b/software/base/src/main/java/brooklyn/entity/pool/ServerPoolImpl.java
deleted file mode 100644
index 0076f9e..0000000
--- a/software/base/src/main/java/brooklyn/entity/pool/ServerPoolImpl.java
+++ /dev/null
@@ -1,432 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.pool;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationDefinition;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.api.mgmt.LocationManager;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.api.policy.PolicySpec;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.apache.brooklyn.entity.group.AbstractMembershipTrackingPolicy;
-import org.apache.brooklyn.entity.group.DynamicClusterImpl;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.entity.trait.Startable;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.BasicLocationDefinition;
-import org.apache.brooklyn.location.basic.Machines;
-import org.apache.brooklyn.location.dynamic.DynamicLocation;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.guava.Maybe;
-
-import com.google.common.base.Function;
-import com.google.common.base.Joiner;
-import com.google.common.base.Optional;
-import com.google.common.base.Predicate;
-import com.google.common.collect.FluentIterable;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.reflect.TypeToken;
-
-public class ServerPoolImpl extends DynamicClusterImpl implements ServerPool {
-
-    private static final Logger LOG = LoggerFactory.getLogger(ServerPoolImpl.class);
-
-    private static enum MachinePoolMemberStatus {
-        /** The server is available for use */
-        AVAILABLE,
-        /** The server has been leased to another application */
-        CLAIMED,
-        /**
-         * The server will not be leased to other applications. It will be the first
-         * candidate to release when the pool is shrunk.
-         */
-        UNUSABLE
-    }
-
-    private static final AttributeSensor<MachinePoolMemberStatus> SERVER_STATUS = Sensors.newSensor(MachinePoolMemberStatus.class,
-            "pool.serverStatus", "The status of an entity in the pool");
-
-    // The sensors here would be better as private fields but there's not really a
-    // good way to manage their state when rebinding.
-
-    /** Accesses must be synchronised by mutex */
-    // Would use BiMap but persisting them tends to throw ConcurrentModificationExceptions.
-    @SuppressWarnings("serial")
-    public static final AttributeSensor<Map<Entity, MachineLocation>> ENTITY_MACHINE = Sensors.newSensor(new TypeToken<Map<Entity, MachineLocation>>() {},
-            "pool.entityMachineMap", "A mapping of entities and their machine locations");
-
-    @SuppressWarnings("serial")
-    public static final AttributeSensor<Map<MachineLocation, Entity>> MACHINE_ENTITY = Sensors.newSensor(new TypeToken<Map<MachineLocation, Entity>>() {},
-            "pool.machineEntityMap", "A mapping of machine locations and their entities");
-
-    public static final AttributeSensor<LocationDefinition> DYNAMIC_LOCATION_DEFINITION = Sensors.newSensor(LocationDefinition.class,
-            "pool.locationDefinition", "The location definition used to create the pool's dynamic location");
-
-    public static final ConfigKey<Boolean> REMOVABLE = ConfigKeys.newBooleanConfigKey(
-            "pool.member.removable", "Whether a pool member is removable from the cluster. Used to denote additional " +
-                    "existing machines that were manually added to the pool", true);
-
-    @SuppressWarnings("unused")
-    private MemberTrackingPolicy membershipTracker;
-
-    @Override
-    public void init() {
-        super.init();
-        setAttribute(AVAILABLE_COUNT, 0);
-        setAttribute(CLAIMED_COUNT, 0);
-        setAttribute(ENTITY_MACHINE, Maps.<Entity, MachineLocation>newHashMap());
-        setAttribute(MACHINE_ENTITY, Maps.<MachineLocation, Entity>newHashMap());
-    }
-
-    @Override
-    public void start(Collection<? extends Location> locations) {
-        // super.start must happen before the policy is added else the initial
-        // members wont be up (and thus have a MachineLocation) when onEntityAdded
-        // is called.
-        super.start(locations);
-        createLocation();
-        addMembershipTrackerPolicy();
-    }
-
-    @Override
-    public void rebind() {
-        super.rebind();
-        addMembershipTrackerPolicy();
-        createLocation();
-    }
-
-    @Override
-    public void stop() {
-        super.stop();
-        deleteLocation();
-        synchronized (mutex) {
-            setAttribute(AVAILABLE_COUNT, 0);
-            setAttribute(CLAIMED_COUNT, 0);
-            getAttribute(ENTITY_MACHINE).clear();
-            getAttribute(MACHINE_ENTITY).clear();
-        }
-    }
-
-    private void addMembershipTrackerPolicy() {
-        membershipTracker = addPolicy(PolicySpec.create(MemberTrackingPolicy.class)
-                .displayName(getDisplayName() + " membership tracker")
-                .configure("group", this));
-    }
-
-    @Override
-    public ServerPoolLocation getDynamicLocation() {
-        return (ServerPoolLocation) getAttribute(DYNAMIC_LOCATION);
-    }
-
-    protected ServerPoolLocation createLocation() {
-        return createLocation(MutableMap.<String, Object>builder()
-                .putAll(getConfig(LOCATION_FLAGS))
-                .put(DynamicLocation.OWNER.getName(), this)
-                .build());
-    }
-
-    @Override
-    public ServerPoolLocation createLocation(Map<String, ?> flags) {
-        String locationName = getConfig(LOCATION_NAME);
-        if (locationName == null) {
-            String prefix = getConfig(LOCATION_NAME_PREFIX);
-            String suffix = getConfig(LOCATION_NAME_SUFFIX);
-            locationName = Joiner.on("-").skipNulls().join(prefix, getId(), suffix);
-        }
-
-        String locationSpec = String.format(ServerPoolLocationResolver.POOL_SPEC, getId()) + String.format(":(name=\"%s\")", locationName);
-        LocationDefinition definition = new BasicLocationDefinition(locationName, locationSpec, flags);
-        getManagementContext().getLocationRegistry().updateDefinedLocation(definition);
-        Location location = getManagementContext().getLocationRegistry().resolve(definition);
-        LOG.info("Resolved and registered dynamic location {}: {}", locationName, location);
-
-        setAttribute(LOCATION_SPEC, locationSpec);
-        setAttribute(DYNAMIC_LOCATION, location);
-        setAttribute(LOCATION_NAME, location.getId());
-        setAttribute(DYNAMIC_LOCATION_DEFINITION, definition);
-
-        return (ServerPoolLocation) location;
-    }
-
-    @Override
-    public void deleteLocation() {
-        LocationManager mgr = getManagementContext().getLocationManager();
-        ServerPoolLocation location = getDynamicLocation();
-        if (mgr.isManaged(location)) {
-            LOG.debug("{} deleting and unmanaging location {}", this, location);
-            mgr.unmanage(location);
-        }
-        // definition will only be null if deleteLocation has already been called, e.g. by two calls to stop().
-        LocationDefinition definition = getAttribute(DYNAMIC_LOCATION_DEFINITION);
-        if (definition != null) {
-            LOG.debug("{} unregistering dynamic location {}", this, definition);
-            getManagementContext().getLocationRegistry().removeDefinedLocation(definition.getId());
-        }
-        setAttribute(LOCATION_SPEC, null);
-        setAttribute(DYNAMIC_LOCATION, null);
-        setAttribute(LOCATION_NAME, null);
-        setAttribute(DYNAMIC_LOCATION_DEFINITION, null);
-    }
-
-    @Override
-    public boolean isLocationAvailable() {
-        // FIXME: What do true/false mean to callers?
-        // Is it valid to return false if availableMachines is empty?
-        return getDynamicLocation() != null;
-    }
-
-    @Override
-    public MachineLocation claimMachine(Map<?, ?> flags) throws NoMachinesAvailableException {
-        LOG.info("Obtaining machine with flags: {}", Joiner.on(", ").withKeyValueSeparator("=").join(flags));
-        synchronized (mutex) {
-            Optional<Entity> claimed = getMemberWithStatus(MachinePoolMemberStatus.AVAILABLE);
-            if (claimed.isPresent()) {
-                setEntityStatus(claimed.get(), MachinePoolMemberStatus.CLAIMED);
-                updateCountSensors();
-                LOG.debug("{} has been claimed in {}", claimed, this);
-                return getEntityMachineMap().get(claimed.get());
-            } else {
-                throw new NoMachinesAvailableException("No machines available in " + this);
-            }
-        }
-    }
-
-    @Override
-    public void releaseMachine(MachineLocation machine) {
-        synchronized (mutex) {
-            Entity entity = getMachineEntityMap().get(machine);
-            if (entity == null) {
-                LOG.warn("{} releasing machine {} but its owning entity is not known!", this, machine);
-            } else {
-                setEntityStatus(entity, MachinePoolMemberStatus.AVAILABLE);
-                updateCountSensors();
-                LOG.debug("{} has been released in {}", machine, this);
-            }
-        }
-    }
-
-    @Override
-    public Entity addExistingMachine(MachineLocation machine) {
-        LOG.info("Adding additional machine to {}: {}", this, machine);
-        Entity added = addNode(machine, MutableMap.of(REMOVABLE, false));
-        Map<String, ?> args = ImmutableMap.of("locations", ImmutableList.of(machine));
-        Task<Void> task = Effectors.invocation(added, Startable.START, args).asTask();
-        DynamicTasks.queueIfPossible(task).orSubmitAsync(this);
-        return added;
-    }
-
-    @Override
-    public Collection<Entity> addExistingMachinesFromSpec(String spec) {
-        Location location = getManagementContext().getLocationRegistry().resolve(spec, true, null).orNull();
-        List<Entity> additions = Lists.newLinkedList();
-        if (location == null) {
-            LOG.warn("Spec was unresolvable: {}", spec);
-        } else {
-            Iterable<MachineLocation> machines = FluentIterable.from(location.getChildren())
-                    .filter(MachineLocation.class);
-            LOG.info("{} adding additional machines: {}", this, machines);
-            // Doesn't need to be synchronised on mutex: it will be claimed per-machine
-            // as the new members are handled by the membership tracking policy.
-            for (MachineLocation machine : machines) {
-                additions.add(addExistingMachine(machine));
-            }
-            LOG.debug("{} added additional machines", this);
-        }
-        return additions;
-    }
-
-    /**
-     * Overrides to restrict delta to the number of machines that can be <em>safely</em>
-     * removed (i.e. those that are {@link MachinePoolMemberStatus#UNUSABLE unusable} or
-     * {@link MachinePoolMemberStatus#AVAILABLE available}).
-     * <p/>
-     * Does not modify delta if the pool is stopping.
-     * @param delta Requested number of members to remove
-     * @return The entities that were removed
-     */
-    @Override
-    protected Collection<Entity> shrink(int delta) {
-        if (Lifecycle.STOPPING.equals(getAttribute(Attributes.SERVICE_STATE_ACTUAL))) {
-            return super.shrink(delta);
-        }
-
-        synchronized (mutex) {
-            int removable = 0;
-            for (Entity entity : getMembers()) {
-                // Skip machine marked not for removal and machines that are claimed
-                if (!Boolean.FALSE.equals(entity.getConfig(REMOVABLE)) &&
-                        !MachinePoolMemberStatus.CLAIMED.equals(entity.getAttribute(SERVER_STATUS))) {
-                    removable -= 1;
-                }
-            }
-
-            if (delta < removable) {
-                LOG.warn("Too few removable machines in {} to shrink by delta {}. Altered delta to {}",
-                        new Object[]{this, delta, removable});
-                delta = removable;
-            }
-
-            Collection<Entity> removed = super.shrink(delta);
-            updateCountSensors();
-            return removed;
-        }
-    }
-    
-    private Map<Entity, MachineLocation> getEntityMachineMap() {
-        return getAttribute(ENTITY_MACHINE);
-    }
-
-    private Map<MachineLocation, Entity> getMachineEntityMap() {
-        return getAttribute(MACHINE_ENTITY);
-    }
-
-    @Override
-    public Function<Collection<Entity>, Entity> getRemovalStrategy() {
-        return UNCLAIMED_REMOVAL_STRATEGY;
-    }
-
-    private final Function<Collection<Entity>, Entity> UNCLAIMED_REMOVAL_STRATEGY = new Function<Collection<Entity>, Entity>() {
-        // Semantics of superclass mean that mutex should already be held when apply is called
-        @Override
-        public Entity apply(Collection<Entity> members) {
-            synchronized (mutex) {
-                Optional<Entity> choice;
-                if (Lifecycle.STOPPING.equals(getAttribute(Attributes.SERVICE_STATE_ACTUAL))) {
-                    choice = Optional.of(members.iterator().next());
-                } else {
-                    // Otherwise should only choose between removable + unusable or available
-                    choice = getMemberWithStatusExcludingUnremovable(members, MachinePoolMemberStatus.UNUSABLE)
-                            .or(getMemberWithStatusExcludingUnremovable(members, MachinePoolMemberStatus.AVAILABLE));
-                }
-                if (!choice.isPresent()) {
-                    LOG.warn("{} has no machines available to remove!", this);
-                    return null;
-                } else {
-                    LOG.info("{} selected entity to remove from pool: {}", this, choice.get());
-                    choice.get().getAttribute(SERVER_STATUS);
-                    setEntityStatus(choice.get(), null);
-                }
-                MachineLocation entityLocation = getEntityMachineMap().remove(choice.get());
-                if (entityLocation != null) {
-                    getMachineEntityMap().remove(entityLocation);
-                }
-                return choice.get();
-            }
-        }
-    };
-
-    private void serverAdded(Entity member) {
-        Maybe<MachineLocation> machine = Machines.findUniqueMachineLocation(member.getLocations());
-        if (member.getAttribute(SERVER_STATUS) != null) {
-            LOG.debug("Skipped addition of machine already in the pool: {}", member);
-        } else if (machine.isPresentAndNonNull()) {
-            MachineLocation m = machine.get();
-            LOG.info("New machine in {}: {}", this, m);
-            setEntityStatus(member, MachinePoolMemberStatus.AVAILABLE);
-            synchronized (mutex) {
-                getEntityMachineMap().put(member, m);
-                getMachineEntityMap().put(m, member);
-                updateCountSensors();
-            }
-        } else {
-            LOG.warn("Member added to {} that does not have a machine location; it will not be used by the pool: {}",
-                    ServerPoolImpl.this, member);
-            setEntityStatus(member, MachinePoolMemberStatus.UNUSABLE);
-        }
-    }
-
-    private void setEntityStatus(Entity entity, MachinePoolMemberStatus status) {
-        ((EntityInternal) entity).setAttribute(SERVER_STATUS, status);
-    }
-
-    private Optional<Entity> getMemberWithStatus(MachinePoolMemberStatus status) {
-        return getMemberWithStatus0(getMembers(), status, true);
-    }
-
-    private Optional<Entity> getMemberWithStatusExcludingUnremovable(Collection<Entity> entities, MachinePoolMemberStatus status) {
-        return getMemberWithStatus0(entities, status, false);
-    }
-
-    private Optional<Entity> getMemberWithStatus0(Collection<Entity> entities, final MachinePoolMemberStatus status, final boolean includeUnremovableMachines) {
-        return Iterables.tryFind(entities,
-                new Predicate<Entity>() {
-                    @Override
-                    public boolean apply(Entity input) {
-                        return (includeUnremovableMachines || isRemovable(input)) &&
-                                status.equals(input.getAttribute(SERVER_STATUS));
-                    }
-                });
-    }
-
-    /** @return true if the entity has {@link #REMOVABLE} set to null or true. */
-    private boolean isRemovable(Entity entity) {
-        return !Boolean.FALSE.equals(entity.getConfig(REMOVABLE));
-    }
-
-    private void updateCountSensors() {
-        synchronized (mutex) {
-            int available = 0, claimed = 0;
-            for (Entity member : getMembers()) {
-                MachinePoolMemberStatus status = member.getAttribute(SERVER_STATUS);
-                if (MachinePoolMemberStatus.AVAILABLE.equals(status)) {
-                    available++;
-                } else if (MachinePoolMemberStatus.CLAIMED.equals(status)) {
-                    claimed++;
-                }
-            }
-            setAttribute(AVAILABLE_COUNT, available);
-            setAttribute(CLAIMED_COUNT, claimed);
-        }
-    }
-
-    public static class MemberTrackingPolicy extends AbstractMembershipTrackingPolicy {
-        @Override
-        protected void onEntityEvent(EventType type, Entity member) {
-            Boolean isUp = member.getAttribute(Attributes.SERVICE_UP);
-            LOG.info("{} in {}: {} service up is {}", new Object[]{type.name(), entity, member, isUp});
-            if (type.equals(EventType.ENTITY_ADDED) || type.equals(EventType.ENTITY_CHANGE)) {
-                if (Boolean.TRUE.equals(isUp)) {
-                    ((ServerPoolImpl) entity).serverAdded(member);
-                } else if (LOG.isDebugEnabled()) {
-                    LOG.debug("{} observed event {} but {} is not up (yet) and will not be used by the pool",
-                            new Object[]{entity, type.name(), member});
-                }
-            }
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/pool/ServerPoolLocation.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/pool/ServerPoolLocation.java b/software/base/src/main/java/brooklyn/entity/pool/ServerPoolLocation.java
deleted file mode 100644
index b748a24..0000000
--- a/software/base/src/main/java/brooklyn/entity/pool/ServerPoolLocation.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.pool;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.Collection;
-import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Maps;
-
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.location.basic.AbstractLocation;
-import org.apache.brooklyn.location.dynamic.DynamicLocation;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-
-public class ServerPoolLocation extends AbstractLocation implements MachineProvisioningLocation<MachineLocation>,
-        DynamicLocation<ServerPool, ServerPoolLocation> {
-
-    private static final long serialVersionUID = -6771844611899475409L;
-
-    private static final Logger LOG = LoggerFactory.getLogger(ServerPoolLocation.class);
-
-    @SetFromFlag("owner")
-    public static final ConfigKey<ServerPool> OWNER = ConfigKeys.newConfigKey(
-            ServerPool.class, "pool.location.owner");
-
-    @Override
-    public void init() {
-        LOG.debug("Initialising. Owner is: {}", checkNotNull(getConfig(OWNER), OWNER.getName()));
-        super.init();
-    }
-
-    @Override
-    public ServerPool getOwner() {
-        return getConfig(OWNER);
-    }
-
-    @Override
-    public MachineLocation obtain(Map<?, ?> flags) throws NoMachinesAvailableException {
-        // Call server pool and try to obtain one of its machines
-        return getOwner().claimMachine(flags);
-    }
-
-    @Override
-    public MachineProvisioningLocation<MachineLocation> newSubLocation(Map<?, ?> newFlags) {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
-    public void release(MachineLocation machine) {
-        getOwner().releaseMachine(machine);
-    }
-
-    @Override
-    public Map<String, Object> getProvisioningFlags(Collection<String> tags) {
-        return Maps.newLinkedHashMap();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/pool/ServerPoolLocationResolver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/pool/ServerPoolLocationResolver.java b/software/base/src/main/java/brooklyn/entity/pool/ServerPoolLocationResolver.java
deleted file mode 100644
index cd32156..0000000
--- a/software/base/src/main/java/brooklyn/entity/pool/ServerPoolLocationResolver.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.pool;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.Collections;
-import java.util.Map;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationRegistry;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.LocationResolver.EnableableLocationResolver;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Joiner;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Sets;
-
-import org.apache.brooklyn.location.basic.BasicLocationRegistry;
-import org.apache.brooklyn.location.basic.LocationInternal;
-import org.apache.brooklyn.location.basic.LocationPropertiesFromBrooklynProperties;
-import org.apache.brooklyn.location.dynamic.DynamicLocation;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.text.KeyValueParser;
-import org.apache.brooklyn.util.text.Strings;
-
-public class ServerPoolLocationResolver implements EnableableLocationResolver {
-
-    private static final Logger LOG = LoggerFactory.getLogger(ServerPoolLocationResolver.class);
-    private static final String PREFIX = "pool";
-    public static final String POOL_SPEC = PREFIX + ":%s";
-    private static final Pattern PATTERN = Pattern.compile("("+PREFIX+"|"+PREFIX.toUpperCase()+")" +
-            ":([a-zA-Z0-9]+)" + // pool Id
-            "(:\\((.*)\\))?$"); // arguments, e.g. displayName
-
-    private static final Set<String> ACCEPTABLE_ARGS = ImmutableSet.of("name", "displayName");
-
-    private ManagementContext managementContext;
-
-    @Override
-    public boolean isEnabled() {
-        return true;
-    }
-
-    @Override
-    public void init(ManagementContext managementContext) {
-        this.managementContext = checkNotNull(managementContext, "managementContext");
-    }
-
-    @Override
-    public String getPrefix() {
-        return PREFIX;
-    }
-
-    @Override
-    public boolean accepts(String spec, LocationRegistry registry) {
-        return BasicLocationRegistry.isResolverPrefixForSpec(this, spec, true);
-    }
-
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    @Override
-    public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
-        if (LOG.isDebugEnabled()) {
-            LOG.debug("Resolving location '" + spec + "' with flags " + Joiner.on(",").withKeyValueSeparator("=").join(locationFlags));
-        }
-        String namedLocation = (String) locationFlags.get(LocationInternal.NAMED_SPEC_NAME.getName());
-
-        Matcher matcher = PATTERN.matcher(spec);
-        if (!matcher.matches()) {
-            String m = String.format("Invalid location '%s'; must specify either %s:entityId or %s:entityId:(key=argument)",
-                    spec, PREFIX, PREFIX);
-            throw new IllegalArgumentException(m);
-        }
-
-        String argsPart = matcher.group(4);
-        Map<String, String> argsMap = (argsPart != null) ? KeyValueParser.parseMap(argsPart) : Collections.<String,String>emptyMap();
-        String displayNamePart = argsMap.get("displayName");
-        String namePart = argsMap.get("name");
-
-        if (!ACCEPTABLE_ARGS.containsAll(argsMap.keySet())) {
-            Set<String> illegalArgs = Sets.difference(argsMap.keySet(), ACCEPTABLE_ARGS);
-            throw new IllegalArgumentException("Invalid location '"+spec+"'; illegal args "+illegalArgs+"; acceptable args are "+ACCEPTABLE_ARGS);
-        }
-        if (argsMap.containsKey("displayName") && Strings.isEmpty(displayNamePart)) {
-            throw new IllegalArgumentException("Invalid location '"+spec+"'; if displayName supplied then value must be non-empty");
-        }
-        if (argsMap.containsKey("name") && Strings.isEmpty(namePart)) {
-            throw new IllegalArgumentException("Invalid location '"+spec+"'; if name supplied then value must be non-empty");
-        }
-
-        Map<String, Object> filteredProperties = new LocationPropertiesFromBrooklynProperties()
-                .getLocationProperties(PREFIX, namedLocation, registry.getProperties());
-        MutableMap<String, Object> flags = MutableMap.<String, Object>builder()
-                .putAll(filteredProperties)
-                .putAll(locationFlags)
-                .build();
-
-        String poolId = matcher.group(2);
-        if (Strings.isBlank(poolId)) {
-            throw new IllegalArgumentException("Invalid location '"+spec+"'; pool's entity id must be non-empty");
-        }
-
-        final String displayName = displayNamePart != null ? displayNamePart : "Server Pool " + poolId;
-        final String locationName = namePart != null ? namePart : "serverpool-" + poolId;
-
-        Entity pool = managementContext.getEntityManager().getEntity(poolId);
-        LocationSpec<ServerPoolLocation> locationSpec = LocationSpec.create(ServerPoolLocation.class)
-                .configure(flags)
-                .configure(DynamicLocation.OWNER, pool)
-                .configure(LocationInternal.NAMED_SPEC_NAME, locationName)
-                .displayName(displayName);
-        return managementContext.getLocationManager().createLocation(locationSpec);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/service/EntityLaunchListener.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/service/EntityLaunchListener.java b/software/base/src/main/java/brooklyn/entity/service/EntityLaunchListener.java
deleted file mode 100644
index d7cab7b..0000000
--- a/software/base/src/main/java/brooklyn/entity/service/EntityLaunchListener.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.service;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicReference;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.mgmt.ExecutionManager;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.api.sensor.SensorEvent;
-import org.apache.brooklyn.api.sensor.SensorEventListener;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags.EffectorCallTag;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.util.core.task.Tasks;
-
-public class EntityLaunchListener implements Runnable, SensorEventListener<Lifecycle> {
-    private static final String SSH_LAUNCH_TASK_PREFIX = "ssh: launching";
-    private static final String LAUNCH_CHECK_SKIP_TAG = "system-service-update";
-
-    private final AtomicReference<Task<?>> launchTaskRef = new AtomicReference<Task<?>>();
-    private final SystemServiceEnricher enricher;
-
-    public EntityLaunchListener(SystemServiceEnricher enricher) {
-        this.enricher = checkNotNull(enricher, "enricher");
-    }
-
-    @Override
-    public void onEvent(SensorEvent<Lifecycle> event) {
-        if (event.getValue() == Lifecycle.RUNNING) {
-            Task<?>launchTask = getLatestLaunchTask(enricher.getEntity());
-            if (launchTask != null) {
-                launchTaskRef.set(launchTask);
-                if (!launchTask.isDone()) {
-                    launchTask.addListener(this, enricher.getEntityExecutionContext());
-                }
-                if (launchTask.isDone()) {
-                    run();
-                }
-            }
-        }
-    }
-
-    @Override
-    public void run() {
-        Task<?> launchTask = launchTaskRef.getAndSet(null);
-        if (launchTask == null) return;
-        if (launchTask.isError()) return;
-        enricher.onLaunched(launchTask);
-    }
-
-    private Task<?> getLatestLaunchTask(Entity entity) {
-        Task<?> startEffector = null;
-        ExecutionManager executionmgr = enricher.getManagementContext().getExecutionManager();
-        Set<Task<?>> entityTasks = BrooklynTaskTags.getTasksInEntityContext(executionmgr, entity);
-        for (Task<?> t : entityTasks) {
-            if (BrooklynTaskTags.isEffectorTask(t)) {
-                EffectorCallTag effectorTag = BrooklynTaskTags.getEffectorCallTag(t, false);
-                if (SystemServiceEnricher.LAUNCH_EFFECTOR_NAMES.contains(effectorTag.getEffectorName()) &&
-                        !BrooklynTaskTags.hasTag(t, LAUNCH_CHECK_SKIP_TAG)) {
-                    if (startEffector == null || startEffector.getStartTimeUtc() < t.getStartTimeUtc()) {
-                        startEffector = t;
-                    }
-                    BrooklynTaskTags.addTagDynamically(t, LAUNCH_CHECK_SKIP_TAG);
-                }
-            }
-        }
-        if (startEffector != null) {
-            Task<?> launchTask = findSshLaunchChild(startEffector);
-            if (launchTask != null) {
-                return launchTask;
-            }
-        }
-        return null;
-    }
-
-    private Task<?> findSshLaunchChild(Task<?> t) {
-        Iterable<Task<?>> children = Tasks.children(t);
-        for (Task<?> c : children) {
-            if (c.getDisplayName().startsWith(SSH_LAUNCH_TASK_PREFIX)) {
-                return c;
-            }
-        }
-        for (Task<?> c : children) {
-            Task<?> launchTask = findSshLaunchChild(c);
-            if (launchTask != null) {
-                return launchTask;
-            }
-        }
-        return null;
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/service/InitdServiceInstaller.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/service/InitdServiceInstaller.java b/software/base/src/main/java/brooklyn/entity/service/InitdServiceInstaller.java
deleted file mode 100644
index 59fba2e..0000000
--- a/software/base/src/main/java/brooklyn/entity/service/InitdServiceInstaller.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.service;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.io.File;
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.api.objs.HasShortName;
-import org.apache.brooklyn.api.sensor.Enricher;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.effector.core.EffectorTasks;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.EntityInternal;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.location.cloud.names.AbstractCloudMachineNamer;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.ResourceUtils;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.core.task.ssh.SshPutTaskWrapper;
-import org.apache.brooklyn.util.core.task.ssh.SshTasks;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.apache.brooklyn.util.core.text.TemplateProcessor;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.ssh.BashCommands;
-
-
-public class InitdServiceInstaller implements SystemServiceInstaller {
-    private static final ConfigKey<String> SERVICE_TEMPLATE = ConfigKeys.newStringConfigKey(
-            "service.initd.service_template", "URL of the template to be used as the /etc/init.d service", "classpath:///brooklyn/entity/service/service.sh");
-
-    private final Entity entity;
-    private final Enricher enricher;
-
-    public InitdServiceInstaller(Entity entity, Enricher enricher) {
-        this.entity = checkNotNull(entity, "entity");
-        this.enricher = checkNotNull(enricher, "enricher");
-    }
-
-    @Override
-    public Task<?> getServiceInstallTask() {
-        ResourceUtils resource = new ResourceUtils(this);
-        String pidFile = entity.getAttribute(SoftwareProcess.PID_FILE);
-        String template = resource.getResourceAsString(enricher.config().get(SERVICE_TEMPLATE));
-        String serviceName = getServiceName();
-        SshMachineLocation sshMachine = EffectorTasks.getSshMachine(entity);
-        Map<String, Object> params = MutableMap.<String, Object>of(
-                "service.launch_script", Os.mergePaths(getRunDir(), getStartScriptName()),
-                "service.name", serviceName,
-                "service.user", sshMachine.getUser(),
-                "service.log_path", getLogLocation());
-        if (pidFile != null) {
-            params.put("service.pid_file", pidFile);
-        }
-        String service = TemplateProcessor.processTemplateContents(template, (EntityInternal)entity, params);
-        String tmpServicePath = Os.mergePaths(getRunDir(), serviceName);
-        String servicePath = "/etc/init.d/" + serviceName;
-        SshPutTaskWrapper putServiceTask = SshTasks.newSshPutTaskFactory(sshMachine, tmpServicePath)
-                .contents(service)
-                .newTask();
-        ProcessTaskWrapper<Integer> installServiceTask = SshTasks.newSshExecTaskFactory(sshMachine,
-                BashCommands.chain(
-                    BashCommands.sudo("mv " + tmpServicePath + " " + servicePath),
-                    BashCommands.sudo("chmod 0755 " + servicePath),
-                    BashCommands.sudo("chkconfig --add " + serviceName),
-                    BashCommands.sudo("chkconfig " + serviceName + " on")))
-            .requiringExitCodeZero()
-            .newTask();
-
-        return Tasks.<Void>builder()
-            .name("install (init.d)")
-            .description("Install init.d service")
-            .add(putServiceTask)
-            .add(installServiceTask)
-            .build();
-    }
-
-    private String getServiceName() {
-        String serviceNameTemplate = enricher.config().get(SystemServiceEnricher.SERVICE_NAME);
-        return serviceNameTemplate
-                .replace("${id}", entity.getId())
-                .replace("${entity_name}", getEntityName());
-    }
-
-    private CharSequence getEntityName() {
-        String name;
-        if (entity instanceof HasShortName) {
-            name = ((HasShortName)entity).getShortName();
-        } else if (entity instanceof Entity) {
-            name = ((Entity)entity).getDisplayName();
-        } else {
-            name = "brooklyn-service";
-        }
-        return AbstractCloudMachineNamer.sanitize(name.toString()).toLowerCase();
-    }
-
-    private String getStartScriptName() {
-        return enricher.config().get(SystemServiceEnricher.LAUNCH_SCRIPT_NAME);
-    }
-
-    private String getRunDir() {
-        return entity.getAttribute(SoftwareProcess.RUN_DIR);
-    }
-
-    private String getLogLocation() {
-        String logFileLocation = entity.getAttribute(Attributes.LOG_FILE_LOCATION);
-        if (logFileLocation != null) {
-            return new File(logFileLocation).getParent();
-        } else {
-            return "/tmp";
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/service/SystemServiceEnricher.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/service/SystemServiceEnricher.java b/software/base/src/main/java/brooklyn/entity/service/SystemServiceEnricher.java
deleted file mode 100644
index 959d078..0000000
--- a/software/base/src/main/java/brooklyn/entity/service/SystemServiceEnricher.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.service;
-
-import java.util.Set;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.mgmt.ExecutionContext;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.api.sensor.Enricher;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags.WrappedStream;
-import org.apache.brooklyn.effector.core.EffectorTasks;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.Entities;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.sensor.enricher.AbstractEnricher;
-import org.apache.brooklyn.util.core.task.BasicExecutionManager;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.TaskBuilder;
-import org.apache.brooklyn.util.core.task.ssh.SshPutTaskWrapper;
-import org.apache.brooklyn.util.core.task.ssh.SshTasks;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskFactory;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.apache.brooklyn.util.net.Urls;
-
-import com.google.common.collect.ImmutableSet;
-
-public class SystemServiceEnricher extends AbstractEnricher implements Enricher {
-    public static final String DEFAULT_ENRICHER_UNIQUE_TAG = "systemService.tag";
-    protected static final Set<String> LAUNCH_EFFECTOR_NAMES = ImmutableSet.of("start", "restart");
-    public static final ConfigKey<String> LAUNCH_SCRIPT_NAME = ConfigKeys.newStringConfigKey(
-            "service.script_name", "The name of the launch script to be created in the runtime directory of the entity.", "service-launch.sh");
-    public static final ConfigKey<String> SERVICE_NAME = ConfigKeys.newStringConfigKey(
-            "service.name", "The name of the system service. Can use ${entity_name} and ${id} variables to template the value.", "${entity_name}-${id}");
-
-    @Override
-    public void setEntity(EntityLocal entity) {
-        super.setEntity(entity);
-        subscribeLaunch();
-        uniqueTag = DEFAULT_ENRICHER_UNIQUE_TAG;
-    }
-
-    private void subscribeLaunch() {
-        subscribe(entity, Attributes.SERVICE_STATE_ACTUAL, new EntityLaunchListener(this));
-    }
-
-    public void onLaunched(Task<?> task) {
-        WrappedStream streamStdin = BrooklynTaskTags.stream(task, BrooklynTaskTags.STREAM_STDIN);
-        if (streamStdin == null) return;
-
-        WrappedStream streamEnv = BrooklynTaskTags.stream(task, BrooklynTaskTags.STREAM_ENV);
-        String stdin = streamStdin.streamContents.get();
-        String env = streamEnv.streamContents.get();
-
-        final SshMachineLocation sshMachine = EffectorTasks.getSshMachine(entity);
-        final String launchScriptPath = Urls.mergePaths(getRunDir(), getStartScriptName());
-
-        Task<Void> installerTask = TaskBuilder.<Void>builder()
-                .name("install (service)")
-                .description("Install as a system service")
-                .body(new Runnable() {
-                    @Override
-                    public void run() {
-                        ProcessTaskFactory<Integer> taskFactory = SshTasks.newSshExecTaskFactory(sshMachine, "[ -e '" + launchScriptPath + "' ]")
-                                .summary("check installed")
-                                .allowingNonZeroExitCode();
-                        boolean isInstalled = DynamicTasks.queue(taskFactory).get() == 0;
-                        if (!isInstalled) {
-                            Task<?> serviceInstallTask = SystemServiceInstallerFactory.of(entity, SystemServiceEnricher.this).getServiceInstallTask();
-                            DynamicTasks.queue(serviceInstallTask);
-                        }
-                    }
-                })
-                .build();
-
-        SshPutTaskWrapper updateLaunchScriptTask = SshTasks.newSshPutTaskFactory(sshMachine, launchScriptPath).contents(getLaunchScript(stdin, env)).newTask();
-        ProcessTaskWrapper<Integer> makeExecutableTask = SshTasks.newSshExecTaskFactory(sshMachine, "chmod +x " + launchScriptPath)
-                .requiringExitCodeZero()
-                .newTask();
-        Task<Void> udpateTask = TaskBuilder.<Void>builder()
-                .name("update-launch")
-                .description("Update launch script used by the system service")
-                .add(updateLaunchScriptTask)
-                .add(makeExecutableTask)
-                .build();
-
-        Task<Void> updateService = TaskBuilder.<Void>builder()
-                .name("update-system-service")
-                .description("Update system service")
-                .add(installerTask)
-                .add(udpateTask)
-                .tag(BrooklynTaskTags.tagForContextEntity(entity))
-                .tag(BrooklynTaskTags.NON_TRANSIENT_TASK_TAG)
-                .build();
-
-        submitTopLevel(updateService);
-    }
-
-    private void submitTopLevel(Task<Void> updateService) {
-        Task<?> currentTask = BasicExecutionManager.getPerThreadCurrentTask().get();
-        BasicExecutionManager.getPerThreadCurrentTask().set(null);
-        try {
-            Entities.submit(entity, updateService);
-        } finally {
-            BasicExecutionManager.getPerThreadCurrentTask().set(currentTask);
-        }
-    }
-
-    private String getLaunchScript(String stdin, String env) {
-        // (?m) - multiline enable
-        // insert export at beginning of each line
-        return env.replaceAll("(?m)^", "export ") + "\n" + stdin;
-    }
-
-    private String getRunDir() {
-        return entity.getAttribute(SoftwareProcess.RUN_DIR);
-    }
-
-    private String getStartScriptName() {
-        return config().get(LAUNCH_SCRIPT_NAME);
-    }
-
-    ExecutionContext getEntityExecutionContext() {
-        return getManagementContext().getExecutionContext(entity);
-    }
-
-    protected Entity getEntity() {
-        return entity;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/service/SystemServiceInstaller.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/service/SystemServiceInstaller.java b/software/base/src/main/java/brooklyn/entity/service/SystemServiceInstaller.java
deleted file mode 100644
index c5e6533..0000000
--- a/software/base/src/main/java/brooklyn/entity/service/SystemServiceInstaller.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.service;
-
-import org.apache.brooklyn.api.mgmt.Task;
-
-public interface SystemServiceInstaller {
-    Task<?> getServiceInstallTask();
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/service/SystemServiceInstallerFactory.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/service/SystemServiceInstallerFactory.java b/software/base/src/main/java/brooklyn/entity/service/SystemServiceInstallerFactory.java
deleted file mode 100644
index c7f5d9e..0000000
--- a/software/base/src/main/java/brooklyn/entity/service/SystemServiceInstallerFactory.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.service;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.sensor.Enricher;
-
-public class SystemServiceInstallerFactory {
-    public static SystemServiceInstaller of(Entity entity, Enricher systemServiceEnricher) {
-        return new InitdServiceInstaller(entity, systemServiceEnricher);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/software/MachineInitTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/software/MachineInitTasks.java b/software/base/src/main/java/brooklyn/entity/software/MachineInitTasks.java
deleted file mode 100644
index b9c43b8..0000000
--- a/software/base/src/main/java/brooklyn/entity/software/MachineInitTasks.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software;
-
-import java.util.List;
-import java.util.concurrent.Callable;
-
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.annotations.Beta;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.core.task.ssh.SshTasks;
-import org.apache.brooklyn.util.net.Protocol;
-import org.apache.brooklyn.util.ssh.BashCommands;
-import org.apache.brooklyn.util.ssh.IptablesCommands;
-import org.apache.brooklyn.util.ssh.IptablesCommands.Chain;
-import org.apache.brooklyn.util.ssh.IptablesCommands.Policy;
-import org.apache.brooklyn.util.text.Strings;
-
-/**
- * 
- */
-@Beta
-public class MachineInitTasks {
-
-    // TODO Move somewhere so code can also be called by JcloudsLocation!
-    
-    private static final Logger log = LoggerFactory.getLogger(MachineInitTasks.class);
-
-    protected EntityInternal entity() {
-        return (EntityInternal) BrooklynTaskTags.getTargetOrContextEntity(Tasks.current());
-    }
-
-    /**
-     * Returns a queued {@link Task} which opens the given ports in iptables on the given machine.
-     */
-    public Task<Void> openIptablesAsync(final Iterable<Integer> inboundPorts, final SshMachineLocation machine) {
-        return DynamicTasks.queue("open iptables "+toTruncatedString(inboundPorts, 6), new Callable<Void>() {
-            public Void call() {
-                openIptablesImpl(inboundPorts, machine);
-                return null;
-            }
-        });
-    }
-
-    /**
-     * Returns a queued {@link Task} which stops iptables on the given machine.
-     */
-    public Task<Void> stopIptablesAsync(final SshMachineLocation machine) {
-        return DynamicTasks.queue("stop iptables", new Callable<Void>() {
-            public Void call() {
-                stopIptablesImpl(machine);
-                return null;
-            }
-        });
-    }
-
-    /**
-     * See docs in {@link BashCommands#dontRequireTtyForSudo()}
-     */
-    public Task<Boolean> dontRequireTtyForSudoAsync(final SshMachineLocation machine) {
-        return DynamicTasks.queue(SshTasks.dontRequireTtyForSudo(machine, true).newTask().asTask());
-    }
-
-    protected void openIptablesImpl(Iterable<Integer> inboundPorts, SshMachineLocation machine) {
-        if (inboundPorts == null || Iterables.isEmpty(inboundPorts)) {
-            log.info("No ports to open in iptables (no inbound ports) for {} at {}", machine, this);
-        } else {
-            log.info("Opening ports in iptables for {} at {}", entity(), machine);
-
-            List<String> iptablesRules = Lists.newArrayList();
-
-            if (isLocationFirewalldEnabled(machine)) {
-                for (Integer port : inboundPorts) {
-                    iptablesRules.add(IptablesCommands.addFirewalldRule(Chain.INPUT, Protocol.TCP, port, Policy.ACCEPT));
-                 }
-            } else {
-                iptablesRules = createIptablesRulesForNetworkInterface(inboundPorts);
-                iptablesRules.add(IptablesCommands.saveIptablesRules());
-            }
-            List<String> batch = Lists.newArrayList();
-            // Some entities, such as Riak (erlang based) have a huge range of ports, which leads to a script that
-            // is too large to run (fails with a broken pipe). Batch the rules into batches of 50
-            for (String rule : iptablesRules) {
-                batch.add(rule);
-                if (batch.size() == 50) {
-                    machine.execCommands("Inserting iptables rules, 50 command batch", batch);
-                    batch.clear();
-                }
-            }
-            if (batch.size() > 0) {
-                machine.execCommands("Inserting iptables rules", batch);
-            }
-            machine.execCommands("List iptables rules", ImmutableList.of(IptablesCommands.listIptablesRule()));
-        }
-    }
-
-    protected void stopIptablesImpl(SshMachineLocation machine) {
-        log.info("Stopping iptables for {} at {}", entity(), machine);
-
-        List<String> cmds = ImmutableList.<String>of();
-        if (isLocationFirewalldEnabled(machine)) {
-            cmds = ImmutableList.of(IptablesCommands.firewalldServiceStop(), IptablesCommands.firewalldServiceStatus());
-        } else {
-            cmds = ImmutableList.of(IptablesCommands.iptablesServiceStop(), IptablesCommands.iptablesServiceStatus());
-        }
-        machine.execCommands("Stopping iptables", cmds);
-    }
-    
-    private List<String> createIptablesRulesForNetworkInterface(Iterable<Integer> ports) {
-        List<String> iptablesRules = Lists.newArrayList();
-        for (Integer port : ports) {
-           iptablesRules.add(IptablesCommands.insertIptablesRule(Chain.INPUT, Protocol.TCP, port, Policy.ACCEPT));
-        }
-        return iptablesRules;
-     }
-
-    public boolean isLocationFirewalldEnabled(SshMachineLocation location) {
-        int result = location.execCommands("checking if firewalld is active", 
-                ImmutableList.of(IptablesCommands.firewalldServiceIsActive()));
-        if (result == 0) {
-            return true;
-        }
-        
-        return false;
-    }
-    
-    protected String toTruncatedString(Iterable<?> vals, int maxShown) {
-        StringBuilder result = new StringBuilder("[");
-        int shown = 0;
-        for (Object val : (vals == null ? ImmutableList.of() : vals)) {
-            if (shown != 0) {
-                result.append(", ");
-            }
-            if (shown < maxShown) {
-                result.append(Strings.toString(val));
-                shown++;
-            } else {
-                result.append("...");
-                break;
-            }
-        }
-        result.append("]");
-        return result.toString();
-    }
-}


[68/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - cleanup and test fixes following refectoring, esp the software/base changes

Posted by he...@apache.org.
BROOKLYN-162 - cleanup and test fixes following refectoring, esp the software/base 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/c45bab04
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/c45bab04
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/c45bab04

Branch: refs/heads/master
Commit: c45bab04f2efec84ce489e6f505f12cf0bdbcd53
Parents: a1ad34d
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Wed Aug 19 01:00:43 2015 +0100
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Wed Aug 19 02:13:26 2015 +0100

----------------------------------------------------------------------
 .../entity/machine/pool/ServerPool.java         |  2 +-
 .../brooklyn/sensor/feed/jmx/JmxFeed.java       | 17 ++-------
 .../BrooklynNodeIntegrationTest.java            |  4 +--
 .../app/ClusterWebServerDatabaseSample.java     | 36 ++++++++++----------
 .../sample/app/SingleWebServerSample.java       | 13 ++++---
 .../app/SampleLocalhostIntegrationTest.java     | 19 +++++------
 .../brooklyn/sample/app/SampleUnitTest.java     | 21 ++++++------
 .../brooklyn/cli/BaseCliIntegrationTest.java    |  2 +-
 .../specs/model/sensor-summary-spec.js          |  2 +-
 .../brooklyn/launcher/BrooklynLauncherTest.java |  2 +-
 .../resources/rebind-test-catalog-additions.bom |  4 +--
 .../src/test/resources/rebind-test-catalog.bom  |  4 +--
 .../fixtures/catalog-application-list.json      |  6 ++--
 .../resources/fixtures/catalog-application.json |  2 +-
 .../resources/fixtures/sensor-summary-list.json |  2 +-
 .../src/main/resources/reset-catalog.xml        |  6 ++--
 .../rest/resources/CatalogResetTest.java        |  4 +--
 .../rest/resources/CatalogResourceTest.java     | 18 +++++-----
 .../test/osgi/entities/more/MoreEntity.java     |  1 -
 .../test/osgi/entities/more/MoreEntityImpl.java |  1 -
 .../test/osgi/entities/more/MoreLocation.java   |  1 -
 .../test/osgi/entities/more/MorePolicy.java     |  2 --
 .../test/osgi/entities/more/MoreTemplate.java   |  6 ----
 .../test/osgi/entities/more/MoreEntity.java     |  6 ++--
 .../test/osgi/entities/more/MoreEntityImpl.java |  7 ++--
 .../test/osgi/entities/more/MoreEntity.java     |  6 ++--
 .../test/osgi/entities/more/MoreEntityImpl.java |  7 ++--
 .../test/osgi/entities/more/MoreLocation.java   |  2 +-
 .../test/osgi/entities/more/MorePolicy.java     |  2 +-
 .../test/osgi/entities/more/MoreTemplate.java   |  7 +---
 30 files changed, 89 insertions(+), 123 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPool.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPool.java b/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPool.java
index 548242f..6b89388 100644
--- a/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPool.java
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPool.java
@@ -56,7 +56,7 @@ import org.apache.brooklyn.sensor.core.Sensors;
  *         {@link org.apache.brooklyn.entity.software.base.SoftwareProcess#PROVISIONING_PROPERTIES PROVISIONING_PROPERTIES}.
  *         For example, in YAML:
  *         <pre>
- *     - type: brooklyn.entity.pool.ServerPool
+ *     - type: org.apache.brooklyn.entity.machine.pool.ServerPool
  *       brooklyn.config:
  *         # Suitable for TomcatServers
  *         provisioning.properties:

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeed.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeed.java b/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeed.java
index 3c1897e..dec24cc 100644
--- a/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeed.java
+++ b/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeed.java
@@ -257,21 +257,8 @@ public class JmxFeed extends AbstractFeed {
     protected void preStart() {
         /*
          * All actions on the JmxHelper are done async (through the poller's threading) so we don't 
-         * block on start for a long time (e.g. if the entity is not contactable and doing a rebind 
-         * on restart of brooklyn). Without that, one gets a 120 second pause with it stuck in a 
-         * stack trace like:
-         * 
-         *      at brooklyn.event.feed.jmx.JmxHelper.sleep(JmxHelper.java:640)
-         *      at brooklyn.event.feed.jmx.JmxHelper.connect(JmxHelper.java:320)
-         *      at brooklyn.event.feed.jmx.JmxFeed.preStart(JmxFeed.java:172)
-         *      at brooklyn.event.feed.AbstractFeed.start(AbstractFeed.java:68)
-         *      at brooklyn.event.feed.jmx.JmxFeed$Builder.build(JmxFeed.java:119)
-         *      at brooklyn.entity.java.JavaAppUtils.connectMXBeanSensors(JavaAppUtils.java:109)
-         *      at brooklyn.entity.java.VanillaJavaApp.connectSensors(VanillaJavaApp.java:97)
-         *      at brooklyn.entity.basic.SoftwareProcessImpl.callRebindHooks(SoftwareProcessImpl.java:189)
-         *      at brooklyn.entity.basic.SoftwareProcessImpl.rebind(SoftwareProcessImpl.java:235)
-         *      ...
-         *      at brooklyn.entity.rebind.RebindManagerImpl.rebind(RebindManagerImpl.java:184)
+         * block on start/rebind if the entity is unreachable 
+         * (without this we get a 120s pause in JmxHelper.connect restarting)
          */
         final SetMultimap<NotificationFilter, JmxNotificationSubscriptionConfig<?>> notificationSubscriptions = getConfig(NOTIFICATION_SUBSCRIPTIONS);
         final SetMultimap<List<?>, JmxOperationPollConfig<?>> operationPolls = getConfig(OPERATION_POLLS);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java
index 0092612..e73cf9f 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java
@@ -155,7 +155,7 @@ public class BrooklynNodeIntegrationTest extends BrooklynAppUnitTestSupport {
 
 location: localhost
 services:
-- type: brooklyn.entity.brooklynnode.BrooklynNode
+- type: org.apache.brooklyn.entity.brooklynnode.BrooklynNode
   bindAddress: 127.0.0.1
   onExistingProperties: do_not_use
 
@@ -368,7 +368,7 @@ services:
     protected void waitForApps(final URI webConsoleUri, final int num) {
         waitForApps(webConsoleUri.toString());
         
-        // e.g. [{"id":"UnBqPcqg","spec":{"name":"Application (UnBqPcqg)","type":"brooklyn.entity.basic.BasicApplication","locations":["pOL4NtiW"]},"status":"RUNNING","links":{"self":"/v1/applications/UnBqPcqg","entities":"/v1/applications/UnBqPcqg/entities"}}]
+        // e.g. [{"id":"UnBqPcqg","spec":{"name":"Application (UnBqPcqg)","type":"org.apache.brooklyn.entity.stock.BasicApplication","locations":["pOL4NtiW"]},"status":"RUNNING","links":{"self":"/v1/applications/UnBqPcqg","entities":"/v1/applications/UnBqPcqg/entities"}}]
         Asserts.succeedsEventually(new Runnable() {
             @Override
             public void run() {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/usage/archetypes/quickstart/src/brooklyn-sample/src/main/java/com/acme/sample/brooklyn/sample/app/ClusterWebServerDatabaseSample.java
----------------------------------------------------------------------
diff --git a/usage/archetypes/quickstart/src/brooklyn-sample/src/main/java/com/acme/sample/brooklyn/sample/app/ClusterWebServerDatabaseSample.java b/usage/archetypes/quickstart/src/brooklyn-sample/src/main/java/com/acme/sample/brooklyn/sample/app/ClusterWebServerDatabaseSample.java
index cd18511..bfbb464 100644
--- a/usage/archetypes/quickstart/src/brooklyn-sample/src/main/java/com/acme/sample/brooklyn/sample/app/ClusterWebServerDatabaseSample.java
+++ b/usage/archetypes/quickstart/src/brooklyn-sample/src/main/java/com/acme/sample/brooklyn/sample/app/ClusterWebServerDatabaseSample.java
@@ -1,41 +1,41 @@
 package com.acme.sample.brooklyn.sample.app;
 
-import static brooklyn.event.basic.DependentConfiguration.attributeWhenReady;
-import static brooklyn.event.basic.DependentConfiguration.formatString;
-
 import java.util.concurrent.TimeUnit;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import org.apache.brooklyn.api.catalog.Catalog;
 import org.apache.brooklyn.api.catalog.CatalogConfig;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
-import brooklyn.enricher.HttpLatencyDetector;
-import brooklyn.enricher.basic.SensorPropagatingEnricher;
-import brooklyn.enricher.basic.SensorTransformingEnricher;
-import brooklyn.entity.basic.AbstractApplication;
-import brooklyn.entity.basic.ConfigKeys;
-import brooklyn.entity.basic.Entities;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.core.AbstractApplication;
+import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.mysql.MySqlNode;
-import brooklyn.entity.group.DynamicCluster;
-import brooklyn.entity.java.JavaEntityMethods;
-import org.apache.brooklyn.api.entity.proxying.EntitySpec;
+import org.apache.brooklyn.entity.group.DynamicCluster;
+import org.apache.brooklyn.entity.java.JavaEntityMethods;
 import org.apache.brooklyn.entity.webapp.ControlledDynamicWebAppCluster;
 import org.apache.brooklyn.entity.webapp.DynamicWebAppCluster;
 import org.apache.brooklyn.entity.webapp.JavaWebAppService;
 import org.apache.brooklyn.entity.webapp.WebAppService;
 import org.apache.brooklyn.entity.webapp.WebAppServiceConstants;
-import org.apache.brooklyn.api.event.AttributeSensor;
-import brooklyn.event.basic.Sensors;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.policy.autoscaling.AutoScalerPolicy;
+import org.apache.brooklyn.policy.enricher.HttpLatencyDetector;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.sensor.enricher.SensorPropagatingEnricher;
+import org.apache.brooklyn.sensor.enricher.SensorTransformingEnricher;
 import org.apache.brooklyn.util.maven.MavenArtifact;
 import org.apache.brooklyn.util.maven.MavenRetriever;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import com.google.common.base.Functions;
 
+import static org.apache.brooklyn.sensor.core.DependentConfiguration.attributeWhenReady;
+import static org.apache.brooklyn.sensor.core.DependentConfiguration.formatString;
+
+
 /** This sample builds a 3-tier application with an elastic app-server cluster,
  *  and it sets it up for use in the Brooklyn catalog. 
  *  <p>

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/usage/archetypes/quickstart/src/brooklyn-sample/src/main/java/com/acme/sample/brooklyn/sample/app/SingleWebServerSample.java
----------------------------------------------------------------------
diff --git a/usage/archetypes/quickstart/src/brooklyn-sample/src/main/java/com/acme/sample/brooklyn/sample/app/SingleWebServerSample.java b/usage/archetypes/quickstart/src/brooklyn-sample/src/main/java/com/acme/sample/brooklyn/sample/app/SingleWebServerSample.java
index 4452bd6..46b1dff 100644
--- a/usage/archetypes/quickstart/src/brooklyn-sample/src/main/java/com/acme/sample/brooklyn/sample/app/SingleWebServerSample.java
+++ b/usage/archetypes/quickstart/src/brooklyn-sample/src/main/java/com/acme/sample/brooklyn/sample/app/SingleWebServerSample.java
@@ -1,16 +1,15 @@
 package com.acme.sample.brooklyn.sample.app;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.AbstractApplication;
-import brooklyn.entity.basic.Attributes;
-import org.apache.brooklyn.api.entity.proxying.EntitySpec;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.entity.core.AbstractApplication;
+import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.webapp.JavaWebAppService;
 import org.apache.brooklyn.entity.webapp.jboss.JBoss7Server;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.util.maven.MavenArtifact;
 import org.apache.brooklyn.util.maven.MavenRetriever;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /** This example starts one web app on 8080. */
 public class SingleWebServerSample extends AbstractApplication {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/usage/archetypes/quickstart/src/brooklyn-sample/src/test/java/com/acme/sample/brooklyn/sample/app/SampleLocalhostIntegrationTest.java
----------------------------------------------------------------------
diff --git a/usage/archetypes/quickstart/src/brooklyn-sample/src/test/java/com/acme/sample/brooklyn/sample/app/SampleLocalhostIntegrationTest.java b/usage/archetypes/quickstart/src/brooklyn-sample/src/test/java/com/acme/sample/brooklyn/sample/app/SampleLocalhostIntegrationTest.java
index 373a012..1122448 100644
--- a/usage/archetypes/quickstart/src/brooklyn-sample/src/test/java/com/acme/sample/brooklyn/sample/app/SampleLocalhostIntegrationTest.java
+++ b/usage/archetypes/quickstart/src/brooklyn-sample/src/test/java/com/acme/sample/brooklyn/sample/app/SampleLocalhostIntegrationTest.java
@@ -3,6 +3,15 @@ package com.acme.sample.brooklyn.sample.app;
 import java.util.Arrays;
 import java.util.Iterator;
 
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.core.StartableApplication;
+import org.apache.brooklyn.entity.webapp.JavaWebAppService;
+import org.apache.brooklyn.util.core.ResourceUtils;
+import org.apache.brooklyn.util.text.Strings;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.Assert;
@@ -10,16 +19,6 @@ import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
-import org.apache.brooklyn.api.entity.Entity;
-import brooklyn.entity.basic.Entities;
-import brooklyn.entity.basic.StartableApplication;
-import org.apache.brooklyn.api.entity.proxying.EntitySpec;
-import org.apache.brooklyn.entity.webapp.JavaWebAppService;
-import org.apache.brooklyn.api.management.ManagementContext;
-import org.apache.brooklyn.core.management.internal.LocalManagementContext;
-import org.apache.brooklyn.core.util.ResourceUtils;
-import org.apache.brooklyn.util.text.Strings;
-
 /**
  * Sample integration tests which show how to launch the sample applications on localhost,
  * make some assertions about them, and then destroy them.

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/usage/archetypes/quickstart/src/brooklyn-sample/src/test/java/com/acme/sample/brooklyn/sample/app/SampleUnitTest.java
----------------------------------------------------------------------
diff --git a/usage/archetypes/quickstart/src/brooklyn-sample/src/test/java/com/acme/sample/brooklyn/sample/app/SampleUnitTest.java b/usage/archetypes/quickstart/src/brooklyn-sample/src/test/java/com/acme/sample/brooklyn/sample/app/SampleUnitTest.java
index 537b547..181d61f 100644
--- a/usage/archetypes/quickstart/src/brooklyn-sample/src/test/java/com/acme/sample/brooklyn/sample/app/SampleUnitTest.java
+++ b/usage/archetypes/quickstart/src/brooklyn-sample/src/test/java/com/acme/sample/brooklyn/sample/app/SampleUnitTest.java
@@ -1,5 +1,15 @@
 package com.acme.sample.brooklyn.sample.app;
 
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.core.StartableApplication;
+import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
+import org.apache.brooklyn.entity.database.mysql.MySqlNode;
+import org.apache.brooklyn.entity.webapp.JavaWebAppService;
+import org.apache.brooklyn.entity.webapp.WebAppService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.Assert;
@@ -7,17 +17,6 @@ import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
-import org.apache.brooklyn.api.entity.Entity;
-import brooklyn.entity.basic.Entities;
-import brooklyn.entity.basic.StartableApplication;
-import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
-import org.apache.brooklyn.entity.database.mysql.MySqlNode;
-import org.apache.brooklyn.api.entity.proxying.EntitySpec;
-import org.apache.brooklyn.entity.webapp.JavaWebAppService;
-import org.apache.brooklyn.entity.webapp.WebAppService;
-import org.apache.brooklyn.api.management.ManagementContext;
-import org.apache.brooklyn.core.management.internal.LocalManagementContext;
-
 import com.google.common.base.Predicates;
 import com.google.common.collect.Iterables;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/usage/dist/src/test/java/org/apache/brooklyn/cli/BaseCliIntegrationTest.java
----------------------------------------------------------------------
diff --git a/usage/dist/src/test/java/org/apache/brooklyn/cli/BaseCliIntegrationTest.java b/usage/dist/src/test/java/org/apache/brooklyn/cli/BaseCliIntegrationTest.java
index 49b4d6d..0960c16 100644
--- a/usage/dist/src/test/java/org/apache/brooklyn/cli/BaseCliIntegrationTest.java
+++ b/usage/dist/src/test/java/org/apache/brooklyn/cli/BaseCliIntegrationTest.java
@@ -38,7 +38,7 @@ import java.util.concurrent.TimeoutException;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 
-import brooklyn.entity.basic.ApplicationBuilder;
+import org.apache.brooklyn.entity.factory.ApplicationBuilder;
 
 import com.google.common.collect.Lists;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/usage/jsgui/src/test/javascript/specs/model/sensor-summary-spec.js
----------------------------------------------------------------------
diff --git a/usage/jsgui/src/test/javascript/specs/model/sensor-summary-spec.js b/usage/jsgui/src/test/javascript/specs/model/sensor-summary-spec.js
index b1bd2fd..222df70 100644
--- a/usage/jsgui/src/test/javascript/specs/model/sensor-summary-spec.js
+++ b/usage/jsgui/src/test/javascript/specs/model/sensor-summary-spec.js
@@ -32,7 +32,7 @@ define(['model/sensor-summary'], function (SensorSummary) {
             expect(filteredSensors.length).toBe(1)
             var ourSensor = filteredSensors.pop()
             expect(ourSensor.get("name")).toBe('service.state')
-            expect(ourSensor.get("type")).toBe('org.apache.brooklyn.entity.software.base.Lifecycle')
+            expect(ourSensor.get("type")).toBe('org.apache.brooklyn.entity.lifecycle.Lifecycle')
             expect(ourSensor.get("description")).toBe('Service lifecycle state')
             expect(ourSensor.getLinkByName('self')).toBe('fixtures/service-state.json')
             expect(ourSensor.getLinkByName()).toBe(undefined)

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherTest.java
----------------------------------------------------------------------
diff --git a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherTest.java b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherTest.java
index e25e1fd..48600a3 100644
--- a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherTest.java
+++ b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherTest.java
@@ -161,7 +161,7 @@ public class BrooklynLauncherTest {
     public void testStartsAppFromYAML() throws Exception {
         String yaml = "name: example-app\n" +
                 "services:\n" +
-                "- serviceType: org.apache.brooklyn.test.entity.TestEntity\n" +
+                "- serviceType: org.apache.brooklyn.core.test.entity.TestEntity\n" +
                 "  name: test-app";
         launcher = newLauncherForTests(true)
                 .webconsole(false)

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/usage/launcher/src/test/resources/rebind-test-catalog-additions.bom
----------------------------------------------------------------------
diff --git a/usage/launcher/src/test/resources/rebind-test-catalog-additions.bom b/usage/launcher/src/test/resources/rebind-test-catalog-additions.bom
index 8c460c8..f4fa777 100644
--- a/usage/launcher/src/test/resources/rebind-test-catalog-additions.bom
+++ b/usage/launcher/src/test/resources/rebind-test-catalog-additions.bom
@@ -25,8 +25,8 @@ brooklyn.catalog:
 
   - id: three
     item:
-      type: brooklyn.entity.basic.EmptySoftwareProcess
+      type: org.apache.brooklyn.entity.software.base.EmptySoftwareProcess
 
   - id: four
     item:
-      type: brooklyn.entity.basic.VanillaSoftwareProcess
\ No newline at end of file
+      type: org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/usage/launcher/src/test/resources/rebind-test-catalog.bom
----------------------------------------------------------------------
diff --git a/usage/launcher/src/test/resources/rebind-test-catalog.bom b/usage/launcher/src/test/resources/rebind-test-catalog.bom
index cb3b4dc..f19e4c4 100644
--- a/usage/launcher/src/test/resources/rebind-test-catalog.bom
+++ b/usage/launcher/src/test/resources/rebind-test-catalog.bom
@@ -25,8 +25,8 @@ brooklyn.catalog:
 
   - id: one
     item:
-      type: brooklyn.entity.basic.EmptySoftwareProcess
+      type: org.apache.brooklyn.entity.software.base.EmptySoftwareProcess
 
   - id: two
     item:
-      type: brooklyn.entity.basic.VanillaSoftwareProcess
\ No newline at end of file
+      type: org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/usage/rest-api/src/test/resources/fixtures/catalog-application-list.json
----------------------------------------------------------------------
diff --git a/usage/rest-api/src/test/resources/fixtures/catalog-application-list.json b/usage/rest-api/src/test/resources/fixtures/catalog-application-list.json
index 68314f0..c4757be 100644
--- a/usage/rest-api/src/test/resources/fixtures/catalog-application-list.json
+++ b/usage/rest-api/src/test/resources/fixtures/catalog-application-list.json
@@ -5,7 +5,7 @@
         "name": "My example application",
         "version": "1.1",
         "description": "My awesome example application, as a catalog item",
-        "planYaml": "services:\n- type: brooklyn.entity.basic.VanillaSoftwareProcess\n  launch.command: echo \"Launch application\"\n  checkRunning.command: echo \"Check running application\"",
+        "planYaml": "services:\n- type: org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess\n  launch.command: echo \"Launch application\"\n  checkRunning.command: echo \"Check running application\"",
         "iconUrl": "http://my.example.com/icon.png"
     },
     {
@@ -14,7 +14,7 @@
         "name": "My example application",
         "version": "2.0",
         "description": "My awesome example application, as a catalog item",
-        "planYaml": "services:\n- type: brooklyn.entity.basic.VanillaSoftwareProcess\n  launch.command: echo \"Launch application\"\n  checkRunning.command: echo \"Check running application\"",
+        "planYaml": "services:\n- type: org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess\n  launch.command: echo \"Launch application\"\n  checkRunning.command: echo \"Check running application\"",
         "iconUrl": "http://my.example.com/icon.png"
     },
     {
@@ -23,7 +23,7 @@
         "name": "Another example application",
         "version": "1.0",
         "description": "Another awesome example application, as a catalog item",
-        "planYaml": "services:\n- type: brooklyn.entity.basic.VanillaSoftwareProcess\n  launch.command: echo \"Launch other application\"\n  checkRunning.command: echo \"Check running other application\"",
+        "planYaml": "services:\n- type: org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess\n  launch.command: echo \"Launch other application\"\n  checkRunning.command: echo \"Check running other application\"",
         "iconUrl": "http://my.other.example.com/icon.png"
     }
 ]
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/usage/rest-api/src/test/resources/fixtures/catalog-application.json
----------------------------------------------------------------------
diff --git a/usage/rest-api/src/test/resources/fixtures/catalog-application.json b/usage/rest-api/src/test/resources/fixtures/catalog-application.json
index 2a3ed8d..7c72270 100644
--- a/usage/rest-api/src/test/resources/fixtures/catalog-application.json
+++ b/usage/rest-api/src/test/resources/fixtures/catalog-application.json
@@ -4,6 +4,6 @@
     "name": "My example application",
     "version": "1.1",
     "description": "My awesome example application, as a catalog item",
-    "planYaml": "services:\n- type: brooklyn.entity.basic.VanillaSoftwareProcess\n  launch.command: echo \"Launch application\"\n  checkRunning.command: echo \"Check running application\"",
+    "planYaml": "services:\n- type: org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess\n  launch.command: echo \"Launch application\"\n  checkRunning.command: echo \"Check running application\"",
     "iconUrl": "http://my.example.com/icon.png"
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/usage/rest-api/src/test/resources/fixtures/sensor-summary-list.json
----------------------------------------------------------------------
diff --git a/usage/rest-api/src/test/resources/fixtures/sensor-summary-list.json b/usage/rest-api/src/test/resources/fixtures/sensor-summary-list.json
index 112b89c..6ab457b 100644
--- a/usage/rest-api/src/test/resources/fixtures/sensor-summary-list.json
+++ b/usage/rest-api/src/test/resources/fixtures/sensor-summary-list.json
@@ -1,7 +1,7 @@
 [
     {
         "name":"service.state",
-        "type":"brooklyn.entity.basic.Lifecycle",
+        "type":"org.apache.brooklyn.entity.lifecycle.Lifecycle",
         "description":"Service lifecycle state",
         "links":{
             "self":"fixtures/service-state.json",

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/usage/rest-server/src/main/resources/reset-catalog.xml
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/main/resources/reset-catalog.xml b/usage/rest-server/src/main/resources/reset-catalog.xml
index 5e6d0f8..adef40a 100644
--- a/usage/rest-server/src/main/resources/reset-catalog.xml
+++ b/usage/rest-server/src/main/resources/reset-catalog.xml
@@ -20,15 +20,15 @@
 <catalog>
     <name>Brooklyn Demos</name>
 
-    <template type="org.apache.brooklyn.entity.software.base.BasicApplication" name="Basic application" />
-    <template type="brooklyn.osgi.tests.SimpleApplication" name="Simple OSGi application">
+    <template type="org.apache.brooklyn.entity.stock.BasicApplication" name="Basic application" />
+    <template type="org.apache.brooklyn.test.osgi.entities.SimpleApplication" name="Simple OSGi application">
         <libraries>
             <bundle>${bundle-location}</bundle>
         </libraries>
     </template>
     <catalog>
         <name>Nested catalog</name>
-        <template type="brooklyn.osgi.tests.SimpleApplication" name="Simple OSGi application">
+        <template type="org.apache.brooklyn.test.osgi.entities.SimpleApplication" name="Simple OSGi application">
             <libraries>
                 <bundle>${bundle-location}</bundle>
             </libraries>

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/CatalogResetTest.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/CatalogResetTest.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/CatalogResetTest.java
index e3d20db..6adfdb5 100644
--- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/CatalogResetTest.java
+++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/CatalogResetTest.java
@@ -105,8 +105,8 @@ public class CatalogResetTest extends BrooklynRestResourceTest {
     
     private void assertItems() {
         BrooklynCatalog catalog = getManagementContext().getCatalog();
-        assertNotNull(catalog.getCatalogItem("brooklyn.entity.basic.BasicApplication", BrooklynCatalog.DEFAULT_VERSION));
-        assertNotNull(catalog.getCatalogItem("brooklyn.osgi.tests.SimpleApplication", BrooklynCatalog.DEFAULT_VERSION));
+        assertNotNull(catalog.getCatalogItem("org.apache.brooklyn.entity.stock.BasicApplication", BrooklynCatalog.DEFAULT_VERSION));
+        assertNotNull(catalog.getCatalogItem("org.apache.brooklyn.test.osgi.entities.SimpleApplication", BrooklynCatalog.DEFAULT_VERSION));
     }
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/CatalogResourceTest.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/CatalogResourceTest.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/CatalogResourceTest.java
index 4bee445..b38c87d 100644
--- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/CatalogResourceTest.java
+++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/CatalogResourceTest.java
@@ -87,13 +87,13 @@ public class CatalogResourceTest extends BrooklynRestResourceTest {
                 "  id: " + symbolicName + "\n"+
                 "  name: My Catalog App\n"+
                 "  description: My description\n"+
-                "  icon_url: classpath:/brooklyn/osgi/tests/icon.gif\n"+
+                "  icon_url: classpath:/org/apache/brooklyn/test/osgi/entities/icon.gif\n"+
                 "  version: " + TEST_VERSION + "\n"+
                 "  libraries:\n"+
                 "  - url: " + bundleUrl + "\n"+
                 "\n"+
                 "services:\n"+
-                "- type: org.apache.brooklyn.test.entity.TestEntity\n";
+                "- type: org.apache.brooklyn.core.test.entity.TestEntity\n";
 
         ClientResponse response = client().resource("/v1/catalog")
                 .post(ClientResponse.class, yaml);
@@ -104,7 +104,7 @@ public class CatalogResourceTest extends BrooklynRestResourceTest {
                 .get(CatalogEntitySummary.class);
 
         Assert.assertNotNull(entityItem.getPlanYaml());
-        Assert.assertTrue(entityItem.getPlanYaml().contains("org.apache.brooklyn.test.entity.TestEntity"));
+        Assert.assertTrue(entityItem.getPlanYaml().contains("org.apache.brooklyn.core.test.entity.TestEntity"));
 
         assertEquals(entityItem.getId(), ver(symbolicName));
         assertEquals(entityItem.getSymbolicName(), symbolicName);
@@ -121,7 +121,7 @@ public class CatalogResourceTest extends BrooklynRestResourceTest {
         assertEquals(entityItem.getName(), "My Catalog App");
         assertEquals(entityItem.getDescription(), "My description");
         assertEquals(entityItem.getIconUrl(), "/v1/catalog/icon/" + symbolicName + "/" + entityItem.getVersion());
-        assertEquals(item.getIconUrl(), "classpath:/brooklyn/osgi/tests/icon.gif");
+        assertEquals(item.getIconUrl(), "classpath:/org/apache/brooklyn/test/osgi/entities/icon.gif");
 
         byte[] iconData = client().resource("/v1/catalog/icon/" + symbolicName + "/" + TEST_VERSION).get(byte[].class);
         assertEquals(iconData.length, 43);
@@ -132,7 +132,7 @@ public class CatalogResourceTest extends BrooklynRestResourceTest {
         TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_PATH);
 
         String symbolicName = "my.catalog.policy.id";
-        String policyType = "brooklyn.osgi.tests.SimplePolicy";
+        String policyType = "org.apache.brooklyn.test.osgi.entities.SimplePolicy";
         String bundleUrl = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL;
 
         String yaml =
@@ -335,7 +335,7 @@ public class CatalogResourceTest extends BrooklynRestResourceTest {
                 "  version: " + TEST_VERSION + "\n"+
                 "\n"+
                 "services:\n"+
-                "- type: org.apache.brooklyn.test.entity.TestEntity\n";
+                "- type: org.apache.brooklyn.core.test.entity.TestEntity\n";
 
         client().resource("/v1/catalog")
                 .post(ClientResponse.class, yaml);
@@ -353,7 +353,7 @@ public class CatalogResourceTest extends BrooklynRestResourceTest {
     @Test
     public void testSetDeprecated() {
         String itemId = "my.catalog.item.id.for.deprecation";
-        String serviceType = "brooklyn.entity.basic.BasicApplication";
+        String serviceType = "org.apache.brooklyn.entity.stock.BasicApplication";
         addTestCatalogItem(itemId, "template", TEST_VERSION, serviceType);
         addTestCatalogItem(itemId, "template", "2.0", serviceType);
         List<CatalogEntitySummary> applications = client().resource("/v1/catalog/applications")
@@ -411,13 +411,13 @@ public class CatalogResourceTest extends BrooklynRestResourceTest {
                 "  id: " + symbolicName + "\n"+
                 "  name: My Catalog App\n"+
                 "  description: My description\n"+
-                "  icon_url: classpath:/brooklyn/osgi/tests/icon.gif\n"+
+                "  icon_url: classpath:/org/apache/brooklyn/test/osgi/entities/icon.gif\n"+
                 "  version: " + TEST_VERSION + "\n"+
                 "  libraries:\n"+
                 "  - url: " + bundleUrl + "\n"+
                 "\n"+
                 "services:\n"+
-                "- type: org.apache.brooklyn.test.entity.TestEntity\n";
+                "- type: org.apache.brooklyn.core.test.entity.TestEntity\n";
 
         ClientResponse response = client().resource("/v1/catalog")
                 .post(ClientResponse.class, yaml);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntity.java
----------------------------------------------------------------------
diff --git a/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntity.java b/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntity.java
index c5a7483..81c6966 100644
--- a/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntity.java
+++ b/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntity.java
@@ -18,7 +18,6 @@
  */
 package org.apache.brooklyn.test.osgi.entities.more;
 
-
 import org.apache.brooklyn.api.effector.Effector;
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.entity.ImplementedBy;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntityImpl.java
----------------------------------------------------------------------
diff --git a/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntityImpl.java b/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntityImpl.java
index 8c82acf..17919d4 100644
--- a/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntityImpl.java
+++ b/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntityImpl.java
@@ -22,7 +22,6 @@ import org.apache.brooklyn.effector.core.EffectorBody;
 import org.apache.brooklyn.entity.core.AbstractEntity;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 
-
 public class MoreEntityImpl extends AbstractEntity implements MoreEntity {
 
     @Override

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreLocation.java
----------------------------------------------------------------------
diff --git a/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreLocation.java b/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreLocation.java
index 14c884d..5ab0abf 100644
--- a/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreLocation.java
+++ b/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreLocation.java
@@ -18,7 +18,6 @@
  */
 package org.apache.brooklyn.test.osgi.entities.more;
 
-
 import org.apache.brooklyn.location.core.AbstractLocation;
 
 public class MoreLocation extends AbstractLocation {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MorePolicy.java
----------------------------------------------------------------------
diff --git a/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MorePolicy.java b/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MorePolicy.java
index 08c7441..84e5a63 100644
--- a/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MorePolicy.java
+++ b/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MorePolicy.java
@@ -18,8 +18,6 @@
  */
 package org.apache.brooklyn.test.osgi.entities.more;
 
-
-import org.apache.brooklyn.api.catalog.Catalog;
 import org.apache.brooklyn.policy.core.AbstractPolicy;
 
 public class MorePolicy extends AbstractPolicy {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreTemplate.java
----------------------------------------------------------------------
diff --git a/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreTemplate.java b/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreTemplate.java
index f27b79b..7e2aa08 100644
--- a/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreTemplate.java
+++ b/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreTemplate.java
@@ -18,12 +18,6 @@
  */
 package org.apache.brooklyn.test.osgi.entities.more;
 
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.entity.Application;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.effector.core.Effectors;
 import org.apache.brooklyn.entity.core.AbstractApplication;
 
 public class MoreTemplate extends AbstractApplication {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/utils/test-bundles/more-entities-v2-evil-twin/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntity.java
----------------------------------------------------------------------
diff --git a/utils/test-bundles/more-entities-v2-evil-twin/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntity.java b/utils/test-bundles/more-entities-v2-evil-twin/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntity.java
index cf8b58d..8a75e9a 100644
--- a/utils/test-bundles/more-entities-v2-evil-twin/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntity.java
+++ b/utils/test-bundles/more-entities-v2-evil-twin/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntity.java
@@ -18,10 +18,10 @@
  */
 package org.apache.brooklyn.test.osgi.entities.more;
 
-import org.apache.brooklyn.api.entity.Effector;
+import org.apache.brooklyn.api.effector.Effector;
 import org.apache.brooklyn.api.entity.Entity;
-import brooklyn.entity.effector.Effectors;
-import org.apache.brooklyn.api.entity.proxying.ImplementedBy;
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.effector.core.Effectors;
 
 @ImplementedBy(MoreEntityImpl.class)
 public interface MoreEntity extends Entity {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/utils/test-bundles/more-entities-v2-evil-twin/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntityImpl.java
----------------------------------------------------------------------
diff --git a/utils/test-bundles/more-entities-v2-evil-twin/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntityImpl.java b/utils/test-bundles/more-entities-v2-evil-twin/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntityImpl.java
index acf33d3..3ebe518 100644
--- a/utils/test-bundles/more-entities-v2-evil-twin/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntityImpl.java
+++ b/utils/test-bundles/more-entities-v2-evil-twin/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntityImpl.java
@@ -18,11 +18,10 @@
  */
 package org.apache.brooklyn.test.osgi.entities.more;
 
-import brooklyn.entity.basic.AbstractEntity;
-import brooklyn.entity.effector.EffectorBody;
 import org.apache.brooklyn.api.policy.PolicySpec;
-import org.apache.brooklyn.core.util.config.ConfigBag;
-
+import org.apache.brooklyn.effector.core.EffectorBody;
+import org.apache.brooklyn.entity.core.AbstractEntity;
+import org.apache.brooklyn.util.core.config.ConfigBag;
 
 public class MoreEntityImpl extends AbstractEntity implements MoreEntity {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntity.java
----------------------------------------------------------------------
diff --git a/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntity.java b/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntity.java
index 18a2b8f..edd650b 100644
--- a/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntity.java
+++ b/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntity.java
@@ -19,10 +19,10 @@
 package org.apache.brooklyn.test.osgi.entities.more;
 
 import org.apache.brooklyn.api.catalog.Catalog;
-import org.apache.brooklyn.api.entity.Effector;
+import org.apache.brooklyn.api.effector.Effector;
 import org.apache.brooklyn.api.entity.Entity;
-import brooklyn.entity.effector.Effectors;
-import org.apache.brooklyn.api.entity.proxying.ImplementedBy;
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.effector.core.Effectors;
 
 @Catalog(name="More Entity v2")
 @ImplementedBy(MoreEntityImpl.class)

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntityImpl.java
----------------------------------------------------------------------
diff --git a/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntityImpl.java b/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntityImpl.java
index 0f021b4..36b421f 100644
--- a/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntityImpl.java
+++ b/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreEntityImpl.java
@@ -18,11 +18,10 @@
  */
 package org.apache.brooklyn.test.osgi.entities.more;
 
-import brooklyn.entity.basic.AbstractEntity;
-import brooklyn.entity.effector.EffectorBody;
 import org.apache.brooklyn.api.policy.PolicySpec;
-import org.apache.brooklyn.core.util.config.ConfigBag;
-
+import org.apache.brooklyn.effector.core.EffectorBody;
+import org.apache.brooklyn.entity.core.AbstractEntity;
+import org.apache.brooklyn.util.core.config.ConfigBag;
 
 public class MoreEntityImpl extends AbstractEntity implements MoreEntity {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreLocation.java
----------------------------------------------------------------------
diff --git a/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreLocation.java b/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreLocation.java
index 34e8232..51de347 100644
--- a/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreLocation.java
+++ b/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreLocation.java
@@ -19,7 +19,7 @@
 package org.apache.brooklyn.test.osgi.entities.more;
 
 import org.apache.brooklyn.api.catalog.Catalog;
-import org.apache.brooklyn.location.basic.AbstractLocation;
+import org.apache.brooklyn.location.core.AbstractLocation;
 
 @Catalog(name="More Location", description="Cataliog item OSGi test location")
 public class MoreLocation extends AbstractLocation {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MorePolicy.java
----------------------------------------------------------------------
diff --git a/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MorePolicy.java b/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MorePolicy.java
index f1c6cb9..f7d7f2d 100644
--- a/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MorePolicy.java
+++ b/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MorePolicy.java
@@ -19,7 +19,7 @@
 package org.apache.brooklyn.test.osgi.entities.more;
 
 import org.apache.brooklyn.api.catalog.Catalog;
-import org.apache.brooklyn.core.policy.basic.AbstractPolicy;
+import org.apache.brooklyn.policy.core.AbstractPolicy;
 
 @Catalog(name="More Policy", description="Cataliog item OSGi test policy")
 public class MorePolicy extends AbstractPolicy {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/c45bab04/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreTemplate.java
----------------------------------------------------------------------
diff --git a/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreTemplate.java b/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreTemplate.java
index 0dfb0fd..03a7c1c 100644
--- a/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreTemplate.java
+++ b/utils/test-bundles/more-entities-v2/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreTemplate.java
@@ -19,12 +19,7 @@
 package org.apache.brooklyn.test.osgi.entities.more;
 
 import org.apache.brooklyn.api.catalog.Catalog;
-import org.apache.brooklyn.api.entity.Application;
-import org.apache.brooklyn.api.entity.Effector;
-import org.apache.brooklyn.api.entity.Entity;
-import brooklyn.entity.basic.AbstractApplication;
-import brooklyn.entity.effector.Effectors;
-import org.apache.brooklyn.api.entity.proxying.ImplementedBy;
+import org.apache.brooklyn.entity.core.AbstractApplication;
 
 @Catalog(name="More Template", description="Cataliog item OSGi test template")
 public class MoreTemplate extends AbstractApplication {


[22/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessSshDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessSshDriver.java
new file mode 100644
index 0000000..195e8f8
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessSshDriver.java
@@ -0,0 +1,657 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import static org.apache.brooklyn.util.JavaGroovyEquivalents.elvis;
+import static org.apache.brooklyn.util.JavaGroovyEquivalents.groovyTruth;
+
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.brooklyn.api.entity.drivers.downloads.DownloadResolver;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.core.BrooklynLogging;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
+import org.apache.brooklyn.effector.core.EffectorTasks;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.apache.brooklyn.entity.software.base.lifecycle.NaiveScriptRunner;
+import org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Predicates;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
+import org.apache.brooklyn.util.core.internal.ssh.SshTool;
+import org.apache.brooklyn.util.core.internal.ssh.sshj.SshjTool;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.guava.Maybe;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.ssh.BashCommands;
+import org.apache.brooklyn.util.stream.KnownSizeInputStream;
+import org.apache.brooklyn.util.stream.Streams;
+import org.apache.brooklyn.util.text.StringPredicates;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.time.Duration;
+
+/**
+ * An abstract SSH implementation of the {@link AbstractSoftwareProcessDriver}.
+ *
+ * This provides conveniences for clients implementing the install/customize/launch/isRunning/stop lifecycle
+ * over SSH.  These conveniences include checking whether software is already installed,
+ * creating/using a PID file for some operations, and reading ssh-specific config from the entity
+ * to override/augment ssh flags on the session.
+ */
+public abstract class AbstractSoftwareProcessSshDriver extends AbstractSoftwareProcessDriver implements NaiveScriptRunner {
+
+    public static final Logger log = LoggerFactory.getLogger(AbstractSoftwareProcessSshDriver.class);
+    public static final Logger logSsh = LoggerFactory.getLogger(BrooklynLogging.SSH_IO);
+
+    // we cache these for efficiency and in case the entity becomes unmanaged
+    private volatile String installDir;
+    private volatile String runDir;
+    private volatile String expandedInstallDir;
+    private final Object installDirSetupMutex = new Object();
+
+    protected volatile DownloadResolver resolver;
+
+    /** include this flag in newScript creation to prevent entity-level flags from being included;
+     * any SSH-specific flags passed to newScript override flags from the entity,
+     * and flags from the entity override flags on the location
+     * (where there aren't conflicts, flags from all three are used however) */
+    public static final String IGNORE_ENTITY_SSH_FLAGS = SshEffectorTasks.IGNORE_ENTITY_SSH_FLAGS.getName();
+
+    public AbstractSoftwareProcessSshDriver(EntityLocal entity, SshMachineLocation machine) {
+        super(entity, machine);
+
+        // FIXME this assumes we own the location, and causes warnings about configuring location after deployment;
+        // better would be to wrap the ssh-execution-provider to supply these flags
+        if (getSshFlags()!=null && !getSshFlags().isEmpty())
+            machine.configure(getSshFlags());
+
+        // ensure these are set using the routines below, not a global ConfigToAttributes.apply()
+        getInstallDir();
+        getRunDir();
+    }
+
+    /** returns location (tighten type, since we know it is an ssh machine location here) */
+    public SshMachineLocation getLocation() {
+        return (SshMachineLocation) super.getLocation();
+    }
+
+    protected void setInstallDir(String installDir) {
+        this.installDir = installDir;
+        entity.setAttribute(SoftwareProcess.INSTALL_DIR, installDir);
+    }
+
+    public String getInstallDir() {
+        if (installDir != null) return installDir;
+
+        String existingVal = getEntity().getAttribute(SoftwareProcess.INSTALL_DIR);
+        if (Strings.isNonBlank(existingVal)) { // e.g. on rebind
+            installDir = existingVal;
+            return installDir;
+        }
+
+        synchronized (installDirSetupMutex) {
+            // previously we looked at sensor value, but we shouldn't as it might have been converted from the config key value
+            // *before* we computed the install label, or that label may have changed since previous install; now force a recompute
+            setInstallLabel();
+
+            // deprecated in 0.7.0 - "brooklyn.dirs.install" is no longer supported
+            Maybe<Object> minstallDir = getEntity().getConfigRaw(SoftwareProcess.INSTALL_DIR, false);
+            if (!minstallDir.isPresent() || minstallDir.get()==null) {
+                String installBasedir = ((EntityInternal)entity).getManagementContext().getConfig().getFirst("brooklyn.dirs.install");
+                if (installBasedir != null) {
+                    log.warn("Using legacy 'brooklyn.dirs.install' setting for "+entity+"; may be removed in future versions.");
+                    setInstallDir(Os.tidyPath(Os.mergePathsUnix(installBasedir, getEntityVersionLabel()+"_"+entity.getId())));
+                    return installDir;
+                }
+            }
+
+            // set it null first so that we force a recompute
+            setInstallDir(null);
+            setInstallDir(Os.tidyPath(ConfigToAttributes.apply(getEntity(), SoftwareProcess.INSTALL_DIR)));
+            return installDir;
+        }
+    }
+
+    protected void setInstallLabel() {
+        if (getEntity().getConfigRaw(SoftwareProcess.INSTALL_UNIQUE_LABEL, false).isPresentAndNonNull()) return;
+        getEntity().setConfig(SoftwareProcess.INSTALL_UNIQUE_LABEL,
+            getEntity().getEntityType().getSimpleName()+
+            (Strings.isNonBlank(getVersion()) ? "_"+getVersion() : "")+
+            (Strings.isNonBlank(getInstallLabelExtraSalt()) ? "_"+getInstallLabelExtraSalt() : "") );
+    }
+
+    /** allows subclasses to return extra salt (ie unique hash)
+     * for cases where install dirs need to be distinct e.g. based on extra plugins being placed in the install dir;
+     * {@link #setInstallLabel()} uses entity-type simple name and version already
+     * <p>
+     * this salt should not be too long and must not contain invalid path chars.
+     * a hash code of other relevant info is not a bad choice.
+     **/
+    protected String getInstallLabelExtraSalt() {
+        return null;
+    }
+
+    protected void setRunDir(String runDir) {
+        this.runDir = runDir;
+        entity.setAttribute(SoftwareProcess.RUN_DIR, runDir);
+    }
+
+    public String getRunDir() {
+        if (runDir != null) return runDir;
+
+        String existingVal = getEntity().getAttribute(SoftwareProcess.RUN_DIR);
+        if (Strings.isNonBlank(existingVal)) { // e.g. on rebind
+            runDir = existingVal;
+            return runDir;
+        }
+
+        // deprecated in 0.7.0
+        Maybe<Object> mRunDir = getEntity().getConfigRaw(SoftwareProcess.RUN_DIR, true);
+        if (!mRunDir.isPresent() || mRunDir.get()==null) {
+            String runBasedir = ((EntityInternal)entity).getManagementContext().getConfig().getFirst("brooklyn.dirs.run");
+            if (runBasedir != null) {
+                log.warn("Using legacy 'brooklyn.dirs.run' setting for "+entity+"; may be removed in future versions.");
+                runDir = Os.mergePathsUnix(runBasedir, entity.getApplication().getId()+"/"+"entities"+"/"+getEntityVersionLabel()+"_"+entity.getId());
+                runDir = Os.tidyPath(runDir);
+                getEntity().setAttribute(SoftwareProcess.RUN_DIR, runDir);
+                return runDir;
+            }
+        }
+
+        setRunDir(Os.tidyPath(ConfigToAttributes.apply(getEntity(), SoftwareProcess.RUN_DIR)));
+        return runDir;
+    }
+
+    public void setExpandedInstallDir(String val) {
+        String oldVal = getEntity().getAttribute(SoftwareProcess.EXPANDED_INSTALL_DIR);
+        if (Strings.isNonBlank(oldVal) && !oldVal.equals(val)) {
+            log.info("Resetting expandedInstallDir (to "+val+" from "+oldVal+") for "+getEntity());
+        }
+
+        expandedInstallDir = val;
+        getEntity().setAttribute(SoftwareProcess.EXPANDED_INSTALL_DIR, val);
+    }
+
+    public String getExpandedInstallDir() {
+        if (expandedInstallDir != null) return expandedInstallDir;
+
+        String existingVal = getEntity().getAttribute(SoftwareProcess.EXPANDED_INSTALL_DIR);
+        if (Strings.isNonBlank(existingVal)) { // e.g. on rebind
+            expandedInstallDir = existingVal;
+            return expandedInstallDir;
+        }
+
+        String untidiedVal = ConfigToAttributes.apply(getEntity(), SoftwareProcess.EXPANDED_INSTALL_DIR);
+        if (Strings.isNonBlank(untidiedVal)) {
+            setExpandedInstallDir(Os.tidyPath(untidiedVal));
+            return expandedInstallDir;
+        } else {
+            throw new IllegalStateException("expandedInstallDir is null; most likely install was not called for "+getEntity());
+        }
+    }
+
+    public SshMachineLocation getMachine() { return getLocation(); }
+    public String getHostname() { return entity.getAttribute(Attributes.HOSTNAME); }
+    public String getAddress() { return entity.getAttribute(Attributes.ADDRESS); }
+    public String getSubnetHostname() { return entity.getAttribute(Attributes.SUBNET_HOSTNAME); }
+    public String getSubnetAddress() { return entity.getAttribute(Attributes.SUBNET_ADDRESS); }
+
+    protected Map<String, Object> getSshFlags() {
+        return SshEffectorTasks.getSshFlags(getEntity(), getMachine());
+    }
+
+    public int execute(String command, String summaryForLogging) {
+        return execute(ImmutableList.of(command), summaryForLogging);
+    }
+
+    public int execute(List<String> script, String summaryForLogging) {
+        return execute(Maps.newLinkedHashMap(), script, summaryForLogging);
+    }
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @Override
+    public int execute(Map flags2, List<String> script, String summaryForLogging) {
+        // TODO replace with SshEffectorTasks.ssh ?; remove the use of flags
+
+        Map flags = Maps.newLinkedHashMap();
+        if (!flags2.containsKey(IGNORE_ENTITY_SSH_FLAGS)) {
+            flags.putAll(getSshFlags());
+        }
+        flags.putAll(flags2);
+        Map<String, String> environment = (Map<String, String>) flags.get("env");
+        if (environment == null) {
+            // Important only to call getShellEnvironment() if env was not supplied; otherwise it
+            // could cause us to resolve config (e.g. block for attributeWhenReady) too early.
+            environment = getShellEnvironment();
+        }
+        if (Tasks.current()!=null) {
+            // attach tags here, as well as in ScriptHelper, because they may have just been read from the driver
+            if (environment!=null) {
+                Tasks.addTagDynamically(BrooklynTaskTags.tagForEnvStream(BrooklynTaskTags.STREAM_ENV, environment));
+            }
+            if (BrooklynTaskTags.stream(Tasks.current(), BrooklynTaskTags.STREAM_STDIN)==null) {
+                Tasks.addTagDynamically(BrooklynTaskTags.tagForStreamSoft(BrooklynTaskTags.STREAM_STDIN,
+                    Streams.byteArrayOfString(Strings.join(script, "\n"))));
+            }
+            if (BrooklynTaskTags.stream(Tasks.current(), BrooklynTaskTags.STREAM_STDOUT)==null) {
+                ByteArrayOutputStream stdout = new ByteArrayOutputStream();
+                Tasks.addTagDynamically(BrooklynTaskTags.tagForStreamSoft(BrooklynTaskTags.STREAM_STDOUT, stdout));
+                ByteArrayOutputStream stderr = new ByteArrayOutputStream();
+                Tasks.addTagDynamically(BrooklynTaskTags.tagForStreamSoft(BrooklynTaskTags.STREAM_STDERR, stderr));
+                flags.put("out", stdout);
+                flags.put("err", stderr);
+            }
+        }
+        if (!flags.containsKey("logPrefix")) flags.put("logPrefix", ""+entity.getId()+"@"+getLocation().getDisplayName());
+        return getMachine().execScript(flags, summaryForLogging, script, environment);
+    }
+
+    @Override
+    public void copyInstallResources() {
+        getLocation().acquireMutex("installing " + elvis(entity, this), "installation lock at host for files and templates");
+        try {
+            super.copyInstallResources();
+        } catch (Exception e) {
+            log.warn("Error copying install resources", e);
+            throw Exceptions.propagate(e);
+        } finally {
+            getLocation().releaseMutex("installing " + elvis(entity, this));
+        }
+    }
+
+    @Override
+    public void runPreInstallCommand(String command) {
+        execute(ImmutableList.of(command), "running pre-install commands");
+    }
+
+    @Override
+    public void runPostInstallCommand(String command) {
+        execute(ImmutableList.of(command), "running post-install commands");
+    }
+
+    @Override
+    public void runPreLaunchCommand(String command) {
+        execute(ImmutableList.of(command), "running pre-launch commands");
+    }
+
+    @Override
+    public void runPostLaunchCommand(String command) {
+        execute(ImmutableList.of(command), "running post-launch commands");
+    }
+
+    /**
+     * The environment variables to be set when executing the commands (for install, run, check running, etc).
+     * @see SoftwareProcess#SHELL_ENVIRONMENT
+     */
+    public Map<String, String> getShellEnvironment() {
+        return Strings.toStringMap(entity.getConfig(SoftwareProcess.SHELL_ENVIRONMENT), "");
+    }
+
+
+    /**
+     * @param sshFlags Extra flags to be used when making an SSH connection to the entity's machine.
+     *                 If the map contains the key {@link #IGNORE_ENTITY_SSH_FLAGS} then only the
+     *                 given flags are used. Otherwise, the given flags are combined with (and take
+     *                 precendence over) the flags returned by {@link #getSshFlags()}.
+     * @param source URI of file to copy, e.g. file://.., http://.., classpath://..
+     * @param target Destination on server, relative to {@link #getRunDir()} if not absolute path
+     * @param createParentDir Whether to create the parent target directory, if it doesn't already exist
+     * @return The exit code of the SSH command run
+     */
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    public int copyResource(Map<Object,Object> sshFlags, String source, String target, boolean createParentDir) {
+        // TODO use SshTasks.put instead, better logging
+        Map flags = Maps.newLinkedHashMap();
+        if (!sshFlags.containsKey(IGNORE_ENTITY_SSH_FLAGS)) {
+            flags.putAll(getSshFlags());
+        }
+        flags.putAll(sshFlags);
+
+        String destination = Os.isAbsolutish(target) ? target : Os.mergePathsUnix(getRunDir(), target);
+
+        if (createParentDir) {
+            // don't use File.separator because it's remote machine's format, rather than local machine's
+            int lastSlashIndex = destination.lastIndexOf("/");
+            String parent = (lastSlashIndex > 0) ? destination.substring(0, lastSlashIndex) : null;
+            if (parent != null) {
+                getMachine().execCommands("createParentDir", ImmutableList.of("mkdir -p "+parent));
+            }
+        }
+
+        int result = getMachine().installTo(resource, flags, source, destination);
+        if (result == 0) {
+            if (log.isDebugEnabled()) {
+                log.debug("Copied file for {}: {} to {} - result {}", new Object[] { entity, source, destination, result });
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Input stream will be closed automatically.
+     * <p>
+     * If using {@link SshjTool} usage, consider using {@link KnownSizeInputStream} to avoid having
+     * to write out stream once to find its size!
+     *
+     * @see #copyResource(Map, String, String) for parameter descriptions.
+     */
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    public int copyResource(Map<Object,Object> sshFlags, InputStream source, String target, boolean createParentDir) {
+        Map flags = Maps.newLinkedHashMap();
+        if (!sshFlags.containsKey(IGNORE_ENTITY_SSH_FLAGS)) {
+            flags.putAll(getSshFlags());
+        }
+        flags.putAll(sshFlags);
+
+        String destination = Os.isAbsolutish(target) ? target : Os.mergePathsUnix(getRunDir(), target);
+
+        if (createParentDir) {
+            // don't use File.separator because it's remote machine's format, rather than local machine's
+            int lastSlashIndex = destination.lastIndexOf("/");
+            String parent = (lastSlashIndex > 0) ? destination.substring(0, lastSlashIndex) : null;
+            if (parent != null) {
+                getMachine().execCommands("createParentDir", ImmutableList.of("mkdir -p "+parent));
+            }
+        }
+
+        // TODO SshMachineLocation.copyTo currently doesn't log warn on non-zero or set blocking details
+        // (because delegated to by installTo, for multiple calls). So do it here for now.
+        int result;
+        String prevBlockingDetails = Tasks.setBlockingDetails("copying resource to server at "+destination);
+        try {
+            result = getMachine().copyTo(flags, source, destination);
+        } finally {
+            Tasks.setBlockingDetails(prevBlockingDetails);
+        }
+
+        if (result == 0) {
+            log.debug("copying stream complete; {} on {}", new Object[] { destination, getMachine() });
+        } else {
+            log.warn("copying stream failed; {} on {}: {}", new Object[] { destination, getMachine(), result });
+        }
+        return result;
+    }
+
+    public void checkNoHostnameBug() {
+        try {
+            ProcessTaskWrapper<Integer> hostnameTask = DynamicTasks.queue(SshEffectorTasks.ssh("echo FOREMARKER; hostname; echo AFTMARKER")).block();
+            String stdout = Strings.getFragmentBetween(hostnameTask.getStdout(), "FOREMARKER", "AFTMARKER");
+            if (hostnameTask.getExitCode() == 0 && Strings.isNonBlank(stdout)) {
+                String hostname = stdout.trim();
+                if (hostname.equals("(none)")) {
+                    String newHostname = "br-"+getEntity().getId().toLowerCase();
+                    log.info("Detected no-hostname bug with hostname "+hostname+" for "+getEntity()+"; renaming "+getMachine()+"  to hostname "+newHostname);
+                    DynamicTasks.queue(SshEffectorTasks.ssh(BashCommands.setHostname(newHostname, null))).block();
+                }
+            } else {
+                log.debug("Hostname could not be determined for location "+EffectorTasks.findSshMachine()+"; not doing no-hostname bug check");
+            }
+        } catch (Exception e) {
+            Exceptions.propagateIfFatal(e);
+            log.warn("Error checking/fixing no-hostname bug (continuing): "+e, e);
+        }
+    }
+
+    public static final String INSTALLING = "installing";
+    public static final String CUSTOMIZING = "customizing";
+    public static final String LAUNCHING = "launching";
+    public static final String CHECK_RUNNING = "check-running";
+    public static final String STOPPING = "stopping";
+    public static final String KILLING = "killing";
+    public static final String RESTARTING = "restarting";
+
+    public static final String PID_FILENAME = "pid.txt";
+
+    /* Flags */
+
+    /**
+     * Use a PID file, created by <em>launching</em>, and reading it for <em>check-running</em>,
+     * <em>stopping</em> and <em>killing</em>. The value can be <em>true</em> or a path to a file to
+     * use; either relative to <em>RUN_DIR</em> or an absolute path.
+     */
+    public static final String USE_PID_FILE = "usePidFile";
+
+    /**
+     * Define the process owner if not the same as the brooklyn user. Both <em>stopping</em> and
+     * <em>killing</em> will sudo to this user before issuing the <code>kill</code> command. Only valid
+     * if <em>USE_PID_FILE</em> is also set.
+     */
+    public static final String PROCESS_OWNER = "processOwner";
+
+    /**
+     * Marks the script as having a customised setup, to prevent the default headers and footers being
+     * added to the list of commands.
+     */
+    public static final String NON_STANDARD_LAYOUT = "nonStandardLayout";
+
+    /**
+     * Prevents creation of the <code>$INSTALL_DIR/BROOKLYN</code> marker file after <em>installing</em>
+     * phase finishes, to allow further installation phases to execute.
+     */
+    public static final String INSTALL_INCOMPLETE = "installIncomplete";
+
+    /**
+     * Enable shell debugging output via <code>set -x</code> prepended to the command header.
+     */
+    public static final String DEBUG = "debug";
+
+    /** Permitted flags for {@link #newScript(Map, String)}. */
+    public static final List<String> VALID_FLAGS =
+            ImmutableList.of(USE_PID_FILE, PROCESS_OWNER, NON_STANDARD_LAYOUT, INSTALL_INCOMPLETE, DEBUG);
+
+    /** @see #newScript(Map, String) */
+    protected ScriptHelper newScript(String phase) {
+        return newScript(Maps.<String, Object>newLinkedHashMap(), phase);
+    }
+
+    /**
+     * Sets up a {@link ScriptHelper} to generate a script that controls the given phase
+     * (<em>check-running</em>, <em>launching</em> etc.) including default header and
+     * footer commands.
+     * <p>
+     * Supported flags:
+     * <ul>
+     * <li><strong>usePidFile</strong> - <em>true</em> or <em>filename</em> to save and retrieve the PID
+     * <li><strong>processOwner</strong> - <em>username</em> that owns the running process
+     * <li><strong>nonStandardLayout</strong> - <em>true</em> to omit all default commands
+     * <li><strong>installIncomplete</strong> - <em>true</em> to prevent marking complete
+     * <li><strong>debug</strong> - <em>true</em> to enable shell debug output
+     * </li>
+     *
+     * @param flags a {@link Map} of flags to control script generation
+     * @param phase the phase to create the ScriptHelper for
+     *
+     * @see #newScript(String)
+     * @see #USE_PID_FILE
+     * @see #PROCESS_OWNER
+     * @see #NON_STANDARD_LAYOUT
+     * @see #INSTALL_INCOMPLETE
+     * @see #DEBUG
+     */
+    protected ScriptHelper newScript(Map<String, ?> flags, String phase) {
+        if (!Entities.isManaged(getEntity()))
+            throw new IllegalStateException(getEntity()+" is no longer managed; cannot create script to run here ("+phase+")");
+
+        if (!Iterables.all(flags.keySet(), StringPredicates.equalToAny(VALID_FLAGS))) {
+            throw new IllegalArgumentException("Invalid flags passed: " + flags);
+        }
+
+        ScriptHelper s = new ScriptHelper(this, phase+" "+elvis(entity,this));
+        if (!groovyTruth(flags.get(NON_STANDARD_LAYOUT))) {
+            if (groovyTruth(flags.get(DEBUG))) {
+                s.header.prepend("set -x");
+            }
+            if (INSTALLING.equals(phase)) {
+                // mutexId should be global because otherwise package managers will contend with each other
+                s.useMutex(getLocation(), "installation lock at host", "installing "+elvis(entity,this));
+                s.header.append(
+                        "export INSTALL_DIR=\""+getInstallDir()+"\"",
+                        "mkdir -p $INSTALL_DIR",
+                        "cd $INSTALL_DIR",
+                        "test -f BROOKLYN && exit 0"
+                        );
+
+                if (!groovyTruth(flags.get(INSTALL_INCOMPLETE))) {
+                    s.footer.append("date > $INSTALL_DIR/BROOKLYN");
+                }
+                // don't set vars during install phase, prevent dependency resolution
+                s.environmentVariablesReset();
+            }
+            if (ImmutableSet.of(CUSTOMIZING, LAUNCHING, CHECK_RUNNING, STOPPING, KILLING, RESTARTING).contains(phase)) {
+                s.header.append(
+                        "export RUN_DIR=\""+getRunDir()+"\"",
+                        "mkdir -p $RUN_DIR",
+                        "cd $RUN_DIR"
+                        );
+            }
+        }
+
+        if (ImmutableSet.of(LAUNCHING, RESTARTING).contains(phase)) {
+            s.failIfBodyEmpty();
+        }
+        if (ImmutableSet.of(STOPPING, KILLING).contains(phase)) {
+            // stopping and killing allowed to have empty body if pid file set
+            if (!groovyTruth(flags.get(USE_PID_FILE)))
+                s.failIfBodyEmpty();
+        }
+        if (ImmutableSet.of(INSTALLING, LAUNCHING).contains(phase)) {
+            s.updateTaskAndFailOnNonZeroResultCode();
+        }
+        if (phase.equalsIgnoreCase(CHECK_RUNNING)) {
+            s.setInessential();
+            s.setTransient();
+            s.setFlag(SshTool.PROP_CONNECT_TIMEOUT, Duration.TEN_SECONDS.toMilliseconds());
+            s.setFlag(SshTool.PROP_SESSION_TIMEOUT, Duration.THIRTY_SECONDS.toMilliseconds());
+            s.setFlag(SshTool.PROP_SSH_TRIES, 1);
+        }
+
+        if (groovyTruth(flags.get(USE_PID_FILE))) {
+            Object usePidFile = flags.get(USE_PID_FILE);
+            String pidFile = (usePidFile instanceof CharSequence ? usePidFile : Os.mergePathsUnix(getRunDir(), PID_FILENAME)).toString();
+            String processOwner = (String) flags.get(PROCESS_OWNER);
+            if (LAUNCHING.equals(phase)) {
+                entity.setAttribute(SoftwareProcess.PID_FILE, pidFile);
+                s.footer.prepend("echo $! > "+pidFile);
+            } else if (CHECK_RUNNING.equals(phase)) {
+                // old method, for supplied service, or entity.id
+                // "ps aux | grep ${service} | grep \$(cat ${pidFile}) > /dev/null"
+                // new way, preferred?
+                if (processOwner != null) {
+                    s.body.append(
+                            BashCommands.sudoAsUser(processOwner, "test -f "+pidFile) + " || exit 1",
+                            "ps -p $(" + BashCommands.sudoAsUser(processOwner, "cat "+pidFile) + ")"
+                    );
+                } else {
+                    s.body.append(
+                            "test -f "+pidFile+" || exit 1",
+                            "ps -p `cat "+pidFile+"`"
+                    );
+                }
+                // no pid, not running; 1 is not running
+                s.requireResultCode(Predicates.or(Predicates.equalTo(0), Predicates.equalTo(1)));
+            } else if (STOPPING.equals(phase)) {
+                if (processOwner != null) {
+                    s.body.append(
+                            "export PID=$(" + BashCommands.sudoAsUser(processOwner, "cat "+pidFile) + ")",
+                            "test -n \"$PID\" || exit 0",
+                            BashCommands.sudoAsUser(processOwner, "kill $PID"),
+                            BashCommands.sudoAsUser(processOwner, "kill -9 $PID"),
+                            BashCommands.sudoAsUser(processOwner, "rm -f "+pidFile)
+                    );
+                } else {
+                    s.body.append(
+                            "export PID=$(cat "+pidFile+")",
+                            "test -n \"$PID\" || exit 0",
+                            "kill $PID",
+                            "kill -9 $PID",
+                            "rm -f "+pidFile
+                    );
+                }
+            } else if (KILLING.equals(phase)) {
+                if (processOwner != null) {
+                    s.body.append(
+                            "export PID=$(" + BashCommands.sudoAsUser(processOwner, "cat "+pidFile) + ")",
+                            "test -n \"$PID\" || exit 0",
+                            BashCommands.sudoAsUser(processOwner, "kill -9 $PID"),
+                            BashCommands.sudoAsUser(processOwner, "rm -f "+pidFile)
+                    );
+                } else {
+                    s.body.append(
+                            "export PID=$(cat "+pidFile+")",
+                            "test -n \"$PID\" || exit 0",
+                            "kill -9 $PID",
+                            "rm -f "+pidFile
+                    );
+                }
+            } else if (RESTARTING.equals(phase)) {
+                if (processOwner != null) {
+                    s.footer.prepend(
+                            BashCommands.sudoAsUser(processOwner, "test -f "+pidFile) + " || exit 1",
+                            "ps -p $(" + BashCommands.sudoAsUser(processOwner, "cat "+pidFile) + ") || exit 1"
+                    );
+                } else {
+                    s.footer.prepend(
+                            "test -f "+pidFile+" || exit 1",
+                            "ps -p $(cat "+pidFile+") || exit 1"
+                    );
+                }
+                // no pid, not running; no process; can't restart, 1 is not running
+            } else {
+                log.warn(USE_PID_FILE + ": script option not valid for " + s.summary);
+            }
+        }
+
+        return s;
+    }
+
+    @Override
+    protected void createDirectory(String directoryName, String summaryForLogging) {
+        DynamicTasks.queue(SshEffectorTasks.ssh("mkdir -p " + directoryName).summary(summaryForLogging)
+                .requiringExitCodeZero()).get();
+    }
+
+    public Set<Integer> getPortsUsed() {
+        Set<Integer> result = Sets.newLinkedHashSet();
+        result.add(22);
+        return result;
+    }
+
+    @Override
+    public void setup() { }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessWinRmDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessWinRmDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessWinRmDriver.java
new file mode 100644
index 0000000..42d0d45
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessWinRmDriver.java
@@ -0,0 +1,193 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import java.io.File;
+import java.io.InputStream;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.config.ConfigKey;
+import org.python.core.PyException;
+import org.apache.brooklyn.location.basic.WinRmMachineLocation;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.util.exceptions.ReferenceWithError;
+import org.apache.brooklyn.util.repeat.Repeater;
+import org.apache.brooklyn.util.time.Duration;
+
+import io.cloudsoft.winrm4j.winrm.WinRmToolResponse;
+
+import com.google.api.client.util.Strings;
+import com.google.common.collect.ImmutableList;
+
+public abstract class AbstractSoftwareProcessWinRmDriver extends AbstractSoftwareProcessDriver {
+
+    AttributeSensor<String> WINDOWS_USERNAME = Sensors.newStringSensor("windows.username",
+            "Default Windows username to be used when connecting to the Entity's VM");
+    AttributeSensor<String> WINDOWS_PASSWORD = Sensors.newStringSensor("windows.password",
+            "Default Windows password to be used when connecting to the Entity's VM");
+
+    public AbstractSoftwareProcessWinRmDriver(EntityLocal entity, WinRmMachineLocation location) {
+        super(entity, location);
+        entity.setAttribute(WINDOWS_USERNAME, location.config().get(WinRmMachineLocation.USER));
+        entity.setAttribute(WINDOWS_PASSWORD, location.config().get(WinRmMachineLocation.PASSWORD));
+    }
+
+    @Override
+    public void runPreInstallCommand(String command) {
+        execute(ImmutableList.of(command));
+    }
+
+    @Override
+    public void setup() {
+        // Default to no-op
+    }
+
+    @Override
+    public void runPostInstallCommand(String command) {
+        execute(ImmutableList.of(command));
+    }
+
+    @Override
+    public void runPreLaunchCommand(String command) {
+        execute(ImmutableList.of(command));
+    }
+
+    @Override
+    public void runPostLaunchCommand(String command) {
+        execute(ImmutableList.of(command));
+    }
+
+    @Override
+    public WinRmMachineLocation getLocation() {
+        return (WinRmMachineLocation)super.getLocation();
+    }
+
+    @Override
+    public String getRunDir() {
+        // TODO: This needs to be tidied, and read from the appropriate flags (if set)
+        return "$HOME\\brooklyn-managed-processes\\apps\\" + entity.getApplicationId() + "\\entities\\" + getEntityVersionLabel()+"_"+entity.getId();
+    }
+
+    @Override
+    public String getInstallDir() {
+        // TODO: This needs to be tidied, and read from the appropriate flags (if set)
+        return "$HOME\\brooklyn-managed-processes\\installs\\" + entity.getApplicationId() + "\\" + getEntityVersionLabel()+"_"+entity.getId();
+    }
+
+    @Override
+    public int copyResource(Map<Object, Object> sshFlags, String source, String target, boolean createParentDir) {
+        if (createParentDir) {
+            createDirectory(getDirectory(target), "Creating resource directory");
+        }
+        return copyTo(new File(source), target);
+    }
+
+    @Override
+    public int copyResource(Map<Object, Object> sshFlags, InputStream source, String target, boolean createParentDir) {
+        if (createParentDir) {
+            createDirectory(getDirectory(target), "Creating resource directory");
+        }
+        return copyTo(source, target);
+    }
+
+    @Override
+    protected void createDirectory(String directoryName, String summaryForLogging) {
+        getLocation().executePsScript("New-Item -path \"" + directoryName + "\" -type directory -ErrorAction SilentlyContinue");
+    }
+
+    protected WinRmToolResponse executeCommand(ConfigKey<String> regularCommandKey, ConfigKey<String> powershellCommandKey, boolean allowNoOp) {
+        String regularCommand = getEntity().getConfig(regularCommandKey);
+        String powershellCommand = getEntity().getConfig(powershellCommandKey);
+        if (Strings.isNullOrEmpty(regularCommand) && Strings.isNullOrEmpty(powershellCommand)) {
+            if (allowNoOp) {
+                return new WinRmToolResponse("", "", 0);
+            } else {
+                throw new IllegalStateException(String.format("Exactly one of %s or %s must be set", regularCommandKey.getName(), powershellCommandKey.getName()));
+            }
+        } else if (!Strings.isNullOrEmpty(regularCommand) && !Strings.isNullOrEmpty(powershellCommand)) {
+            throw new IllegalStateException(String.format("%s and %s cannot both be set", regularCommandKey.getName(), powershellCommandKey.getName()));
+        }
+
+        if (Strings.isNullOrEmpty(regularCommand)) {
+            return getLocation().executePsScript(ImmutableList.of(powershellCommand));
+        } else {
+            return getLocation().executeScript(ImmutableList.of(regularCommand));
+        }
+    }
+
+    public int execute(List<String> script) {
+        return getLocation().executeScript(script).getStatusCode();
+    }
+
+    public int executePsScriptNoRetry(List<String> psScript) {
+        return getLocation().executePsScriptNoRetry(psScript).getStatusCode();
+    }
+
+    public int executePsScript(List<String> psScript) {
+        return getLocation().executePsScript(psScript).getStatusCode();
+    }
+
+    public int copyTo(File source, String destination) {
+        return getLocation().copyTo(source, destination);
+    }
+
+    public int copyTo(InputStream source, String destination) {
+        return getLocation().copyTo(source, destination);
+    }
+
+    public void rebootAndWait() {
+        try {
+            executePsScriptNoRetry(ImmutableList.of("Restart-Computer -Force"));
+        } catch (PyException e) {
+            // Restarting the computer will cause the command to fail; ignore the exception and continue
+        }
+        waitForWinRmStatus(false, entity.getConfig(VanillaWindowsProcess.REBOOT_BEGUN_TIMEOUT));
+        waitForWinRmStatus(true, entity.getConfig(VanillaWindowsProcess.REBOOT_COMPLETED_TIMEOUT)).getWithError();
+    }
+
+    private String getDirectory(String fileName) {
+        return fileName.substring(0, fileName.lastIndexOf("\\"));
+    }
+
+    private ReferenceWithError<Boolean> waitForWinRmStatus(final boolean requiredStatus, Duration timeout) {
+        // TODO: Reduce / remove duplication between this and JcloudsLocation.waitForWinRmAvailable
+        Callable<Boolean> checker = new Callable<Boolean>() {
+            @Override
+            public Boolean call() throws Exception {
+                try {
+                    return (execute(ImmutableList.of("hostname")) == 0) == requiredStatus;
+                } catch (Exception e) {
+                    return !requiredStatus;
+                }
+            }
+        };
+
+        return new Repeater()
+                .every(1, TimeUnit.SECONDS)
+                .until(checker)
+                .limitTimeTo(timeout)
+                .runKeepingError();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractVanillaProcess.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractVanillaProcess.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractVanillaProcess.java
new file mode 100644
index 0000000..ef9c9c4
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractVanillaProcess.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.sensor.core.AttributeSensorAndConfigKey;
+
+public interface AbstractVanillaProcess extends SoftwareProcess {
+    AttributeSensorAndConfigKey<String, String> DOWNLOAD_URL = SoftwareProcess.DOWNLOAD_URL;
+
+    ConfigKey<String> SUGGESTED_VERSION = ConfigKeys.newConfigKeyWithDefault(SoftwareProcess.SUGGESTED_VERSION, "0.0.0");
+    
+    ConfigKey<String> INSTALL_COMMAND = ConfigKeys.newStringConfigKey("install.command", "command to run during the install phase");
+    ConfigKey<String> CUSTOMIZE_COMMAND = ConfigKeys.newStringConfigKey("customize.command", "command to run during the customization phase");
+    ConfigKey<String> LAUNCH_COMMAND = ConfigKeys.newStringConfigKey("launch.command", "command to run to launch the process");
+    ConfigKey<String> CHECK_RUNNING_COMMAND = ConfigKeys.newStringConfigKey("checkRunning.command", "command to determine whether the process is running");
+    ConfigKey<String> STOP_COMMAND = ConfigKeys.newStringConfigKey("stop.command", "command to run to stop the process");
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcess.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcess.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcess.java
new file mode 100644
index 0000000..98a97c0
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcess.java
@@ -0,0 +1,28 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import org.apache.brooklyn.api.entity.ImplementedBy;
+
+@ImplementedBy(EmptySoftwareProcessImpl.class)
+public interface EmptySoftwareProcess extends SoftwareProcess {
+
+    public SoftwareProcessDriver getDriver();
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessDriver.java
new file mode 100644
index 0000000..e5a9d10
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessDriver.java
@@ -0,0 +1,22 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+public interface EmptySoftwareProcessDriver extends SoftwareProcessDriver {
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessImpl.java
new file mode 100644
index 0000000..154a08a
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessImpl.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+public class EmptySoftwareProcessImpl extends SoftwareProcessImpl implements EmptySoftwareProcess {
+
+    @Override
+    public Class<?> getDriverInterface() {
+        return EmptySoftwareProcessDriver.class;
+    }
+
+    @Override
+    protected void connectSensors() {
+        super.connectSensors();
+        connectServiceUpIsRunning();
+    }
+
+    @Override
+    protected void disconnectSensors() {
+        disconnectServiceUpIsRunning();
+        super.disconnectSensors();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessSshDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessSshDriver.java
new file mode 100644
index 0000000..4ddf540
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/EmptySoftwareProcessSshDriver.java
@@ -0,0 +1,83 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+
+public class EmptySoftwareProcessSshDriver extends AbstractSoftwareProcessSshDriver implements EmptySoftwareProcessDriver {
+
+    private final AtomicBoolean running = new AtomicBoolean();
+
+    public EmptySoftwareProcessSshDriver(EmptySoftwareProcessImpl entity, SshMachineLocation machine) {
+        super(entity, machine);
+    }
+
+    @Override
+    public boolean isRunning() {
+        return running.get();
+    }
+
+    @Override
+    public void install() { }
+
+    @Override
+    public void customize() { }
+
+    @Override
+    public void copyInstallResources() { 
+        Map<String, String> installFiles = entity.getConfig(SoftwareProcess.INSTALL_FILES);
+        Map<String, String> installTemplates = entity.getConfig(SoftwareProcess.INSTALL_TEMPLATES);
+        if ((installFiles!=null && !installFiles.isEmpty()) || (installTemplates!=null && !installTemplates.isEmpty())) {
+            // only do this if there are files, to prevent unnecessary `mkdir`
+            super.copyInstallResources();
+        }
+    }
+
+    @Override
+    public void copyRuntimeResources() { 
+        Map<String, String> runtimeFiles = entity.getConfig(SoftwareProcess.RUNTIME_FILES);
+        Map<String, String> runtimeTemplates = entity.getConfig(SoftwareProcess.RUNTIME_TEMPLATES);
+        if ((runtimeFiles!=null && !runtimeFiles.isEmpty()) || (runtimeTemplates!=null && !runtimeTemplates.isEmpty())) {
+            // only do this if there are files, to prevent unnecessary `mkdir`
+            super.copyRuntimeResources();
+        }        
+    }
+
+    @Override
+    public void launch() {
+        running.set(true);
+    }
+
+    @Override
+    public void rebind() {
+        super.rebind();
+        /* TODO not necessarily, but there is not yet an easy way to persist state without 
+         * using config/sensors which we might not want do. */
+        running.set(true);
+    }
+
+    @Override
+    public void stop() {
+        running.set(false);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerDriverLifecycleEffectorTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerDriverLifecycleEffectorTasks.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerDriverLifecycleEffectorTasks.java
new file mode 100644
index 0000000..7f605e5
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerDriverLifecycleEffectorTasks.java
@@ -0,0 +1,170 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.location.PortRange;
+import org.apache.brooklyn.api.mgmt.TaskAdaptable;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.entity.core.AbstractEntity;
+import org.apache.brooklyn.entity.software.base.lifecycle.MachineLifecycleEffectorTasks;
+import org.apache.brooklyn.entity.trait.StartableMethods;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Supplier;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import com.google.common.reflect.TypeToken;
+
+import org.apache.brooklyn.location.basic.LocationConfigKeys;
+import org.apache.brooklyn.util.collections.MutableSet;
+import org.apache.brooklyn.util.core.flags.TypeCoercions;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.guava.Maybe;
+
+public class SameServerDriverLifecycleEffectorTasks extends MachineLifecycleEffectorTasks {
+
+    private static final Logger LOG = LoggerFactory.getLogger(SameServerDriverLifecycleEffectorTasks.class);
+
+    @Override
+    protected SameServerEntityImpl entity() {
+        return (SameServerEntityImpl) super.entity();
+    }
+
+    /**
+     * @return the ports that this entity wants to use, aggregated for all its child entities.
+     */
+    protected Collection<Integer> getRequiredOpenPorts() {
+        Set<Integer> result = Sets.newLinkedHashSet();
+        result.addAll(getRequiredOpenPorts(entity()));
+        LOG.debug("getRequiredOpenPorts detected aggregated default {} for {}", result, this);
+        return result;
+    }
+
+    /** @return the ports required for a specific child entity */
+    protected Collection<Integer> getRequiredOpenPorts(Entity entity) {
+        Set<Integer> ports = MutableSet.of(22);
+        /* TODO: This won't work if there's a port collision, which will cause the corresponding port attribute
+           to be incremented until a free port is found. In that case the entity will use the free port, but the
+           firewall will open the initial port instead. Mostly a problem for SameServerEntity, localhost location.
+        */
+        // TODO: Remove duplication between this and SoftwareProcessImpl.getRequiredOpenPorts
+        for (ConfigKey<?> k: entity.getEntityType().getConfigKeys()) {
+            Object value;
+            if (PortRange.class.isAssignableFrom(k.getType()) || k.getName().matches(".*\\.port")) {
+                value = entity.config().get(k);
+            } else {
+                // config().get() will cause this to block until all config has been resolved
+                // using config().getRaw(k) means that we won't be able to use e.g. 'http.port: $brooklyn:component("x").attributeWhenReady("foo")'
+                // but that's unlikely to be used
+                Maybe<Object> maybeValue = ((AbstractEntity.BasicConfigurationSupport)entity.config()).getRaw(k);
+                value = maybeValue.isPresent() ? maybeValue.get() : null;
+            }
+
+            Maybe<PortRange> maybePortRange = TypeCoercions.tryCoerce(value, TypeToken.of(PortRange.class));
+
+            if (maybePortRange.isPresentAndNonNull()) {
+                PortRange p = maybePortRange.get();
+                if (p != null && !p.isEmpty()) ports.add(p.iterator().next());
+            }
+        }
+        LOG.debug("getRequiredOpenPorts detected default {} for {}", ports, entity);
+
+        for (Entity child : entity.getChildren()) {
+            ports.addAll(getRequiredOpenPorts(child));
+        }
+        return ports;
+    }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    protected Map<String, Object> obtainProvisioningFlags(MachineProvisioningLocation<?> location) {
+        Map<String, Object> result = super.obtainProvisioningFlags(location);
+        result.putAll(obtainProvisioningFlags(entity(), location));
+        Collection<Integer> ports = getRequiredOpenPorts();
+
+        if (result.containsKey("inboundPorts")) {
+            ports.addAll((Collection<Integer>) result.get("inboundPorts"));
+        }
+        if (!ports.isEmpty()) {
+            result.put("inboundPorts", ports);
+        }
+
+        result.put(LocationConfigKeys.CALLER_CONTEXT.getName(), entity());
+        return result;
+    }
+
+    /** @return provisioning flags for the given entity */
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    protected Map<String,Object> obtainProvisioningFlags(Entity entity, MachineProvisioningLocation location) {
+        Map<String,Object> result = Maps.newLinkedHashMap();
+        result.putAll(Maps.newLinkedHashMap(location.getProvisioningFlags(ImmutableList.of(entity.getEntityType().getName()))));
+        result.putAll(entity.getConfig(SameServerEntity.PROVISIONING_PROPERTIES));
+
+        for (Entity child : entity.getChildren()) {
+            result.putAll(obtainProvisioningFlags(child, location));
+        }
+        return result;
+    }
+
+    @Override
+    protected String startProcessesAtMachine(Supplier<MachineLocation> machineS) {
+        DynamicTasks.queueIfPossible(StartableMethods.startingChildren(entity(), machineS.get()))
+                .orSubmitAsync(entity())
+                .getTask()
+                .getUnchecked();
+        DynamicTasks.waitForLast();
+        return "children started";
+    }
+
+    // Also see stopProcessesAtMachine in SoftwareProcessDriverLifecycleEffectorTasks.
+    // Any fixes made there should probably be applied here too.
+    @Override
+    protected String stopProcessesAtMachine() {
+        TaskAdaptable<?> children = StartableMethods.stoppingChildren(entity());
+        DynamicTasks.queue(children);
+        Exception childException = null;
+        try {
+            DynamicTasks.waitForLast();
+        } catch (Exception e) {
+            childException = e;
+        }
+
+        try {
+            children.asTask().get();
+        } catch (Exception e) {
+            childException = e;
+            LOG.debug("Error stopping children; continuing and will rethrow if no other errors", e);
+        }
+
+        if (childException != null)
+            throw new IllegalStateException("error stopping child", childException);
+
+        return "children stopped";
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerEntity.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerEntity.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerEntity.java
new file mode 100644
index 0000000..927f059
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerEntity.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic.ComputeServiceIndicatorsFromChildrenAndMembers;
+import org.apache.brooklyn.entity.trait.Startable;
+import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.collections.QuorumCheck;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+
+import com.google.common.reflect.TypeToken;
+
+/**
+ * An entity that, on start({@link MachineProvisioningLocation}), will obtain a machine
+ * and pass that to each of its children by calling their {@link Startable#start(java.util.Collection)}
+ * methods with that machine.
+ * 
+ * Thus multiple entities can be set up to run on the same machine.
+ * 
+ * @author aled
+ */
+@ImplementedBy(SameServerEntityImpl.class)
+@SuppressWarnings("serial")
+public interface SameServerEntity extends Entity, Startable {
+
+    @SetFromFlag("provisioningProperties")
+    ConfigKey<Map<String,Object>> PROVISIONING_PROPERTIES = ConfigKeys.newConfigKey(
+            new TypeToken<Map<String, Object>>() {},
+            "provisioning.properties", "Custom properties to be passed in when provisioning a new machine",
+            MutableMap.<String, Object>of());
+    
+    ConfigKey<QuorumCheck> UP_QUORUM_CHECK = ComputeServiceIndicatorsFromChildrenAndMembers.UP_QUORUM_CHECK;
+    ConfigKey<QuorumCheck> RUNNING_QUORUM_CHECK = ComputeServiceIndicatorsFromChildrenAndMembers.RUNNING_QUORUM_CHECK;
+
+    AttributeSensor<Lifecycle> SERVICE_STATE_ACTUAL = Attributes.SERVICE_STATE_ACTUAL;
+
+    @SuppressWarnings("rawtypes")
+    AttributeSensor<MachineProvisioningLocation> PROVISIONING_LOCATION = new BasicAttributeSensor<MachineProvisioningLocation>(
+            MachineProvisioningLocation.class, "softwareservice.provisioningLocation", "Location used to provision a machine where this is running");
+    
+    AttributeSensor<String> HOSTNAME = Attributes.HOSTNAME;
+    
+    AttributeSensor<String> ADDRESS = Attributes.ADDRESS;
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerEntityImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerEntityImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerEntityImpl.java
new file mode 100644
index 0000000..6627b63
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/SameServerEntityImpl.java
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.util.Collection;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.entity.core.AbstractEntity;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic.ComputeServiceIndicatorsFromChildrenAndMembers;
+import org.apache.brooklyn.entity.software.base.lifecycle.MachineLifecycleEffectorTasks;
+import org.apache.brooklyn.util.collections.QuorumCheck;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.Tasks;
+
+public class SameServerEntityImpl extends AbstractEntity implements SameServerEntity {
+
+    private static final MachineLifecycleEffectorTasks LIFECYCLE_TASKS = new SameServerDriverLifecycleEffectorTasks();
+
+    @Override
+    protected void initEnrichers() {
+        super.initEnrichers();
+        
+        // Because can have multiple children (similar to groups/clusters/apps), need to
+        // monitor their health and indicate this has failed if any of them have failed.
+        addEnricher(ServiceStateLogic.newEnricherFromChildren()
+                .configure(ComputeServiceIndicatorsFromChildrenAndMembers.UP_QUORUM_CHECK, QuorumCheck.QuorumChecks.all()));
+    }
+    
+    /**
+     * Restarts the entity and its children.
+     * <p/>
+     * Subclasses should override {@link #doRestart(ConfigBag)} to customise behaviour. */
+    @Override
+    public final void restart() {
+        if (DynamicTasks.getTaskQueuingContext() != null) {
+            doRestart(ConfigBag.EMPTY);
+        } else {
+            Task<?> task = Tasks.builder().name("restart").body(new Runnable() { public void run() { doRestart(ConfigBag.EMPTY); } }).build();
+            Entities.submit(this, task).getUnchecked();
+        }
+    }
+
+    /**
+     * Starts the entity and its children in the given locations.
+     * <p/>
+     * Subclasses should override {@link #doStart} to customise behaviour.
+     */
+    @Override
+    public final void start(final Collection<? extends Location> locations) {
+        checkNotNull(locations, "locations");
+        if (DynamicTasks.getTaskQueuingContext() != null) {
+            doStart(locations);
+        } else {
+            Task<?> task = Tasks.builder().name("start").body(new Runnable() { public void run() { doStart(locations); } }).build();
+            Entities.submit(this, task).getUnchecked();
+        }
+    }
+
+    /**
+     * Stops the entity and its children.
+     * <p/>
+     * Subclasses should override {@link #doStop} to customise behaviour.
+     */
+    @Override
+    public final void stop() {
+        if (DynamicTasks.getTaskQueuingContext() != null) {
+            doStop();
+        } else {
+            Task<?> task = Tasks.builder().name("stop").body(new Runnable() { public void run() { doStop(); } }).build();
+            Entities.submit(this, task).getUnchecked();
+        }
+    }
+
+    /**
+     * To be overridden instead of {@link #start(Collection)}; sub-classes should call
+     * {@code super.doStart(locations)} and should add do additional work via tasks,
+     * executed using {@link DynamicTasks#queue(String, java.util.concurrent.Callable)}.
+     */
+    protected void doStart(Collection<? extends Location> locations) {
+        LIFECYCLE_TASKS.start(locations);
+    }
+
+    /**
+     * To be overridden instead of {@link #stop()}; sub-classes should call {@code
+     * super.doStop()} and should add do additional work via tasks, executed using
+     * {@link DynamicTasks#queue(String, java.util.concurrent.Callable)}.
+     */
+    protected void doStop() {
+        LIFECYCLE_TASKS.stop(ConfigBag.EMPTY);
+    }
+
+    /**
+     * To be overridden instead of {@link #restart()}; sub-classes should call {@code
+     * super.doRestart(ConfigBag)} and should add do additional work via tasks, executed using
+     * {@link DynamicTasks#queue(String, java.util.concurrent.Callable)}.
+     */
+    protected void doRestart(ConfigBag parameters) {
+        LIFECYCLE_TASKS.restart(parameters);
+    }
+
+    @Deprecated /** @deprecated since 0.7.0 subclasses should instead override {@link #doRestart(ConfigBag)} */
+    protected final void doRestart() {
+        doRestart(ConfigBag.EMPTY);
+    }
+
+}


[26/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/EntityHttpClientImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/EntityHttpClientImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/EntityHttpClientImpl.java
new file mode 100644
index 0000000..8d8a396
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/EntityHttpClientImpl.java
@@ -0,0 +1,162 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.net.URI;
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.http.HttpTool;
+import org.apache.brooklyn.util.core.http.HttpToolResponse;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.net.Urls;
+import org.apache.brooklyn.util.stream.Streams;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.HttpClient;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Predicate;
+
+public class EntityHttpClientImpl implements EntityHttpClient {
+    private static final Logger LOG = LoggerFactory.getLogger(EntityHttpClientImpl.class);
+
+    protected static interface HttpCall {
+        public HttpToolResponse call(HttpClient client, URI uri);
+    }
+
+    protected Entity entity;
+    protected AttributeSensor<?> urlSensor;
+    protected ConfigKey<?> urlConfig;
+    protected Predicate<Integer> responseSuccess = ResponseCodePredicates.success();
+
+    protected EntityHttpClientImpl(Entity entity, AttributeSensor<?> urlSensor) {
+        this.entity = entity;
+        this.urlSensor = urlSensor;
+    }
+
+    protected EntityHttpClientImpl(Entity entity, ConfigKey<?> urlConfig) {
+        this.entity = entity;
+        this.urlConfig = urlConfig;
+    }
+
+    @Override
+    public HttpTool.HttpClientBuilder getHttpClientForBrooklynNode() {
+        String baseUrl = getEntityUrl();
+        HttpTool.HttpClientBuilder builder = HttpTool.httpClientBuilder()
+                .trustAll()
+                .laxRedirect(true)
+                .uri(baseUrl);
+        if (entity.getConfig(BrooklynNode.MANAGEMENT_USER) != null) {
+            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
+                    entity.getConfig(BrooklynNode.MANAGEMENT_USER),
+                    entity.getConfig(BrooklynNode.MANAGEMENT_PASSWORD));
+            builder.credentials(credentials);
+        }
+        return builder;
+    }
+
+    @Override
+    public EntityHttpClient responseSuccess(Predicate<Integer> responseSuccess) {
+        this.responseSuccess = checkNotNull(responseSuccess, "responseSuccess");
+        return this;
+    }
+
+    protected HttpToolResponse exec(String path, HttpCall httpCall) {
+        HttpClient client = Preconditions.checkNotNull(getHttpClientForBrooklynNode(), "No address info for "+entity)
+                .build();
+        String baseUri = getEntityUrl();
+        URI uri = URI.create(Urls.mergePaths(baseUri, path));
+
+        HttpToolResponse result;
+        try {
+            result = httpCall.call(client, uri);
+        } catch (Exception e) {
+            Exceptions.propagateIfFatal(e);
+            throw new IllegalStateException("Invalid response invoking " + uri + ": " + e, e);
+        }
+        Tasks.addTagDynamically(BrooklynTaskTags.tagForStream("http_response", Streams.byteArray(result.getContent())));
+        if (!responseSuccess.apply(result.getResponseCode())) {
+            LOG.warn("Invalid response invoking {}: response code {}\n{}: {}",
+                    new Object[]{uri, result.getResponseCode(), result, new String(result.getContent())});
+            throw new IllegalStateException("Invalid response invoking " + uri + ": response code " + result.getResponseCode());
+        }
+        return result;
+    }
+
+    @Override
+    public HttpToolResponse get(String path) {
+        return exec(path, new HttpCall() {
+            @Override
+            public HttpToolResponse call(HttpClient client, URI uri) {
+                return HttpTool.httpGet(client, uri, MutableMap.<String, String>of());
+            }
+        });
+    }
+
+    @Override
+    public HttpToolResponse post(String path, final Map<String, String> headers, final byte[] body) {
+        return exec(path, new HttpCall() {
+            @Override
+            public HttpToolResponse call(HttpClient client, URI uri) {
+                return HttpTool.httpPost(client, uri, headers, body);
+            }
+        });
+    }
+
+    @Override
+    public HttpToolResponse post(String path, final Map<String, String> headers, final Map<String, String> formParams) {
+        return exec(path, new HttpCall() {
+            @Override
+            public HttpToolResponse call(HttpClient client, URI uri) {
+                return HttpTool.httpPost(client, uri, headers, formParams);
+            }
+        });
+    }
+
+    protected String getEntityUrl() {
+        Preconditions.checkState(urlSensor == null ^ urlConfig == null, "Exactly one of urlSensor and urlConfig should be non-null for entity " + entity);
+        Object url = null;
+        if (urlSensor != null) {
+            url = entity.getAttribute(urlSensor);
+        } else if (urlConfig != null) {
+            url = entity.getConfig(urlConfig);
+        }
+        Preconditions.checkNotNull(url, "URL sensor " + urlSensor + " for entity " + entity + " is empty");
+        return url.toString();
+    }
+
+    @Override
+    public HttpToolResponse delete(String path, final Map<String, String> headers) {
+        return exec(path, new HttpCall() {
+            @Override
+            public HttpToolResponse call(HttpClient client, URI uri) {
+                return HttpTool.httpDelete(client, uri, headers);
+            }
+        });
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/LocalBrooklynNode.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/LocalBrooklynNode.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/LocalBrooklynNode.java
new file mode 100644
index 0000000..38e8cfe
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/LocalBrooklynNode.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import org.apache.brooklyn.api.entity.ImplementedBy;
+
+/**
+ * A {@link BrooklynNode} entity that represents the local Brooklyn service.
+ * <p>
+ * Management username and password can be specified in the {@code brooklyn.properties} file, as
+ * either specific username and password (useful when the credentials are set with SHA-256 hashes
+ * or via LDAP) or a username with separately configured webconsole plaintext password.
+ * <pre>
+ * brooklyn.entity.brooklynnode.local.user=admin
+ * brooklyn.entity.brooklynnode.local.password=password
+ * brooklyn.webconsole.security.user.admin.password=password
+ * </pre>
+ */
+@ImplementedBy(LocalBrooklynNodeImpl.class)
+public interface LocalBrooklynNode extends BrooklynNode {
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/LocalBrooklynNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/LocalBrooklynNodeImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/LocalBrooklynNodeImpl.java
new file mode 100644
index 0000000..9f85ebe
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/LocalBrooklynNodeImpl.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.util.text.Strings;
+
+public class LocalBrooklynNodeImpl extends BrooklynNodeImpl implements LocalBrooklynNode {
+
+    private static final String LOCAL_BROOKLYN_NODE_KEY = "brooklyn.entity.brooklynnode.local.%s";
+    private static final String BROOKLYN_WEBCONSOLE_PASSWORD_KEY = "brooklyn.webconsole.security.user.%s.password";
+
+    @Override
+    protected void connectSensors() {
+        // Override management username and password from brooklyn.properties
+        BrooklynProperties properties = (BrooklynProperties) getManagementContext().getConfig();
+        String user = (String) properties.get(String.format(LOCAL_BROOKLYN_NODE_KEY, "user"));
+        String password = (String) properties.get(String.format(LOCAL_BROOKLYN_NODE_KEY, "password"));
+        if (Strings.isBlank(password)) {
+            if (Strings.isBlank(user)) user = "admin";
+            password = (String) properties.get(String.format(BROOKLYN_WEBCONSOLE_PASSWORD_KEY, user));
+        }
+        if (Strings.isNonBlank(user) && Strings.isNonBlank(password)) {
+            setConfig(MANAGEMENT_USER, user);
+            setConfig(MANAGEMENT_PASSWORD, password);
+        }
+        super.connectSensors();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/RemoteEffectorBuilder.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/RemoteEffectorBuilder.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/RemoteEffectorBuilder.java
new file mode 100644
index 0000000..a031930
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/RemoteEffectorBuilder.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Map;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.effector.core.Effectors.EffectorBuilder;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynEntityMirrorImpl.RemoteEffector;
+import org.apache.brooklyn.util.core.http.HttpToolResponse;
+
+import com.google.common.base.Function;
+
+public class RemoteEffectorBuilder {
+    private static class ResultParser implements Function<HttpToolResponse, String> {
+        @Override
+        public String apply(HttpToolResponse input) {
+            return input.getContentAsString();
+        }
+    }
+    
+
+    public static Collection<Effector<String>> of(Collection<?> cfgEffectors) {
+        Collection<Effector<String>> effectors = new ArrayList<Effector<String>>();
+        for (Object objEff : cfgEffectors) {
+            Map<?, ?> cfgEff = (Map<?, ?>)objEff;
+            String effName = (String)cfgEff.get("name");
+            String description = (String)cfgEff.get("description");
+
+            EffectorBuilder<String> eff = Effectors.effector(String.class, effName);
+            Collection<?> params = (Collection<?>)cfgEff.get("parameters");
+
+            /* The *return type* should NOT be included in the signature here.
+             * It might be a type known only at the mirrored brooklyn node
+             * (in which case loading it here would fail); or possibly it could
+             * be a different version of the type here, in which case the signature
+             * would look valid here, but deserializing it would fail.
+             * 
+             * Best to just pass the json representation back to the caller.
+             * (They won't be able to tell the difference between that and deserialize-then-serialize!)
+             */
+            
+            if (description != null) {
+                eff.description(description);
+            }
+
+            for (Object objParam : params) {
+                buildParam(eff, (Map<?, ?>)objParam);
+            }
+
+            eff.impl(new RemoteEffector<String>(effName, new ResultParser()));
+            effectors.add(eff.build());
+        }
+        return effectors;
+    }
+
+    private static void buildParam(EffectorBuilder<String> eff, Map<?, ?> cfgParam) {
+        String name = (String)cfgParam.get("name");
+        String description = (String)cfgParam.get("description");
+        String defaultValue = (String)cfgParam.get("defaultValue");
+
+        eff.parameter(Object.class, name, description, defaultValue /*TypeCoercions.coerce(defaultValue, paramType)*/);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/BrooklynClusterUpgradeEffectorBody.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/BrooklynClusterUpgradeEffectorBody.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/BrooklynClusterUpgradeEffectorBody.java
new file mode 100644
index 0000000..c6ec7b4
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/BrooklynClusterUpgradeEffectorBody.java
@@ -0,0 +1,206 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode.effector;
+
+import java.io.File;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.concurrent.Callable;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.entity.Group;
+import org.apache.brooklyn.api.mgmt.TaskAdaptable;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
+import org.apache.brooklyn.effector.core.EffectorBody;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynCluster;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynCluster.SelectMasterEffector;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynCluster.UpgradeClusterEffector;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode.SetHighAvailabilityModeEffector;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.EntityPredicates;
+import org.apache.brooklyn.entity.core.EntityTasks;
+import org.apache.brooklyn.entity.group.DynamicCluster;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.net.Urls;
+import org.apache.brooklyn.util.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Predicates;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.Iterables;
+
+public class BrooklynClusterUpgradeEffectorBody extends EffectorBody<Void> implements UpgradeClusterEffector {
+    
+    private static final Logger log = LoggerFactory.getLogger(BrooklynClusterUpgradeEffectorBody.class);
+    
+    public static final Effector<Void> UPGRADE_CLUSTER = Effectors.effector(UpgradeClusterEffector.UPGRADE_CLUSTER)
+        .impl(new BrooklynClusterUpgradeEffectorBody()).build();
+
+    private final AtomicBoolean upgradeInProgress = new AtomicBoolean();
+
+    @Override
+    public Void call(ConfigBag parameters) {
+        if (!upgradeInProgress.compareAndSet(false, true)) {
+            throw new IllegalStateException("An upgrade is already in progress.");
+        }
+
+        EntitySpec<?> origMemberSpec = entity().getConfig(BrooklynCluster.MEMBER_SPEC);
+        Preconditions.checkNotNull(origMemberSpec, BrooklynCluster.MEMBER_SPEC.getName() + " is required for " + UpgradeClusterEffector.class.getName());
+
+        log.debug("Upgrading "+entity()+", changing "+BrooklynCluster.MEMBER_SPEC+" from "+origMemberSpec+" / "+origMemberSpec.getConfig());
+
+        boolean success = false;
+        try {
+            String newDownloadUrl = parameters.get(DOWNLOAD_URL);
+            
+            EntitySpec<?> newMemberSpec = EntitySpec.create(origMemberSpec);
+            
+            ConfigBag newConfig = ConfigBag.newInstance();
+            newConfig.putIfNotNull(DOWNLOAD_URL, newDownloadUrl);
+            newConfig.put(BrooklynNode.DISTRO_UPLOAD_URL, inferUploadUrl(newDownloadUrl));
+            newConfig.putAll(ConfigBag.newInstance(parameters.get(EXTRA_CONFIG)).getAllConfigAsConfigKeyMap());
+            newMemberSpec.configure(newConfig.getAllConfigAsConfigKeyMap());
+            
+            entity().setConfig(BrooklynCluster.MEMBER_SPEC, newMemberSpec);
+            
+            log.debug("Upgrading "+entity()+", new "+BrooklynCluster.MEMBER_SPEC+": "+newMemberSpec+" / "+newMemberSpec.getConfig()+" (adding: "+newConfig+")");
+            
+            upgrade(parameters);
+
+            success = true;
+        } finally {
+            if (!success) {
+                log.debug("Upgrading "+entity()+" failed, will rethrow after restoring "+BrooklynCluster.MEMBER_SPEC+" to: "+origMemberSpec);
+                entity().setConfig(BrooklynCluster.MEMBER_SPEC, origMemberSpec);
+            }
+            
+            upgradeInProgress.set(false);
+        }
+        return null;
+    }
+
+    private String inferUploadUrl(String newDownloadUrl) {
+        if (newDownloadUrl==null) return null;
+        boolean isLocal = "file".equals(Urls.getProtocol(newDownloadUrl)) || new File(newDownloadUrl).exists();
+        if (isLocal) {
+            return newDownloadUrl;
+        } else {
+            return null;
+        }
+    }
+
+    protected void upgrade(ConfigBag parameters) {
+        //TODO currently this will fight with auto-scaler policies; they must be turned off for upgrade to work
+
+        Group cluster = (Group)entity();
+        Collection<Entity> initialMembers = cluster.getMembers();
+        int initialClusterSize = initialMembers.size();
+        
+        if (!BrooklynNodeUpgradeEffectorBody.isPersistenceModeEnabled(cluster)) {
+            // would could try a `forcePersistNow`, but that's sloppy; 
+            // for now, require HA/persistence for upgrading 
+            DynamicTasks.queue( Tasks.warning("Check persistence", 
+                new IllegalStateException("Persistence does not appear to be enabled at this cluster. "
+                + "Cluster upgrade will not succeed unless a custom launch script enables it.")) );
+        }
+       
+        //TODO we'd like to disable these nodes as standby targets, ie in some 'hot standby but not available for failover' mode
+        //currently if failover happens to a new node, assumptions below may fail and the cluster may require manual repair
+
+        //1. Initially create a single node to check if it will launch successfully
+        TaskAdaptable<Collection<Entity>> initialNodeTask = DynamicTasks.queue(newCreateNodesTask(1, "Creating first upgraded version node"));
+
+        //2. If everything is OK with the first node launch the rest as well
+        @SuppressWarnings("unused")
+        TaskAdaptable<Collection<Entity>> remainingNodesTask = DynamicTasks.queue(newCreateNodesTask(initialClusterSize - 1, "Creating remaining upgraded version nodes ("+(initialClusterSize - 1)+")"));
+
+        //3. Once we have all nodes running without errors switch master
+        DynamicTasks.queue(Effectors.invocation(cluster, BrooklynCluster.SELECT_MASTER, MutableMap.of(SelectMasterEffector.NEW_MASTER_ID, 
+            Iterables.getOnlyElement(initialNodeTask.asTask().getUnchecked()).getId()))).asTask().getUnchecked();
+
+        //4. Stop the nodes which were running at the start of the upgrade call, but keep them around.
+        //   Should we create a quarantine-like zone for old stopped version?
+        //   For members that were created meanwhile - they will be using the new version already. If the new version
+        //   isn't good then they will fail to start as well, forcing the policies to retry (and succeed once the
+        //   URL is reverted).
+        
+        //any other nodes created via other means should also be using the new spec, so initialMembers will be all the old version nodes
+        DynamicTasks.queue(Effectors.invocation(BrooklynNode.STOP_NODE_BUT_LEAVE_APPS, Collections.emptyMap(), initialMembers)).asTask().getUnchecked();
+    }
+
+    private TaskAdaptable<Collection<Entity>> newCreateNodesTask(int size, String name) {
+        return Tasks.<Collection<Entity>>builder().name(name).body(new CreateNodesCallable(size)).build();
+    }
+
+    protected class CreateNodesCallable implements Callable<Collection<Entity>> {
+        private final int size;
+        public CreateNodesCallable(int size) {
+            this.size = size;
+        }
+        @Override
+        public Collection<Entity> call() throws Exception {
+            return createNodes(size);
+        }
+    }
+
+    protected Collection<Entity> createNodes(int nodeCnt) {
+        DynamicCluster cluster = (DynamicCluster)entity();
+
+        //1. Create the nodes
+        Collection<Entity> newNodes = cluster.resizeByDelta(nodeCnt);
+
+        //2. Wait for them to be RUNNING (or at least STARTING to have completed)
+        // (should already be the case, because above is synchronous and, we think, it will fail if start does not succeed)
+        DynamicTasks.queue(EntityTasks.requiringAttributeEventually(newNodes, Attributes.SERVICE_STATE_ACTUAL, 
+                Predicates.not(Predicates.equalTo(Lifecycle.STARTING)), Duration.minutes(30)));
+
+        //3. Set HOT_STANDBY in case it is not enabled on the command line ...
+        // TODO support via EntitySpec
+        DynamicTasks.queue(Effectors.invocation(
+                BrooklynNode.SET_HIGH_AVAILABILITY_MODE,
+                MutableMap.of(SetHighAvailabilityModeEffector.MODE, HighAvailabilityMode.HOT_STANDBY), 
+                newNodes)).asTask().getUnchecked();
+        //... and wait until all of the nodes change state
+        // TODO fail quicker if state changes to FAILED
+        DynamicTasks.queue(EntityTasks.requiringAttributeEventually(newNodes, BrooklynNode.MANAGEMENT_NODE_STATE, 
+                Predicates.equalTo(ManagementNodeState.HOT_STANDBY), Duration.FIVE_MINUTES));
+
+        // TODO also check that the nodes created all report the original master, in case persistence changes it
+        
+        //5. Just in case check if all of the nodes are SERVICE_UP (which would rule out ON_FIRE as well)
+        Collection<Entity> failedNodes = Collections2.filter(newNodes, EntityPredicates.attributeEqualTo(BrooklynNode.SERVICE_UP, Boolean.FALSE));
+        if (!failedNodes.isEmpty()) {
+            throw new IllegalStateException("Nodes " + failedNodes + " are not " + BrooklynNode.SERVICE_UP + " though successfully in " + ManagementNodeState.HOT_STANDBY);
+        }
+        return newNodes;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/BrooklynNodeUpgradeEffectorBody.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/BrooklynNodeUpgradeEffectorBody.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/BrooklynNodeUpgradeEffectorBody.java
new file mode 100644
index 0000000..baf4ae9
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/BrooklynNodeUpgradeEffectorBody.java
@@ -0,0 +1,229 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode.effector;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.entity.drivers.DriverDependentEntity;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.config.MapConfigKey;
+import org.apache.brooklyn.effector.core.EffectorBody;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynCluster;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNodeDriver;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.apache.brooklyn.entity.core.EntityTasks;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.StopSoftwareParameters;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.StopSoftwareParameters.StopMode;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.net.Urls;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Predicates;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.reflect.TypeToken;
+
+@SuppressWarnings("serial")
+/** Upgrades a brooklyn node in-place on the box, 
+ * by creating a child brooklyn node and ensuring it can rebind in HOT_STANDBY
+ * <p>
+ * Requires the target node to have persistence enabled. 
+ */
+public class BrooklynNodeUpgradeEffectorBody extends EffectorBody<Void> {
+
+    private static final Logger log = LoggerFactory.getLogger(BrooklynNodeUpgradeEffectorBody.class);
+    
+    public static final ConfigKey<String> DOWNLOAD_URL = BrooklynNode.DOWNLOAD_URL.getConfigKey();
+    public static final ConfigKey<Boolean> DO_DRY_RUN_FIRST = ConfigKeys.newBooleanConfigKey(
+            "doDryRunFirst", "Test rebinding with a temporary instance before stopping the entity for upgrade.", true);
+    public static final ConfigKey<Map<String,Object>> EXTRA_CONFIG = MapConfigKey.builder(new TypeToken<Map<String,Object>>() {})
+        .name("extraConfig")
+        .description("Additional new config to set on the BrooklynNode as part of upgrading")
+        .build();
+
+    public static final Effector<Void> UPGRADE = Effectors.effector(Void.class, "upgrade")
+        .description("Changes the Brooklyn build used to run this node, "
+            + "by spawning a dry-run node then copying the installed files across. "
+            + "This node must be running for persistence for in-place upgrading to work.")
+        .parameter(BrooklynNode.SUGGESTED_VERSION)
+        .parameter(DOWNLOAD_URL)
+        .parameter(DO_DRY_RUN_FIRST)
+        .parameter(EXTRA_CONFIG)
+        .impl(new BrooklynNodeUpgradeEffectorBody()).build();
+    
+    @Override
+    public Void call(ConfigBag parametersO) {
+        if (!isPersistenceModeEnabled(entity())) {
+            // would could try a `forcePersistNow`, but that's sloppy; 
+            // for now, require HA/persistence for upgrading
+            DynamicTasks.queue( Tasks.warning("Check persistence", 
+                new IllegalStateException("Persistence does not appear to be enabled at this cluster. "
+                + "In-place node upgrade will not succeed unless a custom launch script enables it.")) );
+        }
+
+        final ConfigBag parameters = ConfigBag.newInstanceCopying(parametersO);
+
+        /*
+         * all parameters are passed to children, apart from EXTRA_CONFIG
+         * whose value (as a map) is so passed; it provides an easy way to set extra config in the gui.
+         * (IOW a key-value mapping can be passed either inside EXTRA_CONFIG or as a sibling to EXTRA_CONFIG)  
+         */
+        if (parameters.containsKey(EXTRA_CONFIG)) {
+            Map<String, Object> extra = parameters.get(EXTRA_CONFIG);
+            parameters.remove(EXTRA_CONFIG);
+            parameters.putAll(extra);
+        }
+        log.debug(this+" upgrading, using "+parameters);
+        
+        final String bkName;
+        boolean doDryRunFirst = parameters.get(DO_DRY_RUN_FIRST);
+        if(doDryRunFirst) {
+            bkName = dryRunUpdate(parameters);
+        } else {
+            bkName = "direct-"+Identifiers.makeRandomId(4);
+        }
+        
+        // Stop running instance
+        DynamicTasks.queue(Tasks.builder().name("shutdown node")
+                .add(Effectors.invocation(entity(), BrooklynNode.STOP_NODE_BUT_LEAVE_APPS, ImmutableMap.of(StopSoftwareParameters.STOP_MACHINE_MODE, StopMode.NEVER)))
+                .build());
+
+        // backup old files
+        DynamicTasks.queue(Tasks.builder().name("backup old version").body(new Runnable() {
+            @Override
+            public void run() {
+                String runDir = entity().getAttribute(SoftwareProcess.RUN_DIR);
+                String bkDir = Urls.mergePaths(runDir, "..", Urls.getBasename(runDir)+"-backups", bkName);
+                log.debug(this+" storing backup of previous version in "+bkDir);
+                DynamicTasks.queue(SshEffectorTasks.ssh(
+                    "cd "+runDir,
+                    "mkdir -p "+bkDir,
+                    "mv * "+bkDir
+                    // By removing the run dir of the entity we force it to go through
+                    // the customize step again on start and re-generate local-brooklyn.properties.
+                    ).summary("move files"));
+            }
+        }).build());
+        
+        // Reconfigure entity
+        DynamicTasks.queue(Tasks.builder().name("reconfigure").body(new Runnable() {
+            @Override
+            public void run() {
+                DynamicTasks.waitForLast();
+                ((EntityInternal)entity()).setAttribute(SoftwareProcess.INSTALL_DIR, (String)null);
+                entity().setConfig(SoftwareProcess.INSTALL_UNIQUE_LABEL, (String)null);
+                entity().getConfigMap().addToLocalBag(parameters.getAllConfig());
+                entity().setAttribute(BrooklynNode.DOWNLOAD_URL, entity().getConfig(DOWNLOAD_URL));
+
+                // Setting SUGGESTED_VERSION will result in an new empty INSTALL_FOLDER, but clear it
+                // just in case the user specified already installed version.
+                ((BrooklynNodeDriver)((DriverDependentEntity<?>)entity()).getDriver()).clearInstallDir();
+            }
+        }).build());
+        
+        // Start this entity, running the new version.
+        // This will download and install the new dist (if not already done by the dry run node).
+        DynamicTasks.queue(Effectors.invocation(entity(), BrooklynNode.START, ConfigBag.EMPTY));
+
+        return null;
+    }
+
+    private String dryRunUpdate(ConfigBag parameters) {
+        // TODO require entity() node state master or hot standby AND require persistence enabled, or a new 'force_attempt_upgrade' parameter to be applied
+        // TODO could have a 'skip_dry_run_upgrade' parameter
+        // TODO could support 'dry_run_only' parameter, with optional resumption tasks (eg new dynamic effector)
+
+        // 1 add new brooklyn version entity as child (so uses same machine), with same config apart from things in parameters
+        final Entity dryRunChild = entity().addChild(createDryRunSpec()
+            .displayName("Upgraded Version Dry-Run Node")
+            // install dir and label are recomputed because they are not inherited, and download_url will normally be different
+            .configure(parameters.getAllConfig()));
+
+        //force this to start as hot-standby
+        // TODO alternatively could use REST API as in BrooklynClusterUpgradeEffectorBody
+        String launchParameters = dryRunChild.getConfig(BrooklynNode.EXTRA_LAUNCH_PARAMETERS);
+        if (Strings.isBlank(launchParameters)) launchParameters = "";
+        else launchParameters += " ";
+        launchParameters += "--highAvailability "+HighAvailabilityMode.HOT_STANDBY;
+        ((EntityInternal)dryRunChild).setConfig(BrooklynNode.EXTRA_LAUNCH_PARAMETERS, launchParameters);
+
+        Entities.manage(dryRunChild);
+        final String dryRunNodeUid = dryRunChild.getId();
+        ((EntityInternal)dryRunChild).setDisplayName("Dry-Run Upgraded Brooklyn Node ("+dryRunNodeUid+")");
+
+        DynamicTasks.queue(Effectors.invocation(dryRunChild, BrooklynNode.START, ConfigBag.EMPTY));
+
+        // 2 confirm hot standby status
+        DynamicTasks.queue(EntityTasks.requiringAttributeEventually(dryRunChild, BrooklynNode.MANAGEMENT_NODE_STATE, 
+            Predicates.equalTo(ManagementNodeState.HOT_STANDBY), Duration.FIVE_MINUTES));
+
+        // 3 stop new version
+        DynamicTasks.queue(Tasks.builder().name("shutdown transient node")
+            .add(Effectors.invocation(dryRunChild, BrooklynNode.STOP_NODE_BUT_LEAVE_APPS, ImmutableMap.of(StopSoftwareParameters.STOP_MACHINE_MODE, StopMode.NEVER)))
+            .build());
+
+        DynamicTasks.queue(Tasks.<Void>builder().name("remove transient node").body(
+            new Runnable() {
+                @Override
+                public void run() {
+                    Entities.unmanage(dryRunChild);
+                }
+            }
+        ).build());
+
+        return dryRunChild.getId();
+    }
+
+    protected EntitySpec<? extends BrooklynNode> createDryRunSpec() {
+        return EntitySpec.create(BrooklynNode.class);
+    }
+
+    @Beta
+    static boolean isPersistenceModeEnabled(Entity entity) {
+        // TODO when there are PERSIST* options in BrooklynNode, look at them here!
+        // or, even better, make a REST call to check persistence
+        String params = null;
+        if (entity instanceof BrooklynCluster) {
+            EntitySpec<?> spec = entity.getConfig(BrooklynCluster.MEMBER_SPEC);
+            params = Strings.toString( spec.getConfig().get(BrooklynNode.EXTRA_LAUNCH_PARAMETERS) );
+        }
+        if (params==null) params = entity.getConfig(BrooklynNode.EXTRA_LAUNCH_PARAMETERS);
+        if (params==null) return false;
+        if (params.indexOf("persist")==0) return false;
+        return true;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/SelectMasterEffectorBody.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/SelectMasterEffectorBody.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/SelectMasterEffectorBody.java
new file mode 100644
index 0000000..f9bc79f
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/SelectMasterEffectorBody.java
@@ -0,0 +1,174 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode.effector;
+
+import java.util.NoSuchElementException;
+import java.util.concurrent.Callable;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.Group;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
+import org.apache.brooklyn.effector.core.EffectorBody;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynCluster;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynCluster.SelectMasterEffector;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode.SetHighAvailabilityModeEffector;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode.SetHighAvailabilityPriorityEffector;
+import org.apache.brooklyn.entity.core.EntityPredicates;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.repeat.Repeater;
+import org.apache.brooklyn.util.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Objects;
+import com.google.common.collect.Iterables;
+
+public class SelectMasterEffectorBody extends EffectorBody<Void> implements SelectMasterEffector {
+    public static final Effector<Void> SELECT_MASTER = Effectors.effector(SelectMasterEffector.SELECT_MASTER).impl(new SelectMasterEffectorBody()).build();
+    
+    private static final Logger LOG = LoggerFactory.getLogger(SelectMasterEffectorBody.class);
+
+    private static final int HA_STANDBY_PRIORITY = 0;
+    private static final int HA_MASTER_PRIORITY = 1;
+
+    private AtomicBoolean selectMasterInProgress = new AtomicBoolean();
+
+    @Override
+    public Void call(ConfigBag parameters) {
+        if (!selectMasterInProgress.compareAndSet(false, true)) {
+            throw new IllegalStateException("A master change is already in progress.");
+        }
+
+        try {
+            selectMaster(parameters);
+        } finally {
+            selectMasterInProgress.set(false);
+        }
+        return null;
+    }
+
+    private void selectMaster(ConfigBag parameters) {
+        String newMasterId = parameters.get(NEW_MASTER_ID);
+        Preconditions.checkNotNull(newMasterId, NEW_MASTER_ID.getName() + " parameter is required");
+
+        final Entity oldMaster = entity().getAttribute(BrooklynCluster.MASTER_NODE);
+        if (oldMaster != null && oldMaster.getId().equals(newMasterId)) {
+            LOG.info(newMasterId + " is already the current master, no change needed.");
+            return;
+        }
+
+        final Entity newMaster = getMember(newMasterId);
+
+        //1. Increase the priority of the node we wish to become master
+        toggleNodePriority(newMaster, HA_MASTER_PRIORITY);
+
+        //2. Demote the existing master so a new election takes place
+        try {
+            // this allows the finally block to run even on failure
+            DynamicTasks.swallowChildrenFailures();
+            
+            if (oldMaster != null) {
+                demoteOldMaster(oldMaster, HighAvailabilityMode.HOT_STANDBY);
+            }
+
+            waitMasterHandover(oldMaster, newMaster);
+        } finally { 
+            //3. Revert the priority of the node once it has become master
+            toggleNodePriority(newMaster, HA_STANDBY_PRIORITY);
+        }
+
+        checkMasterSelected(newMaster);
+    }
+
+    private void waitMasterHandover(final Entity oldMaster, final Entity newMaster) {
+        boolean masterChanged = Repeater.create()
+            .backoff(Repeater.DEFAULT_REAL_QUICK_PERIOD, 1.5, Duration.FIVE_SECONDS)
+            .limitTimeTo(Duration.ONE_MINUTE)
+            .until(new Callable<Boolean>() {
+                @Override
+                public Boolean call() throws Exception {
+                    Entity master = getMasterNode();
+                    return !Objects.equal(master, oldMaster) && master != null;
+                }
+            })
+            .run();
+        if (!masterChanged) {
+            LOG.warn("Timeout waiting for node to become master: " + newMaster + ".");
+        }
+    }
+
+    private void demoteOldMaster(Entity oldMaster, HighAvailabilityMode mode) {
+        ManagementNodeState oldState = DynamicTasks.queue(
+                Effectors.invocation(
+                        oldMaster,
+                        BrooklynNode.SET_HIGH_AVAILABILITY_MODE,
+                        MutableMap.of(SetHighAvailabilityModeEffector.MODE, mode))
+            ).asTask().getUnchecked();
+
+        if (oldState != ManagementNodeState.MASTER) {
+            LOG.warn("The previous HA state on node " + oldMaster.getId() + " was " + oldState +
+                    ", while the expected value is " + ManagementNodeState.MASTER + ".");
+        }
+    }
+
+    private void toggleNodePriority(Entity node, int newPriority) {
+        Integer oldPriority = DynamicTasks.queue(
+                Effectors.invocation(
+                    node,
+                    BrooklynNode.SET_HIGH_AVAILABILITY_PRIORITY,
+                    MutableMap.of(SetHighAvailabilityPriorityEffector.PRIORITY, newPriority))
+            ).asTask().getUnchecked();
+
+        Integer expectedPriority = (newPriority == HA_MASTER_PRIORITY ? HA_STANDBY_PRIORITY : HA_MASTER_PRIORITY);
+        if (oldPriority != expectedPriority) {
+            LOG.warn("The previous HA priority on node " + node.getId() + " was " + oldPriority +
+                    ", while the expected value is " + expectedPriority + " (while setting priority " +
+                    newPriority + ").");
+        }
+    }
+
+    private void checkMasterSelected(Entity newMaster) {
+        Entity actualMaster = getMasterNode();
+        if (actualMaster != newMaster) {
+            throw new IllegalStateException("Expected node " + newMaster + " to be master, but found that " +
+                    "master is " + actualMaster + " instead.");
+        }
+    }
+
+    private Entity getMember(String memberId) {
+        Group cluster = (Group)entity();
+        try {
+            return Iterables.find(cluster.getMembers(), EntityPredicates.idEqualTo(memberId));
+        } catch (NoSuchElementException e) {
+            throw new IllegalStateException(memberId + " is not an ID of brooklyn node in this cluster");
+        }
+    }
+
+    private Entity getMasterNode() {
+        return entity().getAttribute(BrooklynCluster.MASTER_NODE);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/SetHighAvailabilityModeEffectorBody.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/SetHighAvailabilityModeEffectorBody.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/SetHighAvailabilityModeEffectorBody.java
new file mode 100644
index 0000000..96d3e49
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/SetHighAvailabilityModeEffectorBody.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode.effector;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
+import org.apache.brooklyn.effector.core.EffectorBody;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+import org.apache.brooklyn.entity.brooklynnode.EntityHttpClient;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode.SetHighAvailabilityModeEffector;
+import org.apache.brooklyn.sensor.feed.http.HttpValueFunctions;
+import org.apache.brooklyn.sensor.feed.http.JsonFunctions;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.http.HttpToolResponse;
+import org.apache.brooklyn.util.guava.Functionals;
+import org.apache.brooklyn.util.javalang.Enums;
+import org.apache.http.HttpStatus;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Function;
+import com.google.common.collect.ImmutableMap;
+
+public class SetHighAvailabilityModeEffectorBody extends EffectorBody<ManagementNodeState> implements SetHighAvailabilityModeEffector {
+    public static final Effector<ManagementNodeState> SET_HIGH_AVAILABILITY_MODE = Effectors.effector(SetHighAvailabilityModeEffector.SET_HIGH_AVAILABILITY_MODE).impl(new SetHighAvailabilityModeEffectorBody()).build();
+
+    @Override
+    public ManagementNodeState call(ConfigBag parameters) {
+        HighAvailabilityMode mode = parameters.get(MODE);
+        Preconditions.checkNotNull(mode, MODE.getName() + " parameter is required");
+
+        EntityHttpClient httpClient = ((BrooklynNode)entity()).http();
+        HttpToolResponse resp = httpClient.post("/v1/server/ha/state", 
+                ImmutableMap.of("Brooklyn-Allow-Non-Master-Access", "true"),
+                ImmutableMap.of("mode", mode.toString()));
+
+        if (resp.getResponseCode() == HttpStatus.SC_OK) {
+            Function<HttpToolResponse, ManagementNodeState> parseRespone = Functionals.chain(
+                    Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.cast(String.class)),
+                    Enums.fromStringFunction(ManagementNodeState.class));
+            return parseRespone.apply(resp);
+        } else {
+            throw new IllegalStateException("Unexpected response code: " + resp.getResponseCode() + "\n" + resp.getContentAsString());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/SetHighAvailabilityPriorityEffectorBody.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/SetHighAvailabilityPriorityEffectorBody.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/SetHighAvailabilityPriorityEffectorBody.java
new file mode 100644
index 0000000..4fd1aa4
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/effector/SetHighAvailabilityPriorityEffectorBody.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode.effector;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.effector.core.EffectorBody;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+import org.apache.brooklyn.entity.brooklynnode.EntityHttpClient;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode.SetHighAvailabilityPriorityEffector;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.http.HttpToolResponse;
+import org.apache.http.HttpStatus;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+
+public class SetHighAvailabilityPriorityEffectorBody extends EffectorBody<Integer> implements SetHighAvailabilityPriorityEffector {
+    public static final Effector<Integer> SET_HIGH_AVAILABILITY_PRIORITY = Effectors.effector(SetHighAvailabilityPriorityEffector.SET_HIGH_AVAILABILITY_PRIORITY).impl(new SetHighAvailabilityPriorityEffectorBody()).build();
+
+    @Override
+    public Integer call(ConfigBag parameters) {
+        Integer priority = parameters.get(PRIORITY);
+        Preconditions.checkNotNull(priority, PRIORITY.getName() + " parameter is required");
+
+        EntityHttpClient httpClient = ((BrooklynNode)entity()).http();
+        HttpToolResponse resp = httpClient.post("/v1/server/ha/priority",
+            ImmutableMap.of("Brooklyn-Allow-Non-Master-Access", "true"),
+            ImmutableMap.of("priority", priority.toString()));
+
+        if (resp.getResponseCode() == HttpStatus.SC_OK) {
+            return Integer.valueOf(resp.getContentAsString());
+        } else {
+            throw new IllegalStateException("Unexpected response code: " + resp.getResponseCode() + "\n" + resp.getContentAsString());
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefAttributeFeed.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefAttributeFeed.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefAttributeFeed.java
new file mode 100644
index 0000000..6dcd9a9
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefAttributeFeed.java
@@ -0,0 +1,410 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.mgmt.ExecutionContext;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.apache.brooklyn.sensor.feed.AbstractFeed;
+import org.apache.brooklyn.sensor.feed.PollHandler;
+import org.apache.brooklyn.sensor.feed.Poller;
+import org.apache.brooklyn.sensor.feed.ssh.SshPollValue;
+import org.apache.brooklyn.util.core.flags.TypeCoercions;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.apache.brooklyn.util.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+import com.google.common.base.Strings;
+import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import com.google.common.reflect.TypeToken;
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+
+/**
+ * A sensor feed that retrieves attributes from Chef server and converts selected attributes to sensors.
+ *
+ * <p>To use this feed, you must provide the entity, the name of the node as it is known to Chef, and a collection of attribute
+ * sensors. The attribute sensors must follow the naming convention of starting with the string <tt>chef.attribute.</tt>
+ * followed by a period-separated path through the Chef attribute hierarchy. For example, an attribute sensor named
+ * <tt>chef.attribute.sql_server.instance_name</tt> would cause the feed to search for a Chef attribute called
+ * <tt>sql_server</tt>, and within that an attribute <tt>instance_name</tt>, and set the sensor to the value of this
+ * attribute.</p>
+ *
+ * <p>This feed uses the <tt>knife</tt> tool to query all the attributes on a named node. It then iterates over the configured
+ * list of attribute sensors, using the sensor name to locate an equivalent Chef attribute. The sensor is then set to the value
+ * of the Chef attribute.</p>
+ *
+ * <p>Example:</p>
+ *
+ * {@code
+ * @Override
+ * protected void connectSensors() {
+ *     nodeAttributesFeed = ChefAttributeFeed.newFeed(this, nodeName, new AttributeSensor[]{
+ *             SqlServerNode.CHEF_ATTRIBUTE_NODE_NAME,
+ *             SqlServerNode.CHEF_ATTRIBUTE_SQL_SERVER_INSTANCE_NAME,
+ *             SqlServerNode.CHEF_ATTRIBUTE_SQL_SERVER_PORT,
+ *             SqlServerNode.CHEF_ATTRIBUTE_SQL_SERVER_SA_PASSWORD
+ *     });
+ * }
+ * }
+ *
+ * @since 0.6.0
+ * @author richardcloudsoft
+ */
+public class ChefAttributeFeed extends AbstractFeed {
+
+    private static final Logger log = LoggerFactory.getLogger(ChefAttributeFeed.class);
+
+    /**
+     * Prefix for attribute sensor names.
+     */
+    public static final String CHEF_ATTRIBUTE_PREFIX = "chef.attribute.";
+
+    @SuppressWarnings("serial")
+    public static final ConfigKey<Set<ChefAttributePollConfig<?>>> POLLS = ConfigKeys.newConfigKey(
+            new TypeToken<Set<ChefAttributePollConfig<?>>>() {},
+            "polls");
+
+    public static final ConfigKey<String> NODE_NAME = ConfigKeys.newStringConfigKey("nodeName");
+    
+    public static Builder builder() {
+        return new Builder();
+    }
+
+    @SuppressWarnings("rawtypes")
+    public static class Builder {
+        private EntityLocal entity;
+        private boolean onlyIfServiceUp = false;
+        private String nodeName;
+        private Set<ChefAttributePollConfig> polls = Sets.newLinkedHashSet();
+        private Duration period = Duration.of(30, TimeUnit.SECONDS);
+        private String uniqueTag;
+        private volatile boolean built;
+
+        public Builder entity(EntityLocal val) {
+            this.entity = checkNotNull(val, "entity");
+            return this;
+        }
+        public Builder onlyIfServiceUp() { return onlyIfServiceUp(true); }
+        public Builder onlyIfServiceUp(boolean onlyIfServiceUp) { 
+            this.onlyIfServiceUp = onlyIfServiceUp; 
+            return this; 
+        }
+        public Builder nodeName(String nodeName) {
+            this.nodeName = checkNotNull(nodeName, "nodeName");
+            return this;
+        }
+        public Builder addSensor(ChefAttributePollConfig config) {
+            polls.add(config);
+            return this;
+        }
+        @SuppressWarnings("unchecked")
+        public Builder addSensor(String chefAttributePath, AttributeSensor sensor) {
+            return addSensor(new ChefAttributePollConfig(sensor).chefAttributePath(chefAttributePath));
+        }
+        public Builder addSensors(Map<String, AttributeSensor> sensors) {
+            for (Map.Entry<String, AttributeSensor> entry : sensors.entrySet()) {
+                addSensor(entry.getKey(), entry.getValue());
+            }
+            return this;
+        }
+        public Builder addSensors(AttributeSensor[] sensors) {
+            return addSensors(Arrays.asList(checkNotNull(sensors, "sensors")));
+        }
+        public Builder addSensors(Iterable<AttributeSensor> sensors) {
+            for(AttributeSensor sensor : checkNotNull(sensors, "sensors")) {
+                checkNotNull(sensor, "sensors collection contains a null value");
+                checkArgument(sensor.getName().startsWith(CHEF_ATTRIBUTE_PREFIX), "sensor name must be prefixed "+CHEF_ATTRIBUTE_PREFIX+" for autodetection to work");
+                addSensor(sensor.getName().substring(CHEF_ATTRIBUTE_PREFIX.length()), sensor);
+            }
+            return this;
+        }
+        public Builder period(Duration period) {
+            this.period = period;
+            return this;
+        }
+        public Builder period(long millis) {
+            return period(Duration.of(millis, TimeUnit.MILLISECONDS));
+        }
+        public Builder period(long val, TimeUnit units) {
+            return period(Duration.of(val, units));
+        }
+        public Builder uniqueTag(String uniqueTag) {
+            this.uniqueTag = uniqueTag;
+            return this;
+        }
+        public ChefAttributeFeed build() {
+            built = true;
+            ChefAttributeFeed result = new ChefAttributeFeed(this);
+            result.setEntity(checkNotNull(entity, "entity"));
+            result.start();
+            return result;
+        }
+        @Override
+        protected void finalize() {
+            if (!built) log.warn("SshFeed.Builder created, but build() never called");
+        }
+    }
+
+    private KnifeTaskFactory<String> knifeTaskFactory;
+
+    /**
+     * For rebind; do not call directly; use builder
+     */
+    public ChefAttributeFeed() {
+    }
+    
+    protected ChefAttributeFeed(Builder builder) {
+        setConfig(ONLY_IF_SERVICE_UP, builder.onlyIfServiceUp);
+        setConfig(NODE_NAME, checkNotNull(builder.nodeName, "builder.nodeName"));
+
+        Set<ChefAttributePollConfig<?>> polls = Sets.newLinkedHashSet();
+        for (ChefAttributePollConfig<?> config : builder.polls) {
+            if (!config.isEnabled()) continue;
+            @SuppressWarnings({ "unchecked", "rawtypes" })
+            ChefAttributePollConfig<?> configCopy = new ChefAttributePollConfig(config);
+            if (configCopy.getPeriod() < 0) configCopy.period(builder.period);
+            polls.add(configCopy);
+        }
+        setConfig(POLLS, polls);
+        initUniqueTag(builder.uniqueTag, polls);
+    }
+
+    @Override
+    protected void preStart() {
+        final String nodeName = getConfig(NODE_NAME);
+        final Set<ChefAttributePollConfig<?>> polls = getConfig(POLLS);
+        
+        long minPeriod = Integer.MAX_VALUE;
+        for (ChefAttributePollConfig<?> config : polls) {
+            minPeriod = Math.min(minPeriod, config.getPeriod());
+        }
+
+        knifeTaskFactory = new KnifeNodeAttributeQueryTaskFactory(nodeName);
+        
+        final Callable<SshPollValue> getAttributesFromKnife = new Callable<SshPollValue>() {
+            public SshPollValue call() throws Exception {
+                ProcessTaskWrapper<String> taskWrapper = knifeTaskFactory.newTask();
+                final ExecutionContext executionContext = ((EntityInternal) entity).getManagementSupport().getExecutionContext();
+                log.debug("START: Running knife to query attributes of Chef node {}", nodeName);
+                executionContext.submit(taskWrapper);
+                taskWrapper.block();
+                log.debug("DONE:  Running knife to query attributes of Chef node {}", nodeName);
+                return new SshPollValue(null, taskWrapper.getExitCode(), taskWrapper.getStdout(), taskWrapper.getStderr());
+            }
+        };
+
+        getPoller().scheduleAtFixedRate(
+                new CallInEntityExecutionContext<SshPollValue>(entity, getAttributesFromKnife),
+                new SendChefAttributesToSensors(entity, polls),
+                minPeriod);
+    }
+
+    @SuppressWarnings("unchecked")
+    protected Poller<SshPollValue> getPoller() {
+        return (Poller<SshPollValue>) super.getPoller();
+    }
+
+    /**
+     * An implementation of {@link KnifeTaskFactory} that queries for the attributes of a node.
+     */
+    private static class KnifeNodeAttributeQueryTaskFactory extends KnifeTaskFactory<String> {
+        private final String nodeName;
+
+        public KnifeNodeAttributeQueryTaskFactory(String nodeName) {
+            super("retrieve attributes of node " + nodeName);
+            this.nodeName = nodeName;
+        }
+
+        @Override
+        protected List<String> initialKnifeParameters() {
+            return ImmutableList.of("node", "show", "-l", nodeName, "--format", "json");
+        }
+    }
+
+    /**
+     * A {@link Callable} that wraps another {@link Callable}, where the inner {@link Callable} is executed in the context of a
+     * specific entity.
+     *
+     * @param <T> The type of the {@link Callable}.
+     */
+    private static class CallInEntityExecutionContext<T> implements Callable<T> {
+
+        private final Callable<T> job;
+        private EntityLocal entity;
+
+        private CallInEntityExecutionContext(EntityLocal entity, Callable<T> job) {
+            this.job = job;
+            this.entity = entity;
+        }
+
+        @Override
+        public T call() throws Exception {
+            final ExecutionContext executionContext = ((EntityInternal) entity).getManagementSupport().getExecutionContext();
+            return executionContext.submit(Maps.newHashMap(), job).get();
+        }
+    }
+
+    /**
+     * A poll handler that takes the result of the <tt>knife</tt> invocation and sets the appropriate sensors.
+     */
+    private static class SendChefAttributesToSensors implements PollHandler<SshPollValue> {
+        private static final Iterable<String> PREFIXES = ImmutableList.of("", "automatic", "force_override", "override", "normal", "force_default", "default");
+        private static final Splitter SPLITTER = Splitter.on('.');
+
+        private final EntityLocal entity;
+        private final Map<String, AttributeSensor<?>> chefAttributeSensors;
+
+        public SendChefAttributesToSensors(EntityLocal entity, Set<ChefAttributePollConfig<?>> polls) {
+            this.entity = entity;
+            chefAttributeSensors = Maps.newLinkedHashMap();
+            for (ChefAttributePollConfig<?> config : polls) {
+                chefAttributeSensors.put(config.getChefAttributePath(), config.getSensor());
+            }
+        }
+
+        @Override
+        public boolean checkSuccess(SshPollValue val) {
+            if (val.getExitStatus() != 0) return false;
+            String stderr = val.getStderr();
+            if (stderr == null || stderr.length() != 0) return false;
+            String out = val.getStdout();
+            if (out == null || out.length() == 0) return false;
+            if (!out.contains("{")) return false;
+            return true;
+        }
+
+        @SuppressWarnings({ "unchecked", "rawtypes" })
+        @Override
+        public void onSuccess(SshPollValue val) {
+            String stdout = val.getStdout();
+            int jsonStarts = stdout.indexOf('{');
+            if (jsonStarts > 0)
+                stdout = stdout.substring(jsonStarts);
+            JsonElement jsonElement = new Gson().fromJson(stdout, JsonElement.class);
+
+            for (Map.Entry<String, AttributeSensor<?>> attribute : chefAttributeSensors.entrySet()) {
+                String chefAttributeName = attribute.getKey();
+                AttributeSensor<?> sensor = attribute.getValue();
+                log.trace("Finding value for attribute sensor " + sensor.getName());
+
+                Iterable<String> path = SPLITTER.split(chefAttributeName);
+                JsonElement elementForSensor = null;
+                for(String prefix : PREFIXES) {
+                    Iterable<String> prefixedPath = !Strings.isNullOrEmpty(prefix)
+                            ? Iterables.concat(ImmutableList.of(prefix), path)
+                            : path;
+                    try {
+                        elementForSensor = getElementByPath(jsonElement.getAsJsonObject(), prefixedPath);
+                    } catch(IllegalArgumentException e) {
+                        log.error("Entity {}: bad Chef attribute {} for sensor {}: {}", new Object[]{
+                                entity.getDisplayName(),
+                                Joiner.on('.').join(prefixedPath),
+                                sensor.getName(),
+                                e.getMessage()});
+                        throw Throwables.propagate(e);
+                    }
+                    if (elementForSensor != null) {
+                        log.debug("Entity {}: apply Chef attribute {} to sensor {} with value {}", new Object[]{
+                                entity.getDisplayName(),
+                                Joiner.on('.').join(prefixedPath),
+                                sensor.getName(),
+                                elementForSensor.getAsString()});
+                        break;
+                    }
+                }
+                if (elementForSensor != null) {
+                    entity.setAttribute((AttributeSensor)sensor, TypeCoercions.coerce(elementForSensor.getAsString(), sensor.getTypeToken()));
+                } else {
+                    log.debug("Entity {}: no Chef attribute matching {}; setting sensor {} to null", new Object[]{
+                            entity.getDisplayName(),
+                            chefAttributeName,
+                            sensor.getName()});
+                    entity.setAttribute(sensor, null);
+                }
+            }
+        }
+
+        private JsonElement getElementByPath(JsonElement element, Iterable<String> path) {
+            if (Iterables.isEmpty(path)) {
+                return element;
+            } else {
+                String head = Iterables.getFirst(path, null);
+                Preconditions.checkArgument(!Strings.isNullOrEmpty(head), "path must not contain empty or null elements");
+                Iterable<String> tail = Iterables.skip(path, 1);
+                JsonElement child = ((JsonObject) element).get(head);
+                return child != null
+                        ? getElementByPath(child, tail)
+                        : null;
+            }
+        }
+
+        @Override
+        public void onFailure(SshPollValue val) {
+            log.error("Chef attribute query did not respond as expected. exitcode={} stdout={} stderr={}", new Object[]{val.getExitStatus(), val.getStdout(), val.getStderr()});
+            for (AttributeSensor<?> attribute : chefAttributeSensors.values()) {
+                if (!attribute.getName().startsWith(CHEF_ATTRIBUTE_PREFIX))
+                    continue;
+                entity.setAttribute(attribute, null);
+            }
+        }
+
+        @Override
+        public void onException(Exception exception) {
+            log.error("Detected exception while retrieving Chef attributes from entity " + entity.getDisplayName(), exception);
+            for (AttributeSensor<?> attribute : chefAttributeSensors.values()) {
+                if (!attribute.getName().startsWith(CHEF_ATTRIBUTE_PREFIX))
+                    continue;
+                entity.setAttribute(attribute, null);
+            }
+        }
+        
+        @Override
+        public String toString() {
+            return super.toString()+"["+getDescription()+"]";
+        }
+        
+        @Override
+        public String getDescription() {
+            return ""+chefAttributeSensors;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefAttributePollConfig.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefAttributePollConfig.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefAttributePollConfig.java
new file mode 100644
index 0000000..c6e1c6b
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefAttributePollConfig.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.sensor.feed.PollConfig;
+
+import com.google.common.base.Function;
+import com.google.common.base.Functions;
+
+public class ChefAttributePollConfig<T> extends PollConfig<Object, T, ChefAttributePollConfig<T>>{
+
+    private String chefAttributePath;
+
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public ChefAttributePollConfig(AttributeSensor<T> sensor) {
+        super(sensor);
+        onSuccess((Function)Functions.identity());
+    }
+
+    public ChefAttributePollConfig(ChefAttributePollConfig<T> other) {
+        super(other);
+        this.chefAttributePath = other.chefAttributePath;
+    }
+
+    public String getChefAttributePath() {
+        return chefAttributePath;
+    }
+    
+    public ChefAttributePollConfig<T> chefAttributePath(String val) {
+        this.chefAttributePath = val; return this;
+    }
+    
+    @Override protected String toStringBaseName() { return "chef"; }
+    @Override protected String toStringPollSource() { return chefAttributePath; }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefBashCommands.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefBashCommands.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefBashCommands.java
new file mode 100644
index 0000000..dde58d3
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefBashCommands.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+import static org.apache.brooklyn.util.ssh.BashCommands.INSTALL_CURL;
+import static org.apache.brooklyn.util.ssh.BashCommands.INSTALL_TAR;
+import static org.apache.brooklyn.util.ssh.BashCommands.INSTALL_UNZIP;
+import static org.apache.brooklyn.util.ssh.BashCommands.downloadToStdout;
+import static org.apache.brooklyn.util.ssh.BashCommands.sudo;
+
+import org.apache.brooklyn.util.ssh.BashCommands;
+
+import com.google.common.annotations.Beta;
+
+/** BASH commands useful for setting up Chef */
+@Beta
+public class ChefBashCommands {
+
+    public static final String INSTALL_FROM_OPSCODE =
+            BashCommands.chain(
+                    INSTALL_CURL,
+                    INSTALL_TAR,
+                    INSTALL_UNZIP,
+                    "( "+downloadToStdout("https://www.opscode.com/chef/install.sh") + " | " + sudo("bash")+" )");
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefConfig.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefConfig.java b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefConfig.java
new file mode 100644
index 0000000..974149e
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/chef/ChefConfig.java
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.config.MapConfigKey;
+import org.apache.brooklyn.core.config.SetConfigKey;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+
+import com.google.common.annotations.Beta;
+
+/** {@link ConfigKey}s used to configure the chef driver */
+@Beta
+public interface ChefConfig {
+
+    public static final ConfigKey<String> CHEF_COOKBOOK_PRIMARY_NAME = ConfigKeys.newStringConfigKey("brooklyn.chef.cookbook.primary.name",
+        "Namespace to use for passing data to Chef and for finding effectors");
+    
+    @Deprecated /** @deprecatd since 0.7.0 use #CHEF_COOKBOOK_URLS */
+    @SetFromFlag("cookbooks")
+    public static final MapConfigKey<String> CHEF_COOKBOOKS = new MapConfigKey<String>(String.class, "brooklyn.chef.cookbooksUrls");
+
+    @SetFromFlag("cookbook_urls")
+    public static final MapConfigKey<String> CHEF_COOKBOOK_URLS = new MapConfigKey<String>(String.class, "brooklyn.chef.cookbooksUrls");
+
+    @SetFromFlag("converge_twice")
+    public static final ConfigKey<Boolean> CHEF_RUN_CONVERGE_TWICE = ConfigKeys.newBooleanConfigKey("brooklyn.chef.converge.twice",
+            "Whether to run converge commands twice if the first one fails; needed in some contexts, e.g. when switching between chef-server and chef-solo mode", false);
+
+    @Deprecated /** @deprecated since 0.7.0 use #CHEF_LAUNCH_RUN_LIST */
+    public static final SetConfigKey<String> CHEF_RUN_LIST = new SetConfigKey<String>(String.class, "brooklyn.chef.runList");
+    
+    /** typically set from spec, to customize the launch part of the start effector */
+    @SetFromFlag("launch_run_list")
+    public static final SetConfigKey<String> CHEF_LAUNCH_RUN_LIST = new SetConfigKey<String>(String.class, "brooklyn.chef.launch.runList");
+    /** typically set from spec, to customize the launch part of the start effector */
+    @SetFromFlag("launch_attributes")
+    public static final MapConfigKey<Object> CHEF_LAUNCH_ATTRIBUTES = new MapConfigKey<Object>(Object.class, "brooklyn.chef.launch.attributes");
+    
+    public static enum ChefModes {
+        /** Force use of Chef Solo */
+        SOLO, 
+        /** Force use of Knife; knife must be installed, and either 
+         *  {@link ChefConfig#KNIFE_EXECUTABLE} and {@link ChefConfig#KNIFE_CONFIG_FILE} must be set 
+         *  or knife on the path with valid global config set up */
+        KNIFE,
+        // TODO server via API
+        /** Tries {@link #KNIFE} if valid, else {@link #SOLO} */
+        AUTODETECT
+    };
+
+    @SetFromFlag("chef_mode")
+    public static final ConfigKey<ChefModes> CHEF_MODE = ConfigKeys.newConfigKey(ChefModes.class, "brooklyn.chef.mode",
+            "Whether Chef should run in solo mode, knife mode, or auto-detect", ChefModes.AUTODETECT);
+
+    // TODO server-url for server via API mode
+    
+    public static final ConfigKey<String> KNIFE_SETUP_COMMANDS = ConfigKeys.newStringConfigKey("brooklyn.chef.knife.setupCommands",
+            "An optional set of commands to run on localhost before invoking knife; useful if using ruby version manager for example");
+    public static final ConfigKey<String> KNIFE_EXECUTABLE = ConfigKeys.newStringConfigKey("brooklyn.chef.knife.executableFile",
+            "Knife command to run on the Brooklyn machine, including full path; defaults to scanning the path");
+    public static final ConfigKey<String> KNIFE_CONFIG_FILE = ConfigKeys.newStringConfigKey("brooklyn.chef.knife.configFile",
+            "Knife config file (typically knife.rb) to use, including full path; defaults to knife default/global config");
+
+    @SetFromFlag("chef_node_name")
+    public static final ConfigKey<String> CHEF_NODE_NAME = ConfigKeys.newStringConfigKey("brooklyn.chef.node.nodeName",
+        "Node name to register with the chef server for this entity, if using Chef server and a specific node name is desired; "
+        + "if supplied ,this must be unique across the nodes Chef Server manages; if not supplied, one will be created if needed");
+
+    // for providing some simple (ssh-based) lifecycle operations and checks
+    @SetFromFlag("pid_file")
+    public static final ConfigKey<String> PID_FILE = ConfigKeys.newStringConfigKey("brooklyn.chef.lifecycle.pidFile",
+        "Path to PID file on remote machine, for use in checking running and stopping; may contain wildcards");
+    @SetFromFlag("service_name")
+    public static final ConfigKey<String> SERVICE_NAME = ConfigKeys.newStringConfigKey("brooklyn.chef.lifecycle.serviceName",
+        "Name of OS service this will run as, for use in checking running and stopping");
+    @SetFromFlag("windows_service_name")
+    public static final ConfigKey<String> WINDOWS_SERVICE_NAME = ConfigKeys.newStringConfigKey("brooklyn.chef.lifecycle.windowsServiceName",
+        "Name of OS service this will run as on Windows, if different there, for use in checking running and stopping");
+    
+}


[52/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/InMemoryObjectStore.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/InMemoryObjectStore.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/InMemoryObjectStore.java
deleted file mode 100644
index b0467fd..0000000
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/InMemoryObjectStore.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.StoreObjectAccessorLocking;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Objects;
-
-public class InMemoryObjectStore implements PersistenceObjectStore {
-
-    private static final Logger log = LoggerFactory.getLogger(InMemoryObjectStore.class);
-
-    final Map<String,String> filesByName;
-    final Map<String, Date> fileModTimesByName;
-    boolean prepared = false;
-    
-    public InMemoryObjectStore() {
-        this(MutableMap.<String,String>of(), MutableMap.<String,Date>of());
-    }
-    
-    public InMemoryObjectStore(Map<String,String> map, Map<String, Date> fileModTimesByName) {
-        filesByName = map;
-        this.fileModTimesByName = fileModTimesByName;
-        log.debug("Using memory-based objectStore");
-    }
-    
-    @Override
-    public String getSummaryName() {
-        return "in-memory (test) persistence store";
-    }
-    
-    @Override
-    public void prepareForMasterUse() {
-    }
-
-    @Override
-    public void createSubPath(String subPath) {
-    }
-
-    @Override
-    public StoreObjectAccessor newAccessor(final String path) {
-        if (!prepared) throw new IllegalStateException("prepare method not yet invoked: "+this);
-        return new StoreObjectAccessorLocking(new SingleThreadedInMemoryStoreObjectAccessor(filesByName, fileModTimesByName, path));
-    }
-    
-    public static class SingleThreadedInMemoryStoreObjectAccessor implements StoreObjectAccessor {
-        private final Map<String, String> map;
-        private final Map<String, Date> mapModTime;
-        private final String key;
-
-        public SingleThreadedInMemoryStoreObjectAccessor(Map<String,String> map, Map<String, Date> mapModTime, String key) {
-            this.map = map;
-            this.mapModTime = mapModTime;
-            this.key = key;
-        }
-        @Override
-        public String get() {
-            synchronized (map) {
-                return map.get(key);
-            }
-        }
-        @Override
-        public byte[] getBytes() {
-            return get().getBytes();
-        }
-        @Override
-        public boolean exists() {
-            synchronized (map) {
-                return map.containsKey(key);
-            }
-        }
-        @Override
-        public void put(String val) {
-            synchronized (map) {
-                map.put(key, val);
-                mapModTime.put(key, new Date());
-            }
-        }
-        @Override
-        public void append(String val) {
-            synchronized (map) {
-                String val2 = get();
-                if (val2==null) val2 = val;
-                else val2 = val2 + val;
-
-                map.put(key, val2);
-                mapModTime.put(key, new Date());
-            }
-        }
-        @Override
-        public void delete() {
-            synchronized (map) {
-                map.remove(key);
-                mapModTime.remove(key);
-            }
-        }
-        @Override
-        public Date getLastModifiedDate() {
-            synchronized (map) {
-                return mapModTime.get(key);
-            }
-        }
-    }
-
-    @Override
-    public List<String> listContentsWithSubPath(final String parentSubPath) {
-        if (!prepared) throw new IllegalStateException("prepare method not yet invoked: "+this);
-        synchronized (filesByName) {
-            List<String> result = MutableList.of();
-            for (String file: filesByName.keySet())
-                if (file.startsWith(parentSubPath))
-                    result.add(file);
-            return result;
-        }
-    }
-
-    @Override
-    public void close() {
-    }
-
-    @Override
-    public String toString() {
-        return Objects.toStringHelper(this).add("size", filesByName.size()).toString();
-    }
-
-    @Override
-    public void injectManagementContext(ManagementContext mgmt) {
-    }
-    
-    @Override
-    public void prepareForSharedUse(PersistMode persistMode, HighAvailabilityMode haMode) {
-        prepared = true;
-    }
-
-    @Override
-    public void deleteCompletely() {
-        synchronized (filesByName) {
-            filesByName.clear();
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/InMemoryStoreObjectAccessorWriterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/InMemoryStoreObjectAccessorWriterTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/InMemoryStoreObjectAccessorWriterTest.java
deleted file mode 100644
index 01c6399..0000000
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/InMemoryStoreObjectAccessorWriterTest.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import java.io.IOException;
-
-import org.apache.brooklyn.core.mgmt.rebind.persister.StoreObjectAccessorLocking;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore.StoreObjectAccessorWithLock;
-import org.testng.annotations.Test;
-
-@Test
-public class InMemoryStoreObjectAccessorWriterTest extends PersistenceStoreObjectAccessorWriterTestFixture {
-
-    protected StoreObjectAccessorWithLock newPersistenceStoreObjectAccessor() throws IOException {
-        InMemoryObjectStore store = new InMemoryObjectStore();
-        store.prepareForSharedUse(null, null);
-        return new StoreObjectAccessorLocking(store.newAccessor("foo"));
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/ListeningObjectStore.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/ListeningObjectStore.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/ListeningObjectStore.java
deleted file mode 100644
index 374ec74..0000000
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/ListeningObjectStore.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import java.util.Date;
-import java.util.List;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicLong;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.time.CountdownTimer;
-import org.apache.brooklyn.util.time.Duration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Preconditions;
-
-public class ListeningObjectStore implements PersistenceObjectStore {
-
-    protected final PersistenceObjectStore delegate;
-    protected final List<ObjectStoreTransactionListener> listeners = MutableList.of();
-    private boolean writesFailSilently = false;
-
-    public static interface ObjectStoreTransactionListener {
-        public void recordQueryOut(String summary, int size);
-        public void recordDataOut(String summary, int size);
-        public void recordDataIn(String summary, int size);
-    }
-    
-    public static class RecordingTransactionListener implements ObjectStoreTransactionListener {
-        private static final Logger log = LoggerFactory.getLogger(ListeningObjectStore.RecordingTransactionListener.class);
-        
-        protected final String prefix;
-        protected final AtomicLong bytesIn = new AtomicLong();
-        protected final AtomicLong bytesOut = new AtomicLong();
-        protected final AtomicInteger countQueriesOut = new AtomicInteger();
-        protected final AtomicInteger countDataOut = new AtomicInteger();
-        protected final AtomicInteger countDataIn = new AtomicInteger();
-        
-        public RecordingTransactionListener(String prefix) {
-            this.prefix = prefix;
-        }
-        
-        public long getBytesIn() {
-            return bytesIn.get();
-        }
-        
-        public long getBytesOut() {
-            return bytesOut.get();
-        }
-        
-        public int getCountQueriesOut() {
-            return countQueriesOut.get();
-        }
-        
-        public int getCountDataOut() {
-            return countDataOut.get();
-        }
-        
-        public int getCountDataIn() {
-            return countDataIn.get();
-        }
-        
-        public String getTotalString() {
-            return "totals: out="+Strings.makeSizeString(bytesOut.get())+" in="+Strings.makeSizeString(bytesIn.get());
-        }
-        
-        @Override
-        public void recordQueryOut(String summary, int size) {
-            synchronized (this) { this.notifyAll(); }
-            bytesOut.addAndGet(size);
-            countQueriesOut.incrementAndGet();
-            log.info(prefix+" "+summary+" -->"+size+"; "+getTotalString());
-        }
-        
-        @Override
-        public void recordDataOut(String summary, int size) {
-            synchronized (this) { this.notifyAll(); }
-            bytesOut.addAndGet(size);
-            countDataOut.incrementAndGet();
-            log.info(prefix+" "+summary+" -->"+size+"; "+getTotalString());
-        }
-        
-        @Override
-        public void recordDataIn(String summary, int size) {
-            synchronized (this) { this.notifyAll(); }
-            bytesIn.addAndGet(size);
-            countDataIn.incrementAndGet();
-            log.info(prefix+" "+summary+" <--"+size+"; "+getTotalString());
-        }
-
-        public void blockUntilDataWrittenExceeds(long count, Duration timeout) throws InterruptedException, TimeoutException {
-            CountdownTimer timer = CountdownTimer.newInstanceStarted(timeout);
-            synchronized (this) {
-                while (bytesOut.get()<count) {
-                    if (timer.isExpired())
-                        throw new TimeoutException();
-                    timer.waitOnForExpiry(this);
-                }
-            }
-        }
-    }
-
-    public ListeningObjectStore(PersistenceObjectStore delegate, ObjectStoreTransactionListener ...listeners) {
-        this.delegate = Preconditions.checkNotNull(delegate);
-        for (ObjectStoreTransactionListener listener: listeners)
-            this.listeners.add(listener);
-    }
-
-    @Override
-    public String getSummaryName() {
-        return delegate.getSummaryName();
-    }
-
-    @Override
-    public void prepareForMasterUse() {
-        delegate.prepareForMasterUse();
-    }
-
-    @Override
-    public StoreObjectAccessor newAccessor(String path) {
-        return new ListeningAccessor(path, delegate.newAccessor(path));
-    }
-
-    @Override
-    public void createSubPath(String subPath) {
-        if (writesFailSilently)
-            return;
-        
-        for (ObjectStoreTransactionListener listener: listeners)
-            listener.recordQueryOut("creating path "+subPath, 1+subPath.length());
-        delegate.createSubPath(subPath);
-    }
-
-    @Override
-    public List<String> listContentsWithSubPath(String subPath) {
-        for (ObjectStoreTransactionListener listener: listeners)
-            listener.recordQueryOut("requesting list "+subPath, 1+subPath.length());
-        
-        List<String> result = delegate.listContentsWithSubPath(subPath);
-        
-        for (ObjectStoreTransactionListener listener: listeners)
-            listener.recordDataIn("receiving list "+subPath, result.toString().length());
-        return result;
-    }
-
-    @Override
-    public void close() {
-        delegate.close();
-    }
-
-    @Override
-    public void injectManagementContext(ManagementContext managementContext) {
-        delegate.injectManagementContext(managementContext);
-    }
-    
-    @Override
-    public void prepareForSharedUse(PersistMode persistMode, HighAvailabilityMode haMode) {
-        delegate.prepareForSharedUse(persistMode, haMode);
-    }
-
-    @Override
-    public void deleteCompletely() {
-        for (ObjectStoreTransactionListener listener: listeners)
-            listener.recordDataOut("deleting completely", 1);
-        delegate.deleteCompletely();
-    }
-
-    public class ListeningAccessor implements StoreObjectAccessor {
-
-        protected final String path;
-        protected final StoreObjectAccessor delegate;
-        
-        public ListeningAccessor(String path, StoreObjectAccessor delegate) {
-            this.path = path;
-            this.delegate = delegate;
-        }
-        @Override
-        public boolean exists() {
-            return delegate.exists();
-        }
-        @Override
-        public void put(String val) {
-            if (writesFailSilently)
-                return;
-
-            for (ObjectStoreTransactionListener listener: listeners)
-                listener.recordDataOut("writing "+path, val.length());
-            delegate.put(val);
-        }
-        @Override
-        public void append(String s) {
-            if (writesFailSilently)
-                return;
-
-            for (ObjectStoreTransactionListener listener: listeners)
-                listener.recordDataOut("appending "+path, s.length());
-            delegate.append(s);
-        }
-        @Override
-        public void delete() {
-            if (writesFailSilently)
-                return;
-
-            for (ObjectStoreTransactionListener listener: listeners)
-                listener.recordQueryOut("deleting "+path, path.length());
-            delegate.delete();
-        }
-        @Override
-        public String get() {
-            for (ObjectStoreTransactionListener listener: listeners)
-                listener.recordQueryOut("requesting "+path, path.length());
-            String result = delegate.get();
-            
-            for (ObjectStoreTransactionListener listener: listeners)
-                listener.recordDataIn("reading "+path, (result==null ? 0 : result.length()));
-            return result;
-        }
-        @Override
-        public byte[] getBytes() {
-            return get().getBytes();
-        }
-        @Override
-        public Date getLastModifiedDate() {
-            return delegate.getLastModifiedDate();
-        }
-    }
-
-    public void setWritesFailSilently(boolean writesFailSilently) {
-        this.writesFailSilently = writesFailSilently;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/PersistenceStoreObjectAccessorWriterTestFixture.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/PersistenceStoreObjectAccessorWriterTestFixture.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/PersistenceStoreObjectAccessorWriterTestFixture.java
deleted file mode 100644
index 27cbf25..0000000
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/PersistenceStoreObjectAccessorWriterTestFixture.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
-import java.io.IOException;
-import java.util.Date;
-import java.util.concurrent.Executors;
-
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore.StoreObjectAccessorWithLock;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-
-public abstract class PersistenceStoreObjectAccessorWriterTestFixture {
-
-    private static final Duration TIMEOUT = Duration.TEN_SECONDS;
-    
-    protected ListeningExecutorService executor;
-    protected StoreObjectAccessorWithLock accessor;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
-        accessor = newPersistenceStoreObjectAccessor();
-    }
-
-    protected abstract StoreObjectAccessorWithLock newPersistenceStoreObjectAccessor() throws IOException;
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (accessor != null) {
-            accessor.delete();
-            accessor.waitForCurrentWrites(Duration.TEN_SECONDS);
-        }
-        if (executor != null) executor.shutdownNow();
-    }
-
-    @Test
-    public void testWritesFile() throws Exception {
-        accessor.put("abc");
-        accessor.waitForCurrentWrites(TIMEOUT);
-
-        assertEquals(accessor.get(), "abc");
-    }
-
-    @Test
-    public void testExists() throws Exception {
-        accessor.put("abc");
-        accessor.waitForCurrentWrites(TIMEOUT);
-        assertTrue(accessor.exists());
-        
-        accessor.delete();
-        accessor.waitForCurrentWrites(TIMEOUT);
-        assertFalse(accessor.exists());
-    }
-    
-    @Test
-    public void testAppendsFile() throws Exception {
-        accessor.put("abc\n");
-        accessor.append("def\n");
-        accessor.waitForCurrentWrites(TIMEOUT);
-
-        assertEquals(accessor.get(), "abc\ndef\n");
-    }
-
-    /** most storage systems support <= 1ms resolution; but some file systems -- esp FAT and OSX HFS+ are much much higher! */
-    protected Duration getLastModifiedResolution() {
-        return Duration.millis(1);
-    }
-    
-    @Test
-    public void testLastModifiedTime() throws Exception {
-        accessor.delete();
-        Assert.assertNull(accessor.getLastModifiedDate());
-        accessor.put("abc");
-        accessor.waitForCurrentWrites(TIMEOUT);
-        Date write1 = accessor.getLastModifiedDate();
-        Assert.assertNotNull(write1);
-        
-        Time.sleep(getLastModifiedResolution().times(2));
-        accessor.put("abc");
-        accessor.waitForCurrentWrites(TIMEOUT);
-        Date write2 = accessor.getLastModifiedDate();
-        Assert.assertNotNull(write2);
-        Assert.assertTrue(write2.after(write1), "dates are "+write1+" ("+write1.getTime()+") and "+write2+" ("+write2.getTime()+") ");
-    }
-    
-    @Test
-    public void testWriteBacklogThenDeleteWillLeaveFileDeleted() throws Exception {
-        String big = makeBigString(biggishSize());
-        
-        accessor.put(big);
-        accessor.put(big);
-        accessor.delete();
-        
-        accessor.waitForCurrentWrites(TIMEOUT);
-        assertFalse(accessor.exists());
-    }
-
-    protected int biggishSize() {
-        return 100000;
-    }
-    
-    protected String makeBigString(int size) {
-        // prefer non-random so can't be compressed
-        return Identifiers.makeRandomBase64Id(size);
-//        return com.google.common.base.Strings.repeat("x", size);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/XmlMementoSerializerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/XmlMementoSerializerTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/XmlMementoSerializerTest.java
deleted file mode 100644
index 6cf46d7..0000000
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/XmlMementoSerializerTest.java
+++ /dev/null
@@ -1,455 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import static org.testng.Assert.assertEquals;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Set;
-
-import org.apache.brooklyn.location.basic.SimulatedLocation;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.test.TestResourceUnavailableException;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.collections.MutableSet;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.api.catalog.CatalogItem;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoPersister.LookupContext;
-import org.apache.brooklyn.api.objs.BrooklynObject;
-import org.apache.brooklyn.api.objs.BrooklynObjectType;
-import org.apache.brooklyn.api.policy.Policy;
-import org.apache.brooklyn.api.sensor.Enricher;
-import org.apache.brooklyn.api.sensor.Feed;
-import org.apache.brooklyn.core.catalog.internal.CatalogItemBuilder;
-import org.apache.brooklyn.core.catalog.internal.CatalogItemDtoAbstract;
-import org.apache.brooklyn.core.catalog.internal.CatalogTestUtils;
-import org.apache.brooklyn.core.mgmt.osgi.OsgiTestResources;
-import org.apache.brooklyn.core.mgmt.osgi.OsgiVersionMoreEntityTest;
-import org.apache.brooklyn.core.mgmt.rebind.persister.XmlMementoSerializer;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.group.DynamicCluster;
-
-import com.google.common.base.Objects;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Maps;
-
-public class XmlMementoSerializerTest {
-
-    private static final Logger LOG = LoggerFactory.getLogger(XmlMementoSerializerTest.class);
-
-    private XmlMementoSerializer<Object> serializer;
-
-    @BeforeMethod(alwaysRun=true)
-    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 testArraysAsList() throws Exception {
-        // For some reason Arrays.asList used in the catalog's libraries can't be deserialized correctly,
-        // but here works perfectly - the generated catalog xml contains
-        //    <libraries class="list">
-        //      <a ...>
-        //        <bundle....>
-        // which is deserialized as an ArrayList with a single member array of bundles.
-        // The cause is the class="list" type which should be java.util.Arrays$ArrayList instead.
-        Collection<String> obj = Arrays.asList("a", "b");
-        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 testClass() throws Exception {
-        Class<?> t = XmlMementoSerializer.class;
-        assertSerializeAndDeserialize(t);
-    }
-
-    @Test
-    public void testEntity() throws Exception {
-        final TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
-        ManagementContext managementContext = app.getManagementContext();
-        try {
-            serializer.setLookupContext(new LookupContextImpl(managementContext,
-                    ImmutableList.of(app), ImmutableList.<Location>of(), ImmutableList.<Policy>of(),
-                    ImmutableList.<Enricher>of(), ImmutableList.<Feed>of(), ImmutableList.<CatalogItem<?, ?>>of(), true));
-            assertSerializeAndDeserialize(app);
-        } finally {
-            Entities.destroyAll(managementContext);
-        }
-    }
-
-    @Test
-    public void testLocation() throws Exception {
-        final TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
-        ManagementContext managementContext = app.getManagementContext();
-        try {
-            @SuppressWarnings("deprecation")
-            final Location loc = managementContext.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class));
-            serializer.setLookupContext(new LookupContextImpl(managementContext,
-                    ImmutableList.<Entity>of(), ImmutableList.of(loc), ImmutableList.<Policy>of(),
-                    ImmutableList.<Enricher>of(), ImmutableList.<Feed>of(), ImmutableList.<CatalogItem<?, ?>>of(), true));
-            assertSerializeAndDeserialize(loc);
-        } finally {
-            Entities.destroyAll(managementContext);
-        }
-    }
-
-    @Test
-    public void testCatalogItem() throws Exception {
-        final TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
-        ManagementContext managementContext = app.getManagementContext();
-        try {
-            CatalogItem<?, ?> catalogItem = CatalogItemBuilder.newEntity("symbolicName", "0.0.1")
-                    .displayName("test catalog item")
-                    .description("description")
-                    .plan("yaml plan")
-                    .iconUrl("iconUrl")
-                    .libraries(CatalogItemDtoAbstract.parseLibraries(ImmutableList.of("library-url")))
-                    .build();
-            serializer.setLookupContext(new LookupContextImpl(managementContext,
-                    ImmutableList.<Entity>of(), ImmutableList.<Location>of(), ImmutableList.<Policy>of(),
-                    ImmutableList.<Enricher>of(), ImmutableList.<Feed>of(), ImmutableList.of(catalogItem), true));
-            assertSerializeAndDeserialize(catalogItem);
-        } finally {
-            Entities.destroyAll(managementContext);
-        }
-    }
-
-    @Test
-    public void testEntitySpec() throws Exception {
-        EntitySpec<?> obj = EntitySpec.create(TestEntity.class);
-        assertSerializeAndDeserialize(obj);
-    }
-    
-    @Test
-    public void testEntitySpecFromOsgi() throws Exception {
-        TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), OsgiTestResources.BROOKLYN_TEST_MORE_ENTITIES_V1_PATH);
-        ManagementContext mgmt = LocalManagementContextForTests.builder(true).disableOsgi(false).build();
-        try {
-            CatalogItem<?, ?> ci = OsgiVersionMoreEntityTest.addMoreEntityV1(mgmt, "1.0");
-            
-            EntitySpec<DynamicCluster> spec = EntitySpec.create(DynamicCluster.class)
-                .configure(DynamicCluster.INITIAL_SIZE, 1)
-                .configure(DynamicCluster.MEMBER_SPEC, CatalogTestUtils.createEssentialEntitySpec(mgmt, ci));
-    
-            serializer.setLookupContext(new LookupContextImpl(mgmt,
-                ImmutableList.<Entity>of(), ImmutableList.<Location>of(), ImmutableList.<Policy>of(),
-                ImmutableList.<Enricher>of(), ImmutableList.<Feed>of(), ImmutableList.<CatalogItem<?,?>>of(), true));
-            assertSerializeAndDeserialize(spec);
-        } finally {
-            Entities.destroyAllCatching(mgmt);
-        }
-    }
-
-    @Test
-    public void testImmutableCollectionsWithDanglingEntityRef() throws Exception {
-        // If there's a dangling entity in an ImmutableList etc, then discard it entirely.
-        // If we try to insert null then it fails, breaking the deserialization of that entire file.
-        
-        final TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
-        final TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
-        ManagementContext managementContext = app.getManagementContext();
-        try {
-            serializer.setLookupContext(new LookupContextImpl(managementContext,
-                    ImmutableList.of(app), ImmutableList.<Location>of(), ImmutableList.<Policy>of(),
-                    ImmutableList.<Enricher>of(), ImmutableList.<Feed>of(), ImmutableList.<CatalogItem<?, ?>>of(), false));
-            
-            List<?> resultList = serializeAndDeserialize(ImmutableList.of(app, entity));
-            assertEquals(resultList, ImmutableList.of(app));
-            
-            Set<?> resultSet = serializeAndDeserialize(ImmutableSet.of(app, entity));
-            assertEquals(resultSet, ImmutableSet.of(app));
-            
-            Map<?, ?> resultMap = serializeAndDeserialize(ImmutableMap.of(app, "appval", "appkey", app, entity, "entityval", "entityKey", entity));
-            assertEquals(resultMap, ImmutableMap.of(app, "appval", "appkey", app));
-
-        } finally {
-            Entities.destroyAll(managementContext);
-        }
-    }
-
-    @Test
-    public void testFieldReffingEntity() throws Exception {
-        final TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
-        ReffingEntity reffer = new ReffingEntity(app);
-        ManagementContext managementContext = app.getManagementContext();
-        try {
-            serializer.setLookupContext(new LookupContextImpl(managementContext,
-                    ImmutableList.of(app), ImmutableList.<Location>of(), ImmutableList.<Policy>of(),
-                    ImmutableList.<Enricher>of(), ImmutableList.<Feed>of(), ImmutableList.<CatalogItem<?, ?>>of(), true));
-            ReffingEntity reffer2 = assertSerializeAndDeserialize(reffer);
-            assertEquals(reffer2.entity, app);
-        } finally {
-            Entities.destroyAll(managementContext);
-        }
-    }
-
-    @Test
-    public void testUntypedFieldReffingEntity() throws Exception {
-        final TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
-        ReffingEntity reffer = new ReffingEntity((Object)app);
-        ManagementContext managementContext = app.getManagementContext();
-        try {
-            serializer.setLookupContext(new LookupContextImpl(managementContext,
-                    ImmutableList.of(app), ImmutableList.<Location>of(), ImmutableList.<Policy>of(),
-                    ImmutableList.<Enricher>of(), ImmutableList.<Feed>of(), ImmutableList.<CatalogItem<?, ?>>of(), true));
-            ReffingEntity reffer2 = assertSerializeAndDeserialize(reffer);
-            assertEquals(reffer2.obj, app);
-        } finally {
-            Entities.destroyAll(managementContext);
-        }
-    }
-
-    public static class ReffingEntity {
-        public Entity entity;
-        public Object obj;
-        public ReffingEntity(Entity entity) {
-            this.entity = entity;
-        }
-        public ReffingEntity(Object obj) {
-            this.obj = obj;
-        }
-        @Override
-        public boolean equals(Object o) {
-            return (o instanceof ReffingEntity) && Objects.equal(entity, ((ReffingEntity)o).entity) && Objects.equal(obj, ((ReffingEntity)o).obj);
-        }
-        @Override
-        public int hashCode() {
-            return Objects.hashCode(entity, obj);
-        }
-    }
-
-    @SuppressWarnings("unchecked")
-    private <T> T assertSerializeAndDeserialize(T obj) throws Exception {
-        String serializedForm = serializer.toString(obj);
-        LOG.info("serializedForm=" + serializedForm);
-        Object deserialized = serializer.fromString(serializedForm);
-        assertEquals(deserialized, obj, "serializedForm="+serializedForm);
-        return (T) deserialized;
-    }
-
-    @SuppressWarnings("unchecked")
-    private <T> T serializeAndDeserialize(T obj) throws Exception {
-        String serializedForm = serializer.toString(obj);
-        LOG.info("serializedForm=" + serializedForm);
-        return (T) serializer.fromString(serializedForm);
-    }
-
-    static class LookupContextImpl implements LookupContext {
-        private final ManagementContext mgmt;
-        private final Map<String, Entity> entities;
-        private final Map<String, Location> locations;
-        private final Map<String, Policy> policies;
-        private final Map<String, Enricher> enrichers;
-        private final Map<String, Feed> feeds;
-        private final Map<String, CatalogItem<?, ?>> catalogItems;
-        private final boolean failOnDangling;
-
-        LookupContextImpl(ManagementContext mgmt, Iterable<? extends Entity> entities, Iterable<? extends Location> locations,
-                Iterable<? extends Policy> policies, Iterable<? extends Enricher> enrichers, Iterable<? extends Feed> feeds,
-                Iterable<? extends CatalogItem<?, ?>> catalogItems, boolean failOnDangling) {
-            this.mgmt = mgmt;
-            this.entities = Maps.newLinkedHashMap();
-            this.locations = Maps.newLinkedHashMap();
-            this.policies = Maps.newLinkedHashMap();
-            this.enrichers = Maps.newLinkedHashMap();
-            this.feeds = Maps.newLinkedHashMap();
-            this.catalogItems = Maps.newLinkedHashMap();
-            for (Entity entity : entities) this.entities.put(entity.getId(), entity);
-            for (Location location : locations) this.locations.put(location.getId(), location);
-            for (Policy policy : policies) this.policies.put(policy.getId(), policy);
-            for (Enricher enricher : enrichers) this.enrichers.put(enricher.getId(), enricher);
-            for (Feed feed : feeds) this.feeds.put(feed.getId(), feed);
-            for (CatalogItem<?, ?> catalogItem : catalogItems) this.catalogItems.put(catalogItem.getId(), catalogItem);
-            this.failOnDangling = failOnDangling;
-        }
-        LookupContextImpl(ManagementContext mgmt, Map<String,? extends Entity> entities, Map<String,? extends Location> locations,
-                Map<String,? extends Policy> policies, Map<String,? extends Enricher> enrichers, Map<String,? extends Feed> feeds,
-                Map<String, ? extends CatalogItem<?, ?>> catalogItems, boolean failOnDangling) {
-            this.mgmt = mgmt;
-            this.entities = ImmutableMap.copyOf(entities);
-            this.locations = ImmutableMap.copyOf(locations);
-            this.policies = ImmutableMap.copyOf(policies);
-            this.enrichers = ImmutableMap.copyOf(enrichers);
-            this.feeds = ImmutableMap.copyOf(feeds);
-            this.catalogItems = ImmutableMap.copyOf(catalogItems);
-            this.failOnDangling = failOnDangling;
-        }
-        @Override public ManagementContext lookupManagementContext() {
-            return mgmt;
-        }
-        @Override public Entity lookupEntity(String id) {
-            if (entities.containsKey(id)) {
-                return entities.get(id);
-            }
-            if (failOnDangling) {
-                throw new NoSuchElementException("no entity with id "+id+"; contenders are "+entities.keySet());
-            }
-            return null;
-        }
-        @Override public Location lookupLocation(String id) {
-            if (locations.containsKey(id)) {
-                return locations.get(id);
-            }
-            if (failOnDangling) {
-                throw new NoSuchElementException("no location with id "+id+"; contenders are "+locations.keySet());
-            }
-            return null;
-        }
-        @Override public Policy lookupPolicy(String id) {
-            if (policies.containsKey(id)) {
-                return policies.get(id);
-            }
-            if (failOnDangling) {
-                throw new NoSuchElementException("no policy with id "+id+"; contenders are "+policies.keySet());
-            }
-            return null;
-        }
-        @Override public Enricher lookupEnricher(String id) {
-            if (enrichers.containsKey(id)) {
-                return enrichers.get(id);
-            }
-            if (failOnDangling) {
-                throw new NoSuchElementException("no enricher with id "+id+"; contenders are "+enrichers.keySet());
-            }
-            return null;
-        }
-        @Override public Feed lookupFeed(String id) {
-            if (feeds.containsKey(id)) {
-                return feeds.get(id);
-            }
-            if (failOnDangling) {
-                throw new NoSuchElementException("no feed with id "+id+"; contenders are "+feeds.keySet());
-            }
-            return null;
-        }
-        @Override public CatalogItem<?, ?> lookupCatalogItem(String id) {
-            if (catalogItems.containsKey(id)) {
-                return catalogItems.get(id);
-            }
-            if (failOnDangling) {
-                throw new NoSuchElementException("no catalog item with id "+id+"; contenders are "+catalogItems.keySet());
-            }
-            return null;
-        }
-        
-        @Override
-        public BrooklynObject lookup(BrooklynObjectType type, String id) {
-            switch (type) {
-            case CATALOG_ITEM: return lookupCatalogItem(id);
-            case ENRICHER: return lookupEnricher(id);
-            case ENTITY: return lookupEntity(id);
-            case FEED: return lookupFeed(id);
-            case LOCATION: return lookupLocation(id);
-            case POLICY: return lookupPolicy(id);
-            case UNKNOWN: return null;
-            }
-            throw new IllegalStateException("Unexpected type "+type+" / id "+id);
-        }
-        @Override
-        public BrooklynObject peek(BrooklynObjectType type, String id) {
-            switch (type) {
-            case CATALOG_ITEM: return catalogItems.get(id);
-            case ENRICHER: return enrichers.get(id);
-            case ENTITY: return entities.get(id);
-            case FEED: return feeds.get(id);
-            case LOCATION: return locations.get(id);
-            case POLICY: return policies.get(id);
-            case UNKNOWN: return null;
-            }
-            throw new IllegalStateException("Unexpected type "+type+" / id "+id);
-        }
-    };
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/transformer/CompoundTransformerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/transformer/CompoundTransformerTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/transformer/CompoundTransformerTest.java
index 6cf8216..ae87123 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/transformer/CompoundTransformerTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/transformer/CompoundTransformerTest.java
@@ -36,14 +36,14 @@ import org.apache.brooklyn.api.objs.BrooklynObjectType;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.BasicConfigKey;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.FileBasedObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
 import org.apache.brooklyn.core.mgmt.rebind.PersistenceExceptionHandlerImpl;
 import org.apache.brooklyn.core.mgmt.rebind.RebindOptions;
 import org.apache.brooklyn.core.mgmt.rebind.RebindTestFixtureWithApp;
 import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
 import org.apache.brooklyn.core.mgmt.rebind.RecordingRebindExceptionHandler;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynMementoPersisterToObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.FileBasedObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
 import org.apache.brooklyn.core.mgmt.rebind.transformer.CompoundTransformer;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.util.guava.SerializablePredicate;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/policy/basic/PolicySubscriptionTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/policy/basic/PolicySubscriptionTest.java b/core/src/test/java/org/apache/brooklyn/core/policy/basic/PolicySubscriptionTest.java
index 2c36e72..b989d74 100644
--- a/core/src/test/java/org/apache/brooklyn/core/policy/basic/PolicySubscriptionTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/policy/basic/PolicySubscriptionTest.java
@@ -25,7 +25,7 @@ import org.apache.brooklyn.api.mgmt.SubscriptionHandle;
 import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
 import org.apache.brooklyn.core.test.entity.TestEntity;
 import org.apache.brooklyn.entity.core.RecordingSensorEventListener;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 import org.apache.brooklyn.policy.core.AbstractPolicy;
 import org.apache.brooklyn.sensor.core.BasicSensorEvent;
 import org.apache.brooklyn.test.Asserts;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/server/entity/BrooklynMetricsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/server/entity/BrooklynMetricsTest.java b/core/src/test/java/org/apache/brooklyn/core/server/entity/BrooklynMetricsTest.java
index 2ee1752..74e86a4 100644
--- a/core/src/test/java/org/apache/brooklyn/core/server/entity/BrooklynMetricsTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/server/entity/BrooklynMetricsTest.java
@@ -39,7 +39,7 @@ import org.apache.brooklyn.util.time.Duration;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/test/HttpService.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/test/HttpService.java b/core/src/test/java/org/apache/brooklyn/core/test/HttpService.java
index e1f6acd..fe959f4 100644
--- a/core/src/test/java/org/apache/brooklyn/core/test/HttpService.java
+++ b/core/src/test/java/org/apache/brooklyn/core/test/HttpService.java
@@ -44,7 +44,7 @@ import org.eclipse.jetty.webapp.WebAppContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.api.location.PortRange;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Optional;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/test/entity/TestApplication.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/test/entity/TestApplication.java b/core/src/test/java/org/apache/brooklyn/core/test/entity/TestApplication.java
index ae84eab..15dd766 100644
--- a/core/src/test/java/org/apache/brooklyn/core/test/entity/TestApplication.java
+++ b/core/src/test/java/org/apache/brooklyn/core/test/entity/TestApplication.java
@@ -28,8 +28,8 @@ import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.entity.core.EntityInternal;
 import org.apache.brooklyn.entity.core.StartableApplication;
 import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.sensor.core.Sensors;
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/test/entity/TestApplicationImpl.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/test/entity/TestApplicationImpl.java b/core/src/test/java/org/apache/brooklyn/core/test/entity/TestApplicationImpl.java
index f142b4a..da8ccc9 100644
--- a/core/src/test/java/org/apache/brooklyn/core/test/entity/TestApplicationImpl.java
+++ b/core/src/test/java/org/apache/brooklyn/core/test/entity/TestApplicationImpl.java
@@ -30,8 +30,8 @@ import org.apache.brooklyn.api.sensor.SensorEventListener;
 import org.apache.brooklyn.entity.core.AbstractApplication;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.util.logging.LoggingSetup;
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/test/location/TestPaasLocation.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/test/location/TestPaasLocation.java b/core/src/test/java/org/apache/brooklyn/core/test/location/TestPaasLocation.java
index d68d7d3..d79476c 100644
--- a/core/src/test/java/org/apache/brooklyn/core/test/location/TestPaasLocation.java
+++ b/core/src/test/java/org/apache/brooklyn/core/test/location/TestPaasLocation.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.core.test.location;
 
-import org.apache.brooklyn.location.basic.AbstractLocation;
+import org.apache.brooklyn.location.core.AbstractLocation;
 import org.apache.brooklyn.location.paas.PaasLocation;
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/test/qa/longevity/EntityCleanupLongevityTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/test/qa/longevity/EntityCleanupLongevityTest.java b/core/src/test/java/org/apache/brooklyn/core/test/qa/longevity/EntityCleanupLongevityTest.java
index 5163c93..1e6a185 100644
--- a/core/src/test/java/org/apache/brooklyn/core/test/qa/longevity/EntityCleanupLongevityTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/test/qa/longevity/EntityCleanupLongevityTest.java
@@ -20,7 +20,7 @@ package org.apache.brooklyn.core.test.qa.longevity;
 
 import org.testng.annotations.Test;
 import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 import org.apache.brooklyn.util.javalang.JavaClassNames;
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/test/qa/longevity/EntityCleanupLongevityTestFixture.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/test/qa/longevity/EntityCleanupLongevityTestFixture.java b/core/src/test/java/org/apache/brooklyn/core/test/qa/longevity/EntityCleanupLongevityTestFixture.java
index 4e9971f..3a0ecc1 100644
--- a/core/src/test/java/org/apache/brooklyn/core/test/qa/longevity/EntityCleanupLongevityTestFixture.java
+++ b/core/src/test/java/org/apache/brooklyn/core/test/qa/longevity/EntityCleanupLongevityTestFixture.java
@@ -46,7 +46,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Stopwatch;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/test/qa/longevity/EntityCleanupTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/test/qa/longevity/EntityCleanupTest.java b/core/src/test/java/org/apache/brooklyn/core/test/qa/longevity/EntityCleanupTest.java
index c98a448..b9fb501 100644
--- a/core/src/test/java/org/apache/brooklyn/core/test/qa/longevity/EntityCleanupTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/test/qa/longevity/EntityCleanupTest.java
@@ -20,7 +20,7 @@ package org.apache.brooklyn.core.test.qa.longevity;
 
 import org.testng.annotations.Test;
 import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 import org.apache.brooklyn.util.javalang.JavaClassNames;
 
 public class EntityCleanupTest extends EntityCleanupLongevityTestFixture {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/test/qa/performance/AbstractPerformanceTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/test/qa/performance/AbstractPerformanceTest.java b/core/src/test/java/org/apache/brooklyn/core/test/qa/performance/AbstractPerformanceTest.java
index 7e338f9..cbf50f3 100644
--- a/core/src/test/java/org/apache/brooklyn/core/test/qa/performance/AbstractPerformanceTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/test/qa/performance/AbstractPerformanceTest.java
@@ -31,7 +31,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Stopwatch;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/test/qa/performance/EntityPersistencePerformanceTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/test/qa/performance/EntityPersistencePerformanceTest.java b/core/src/test/java/org/apache/brooklyn/core/test/qa/performance/EntityPersistencePerformanceTest.java
index 1fab2ec..70737f6 100644
--- a/core/src/test/java/org/apache/brooklyn/core/test/qa/performance/EntityPersistencePerformanceTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/test/qa/performance/EntityPersistencePerformanceTest.java
@@ -33,7 +33,7 @@ import org.apache.brooklyn.test.PerformanceTestUtils;
 import org.apache.brooklyn.util.repeat.Repeater;
 import org.apache.brooklyn.util.time.Duration;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.Iterables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/test/qa/performance/FilePersistencePerformanceTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/test/qa/performance/FilePersistencePerformanceTest.java b/core/src/test/java/org/apache/brooklyn/core/test/qa/performance/FilePersistencePerformanceTest.java
index a3bd0cc..594b102 100644
--- a/core/src/test/java/org/apache/brooklyn/core/test/qa/performance/FilePersistencePerformanceTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/test/qa/performance/FilePersistencePerformanceTest.java
@@ -23,7 +23,7 @@ import java.io.IOException;
 import java.util.List;
 import java.util.concurrent.atomic.AtomicInteger;
 
-import org.apache.brooklyn.core.mgmt.rebind.persister.FileBasedStoreObjectAccessor;
+import org.apache.brooklyn.core.mgmt.persist.FileBasedStoreObjectAccessor;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.internal.ssh.process.ProcessTool;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/effector/core/EffectorBasicTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/effector/core/EffectorBasicTest.java b/core/src/test/java/org/apache/brooklyn/effector/core/EffectorBasicTest.java
index 3380032..078b2d2 100644
--- a/core/src/test/java/org/apache/brooklyn/effector/core/EffectorBasicTest.java
+++ b/core/src/test/java/org/apache/brooklyn/effector/core/EffectorBasicTest.java
@@ -40,7 +40,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/core/AbstractApplicationLegacyTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/core/AbstractApplicationLegacyTest.java b/core/src/test/java/org/apache/brooklyn/entity/core/AbstractApplicationLegacyTest.java
index 42e4796..740b9b2 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/core/AbstractApplicationLegacyTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/core/AbstractApplicationLegacyTest.java
@@ -38,7 +38,7 @@ import org.testng.annotations.Test;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 /**
  * Tests the deprecated use of AbstractAppliation, where its constructor is called directly.

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/core/AbstractEntityLegacyTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/core/AbstractEntityLegacyTest.java b/core/src/test/java/org/apache/brooklyn/entity/core/AbstractEntityLegacyTest.java
index 23b6fc3..60da5ad 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/core/AbstractEntityLegacyTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/core/AbstractEntityLegacyTest.java
@@ -35,7 +35,7 @@ import org.apache.brooklyn.util.collections.MutableMap;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 /**
  * Tests the deprecated use of AbstractAppliation, where its constructor is called directly.

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/core/EntitiesTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/core/EntitiesTest.java b/core/src/test/java/org/apache/brooklyn/entity/core/EntitiesTest.java
index f2f3322..e413077 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/core/EntitiesTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/core/EntitiesTest.java
@@ -36,7 +36,7 @@ import org.apache.brooklyn.util.collections.MutableSet;
 import org.testng.Assert;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/core/EntitySetFromFlagTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/core/EntitySetFromFlagTest.java b/core/src/test/java/org/apache/brooklyn/entity/core/EntitySetFromFlagTest.java
index 1f3c7bf..51a163f 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/core/EntitySetFromFlagTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/core/EntitySetFromFlagTest.java
@@ -26,7 +26,7 @@ import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.location.PortRange;
 import org.apache.brooklyn.entity.core.AbstractEntity;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/core/EntitySpecTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/core/EntitySpecTest.java b/core/src/test/java/org/apache/brooklyn/entity/core/EntitySpecTest.java
index 671140e..7c127ab 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/core/EntitySpecTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/core/EntitySpecTest.java
@@ -41,7 +41,7 @@ import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/core/EntitySubscriptionTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/core/EntitySubscriptionTest.java b/core/src/test/java/org/apache/brooklyn/entity/core/EntitySubscriptionTest.java
index 81d8e25..cfdf9f3 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/core/EntitySubscriptionTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/core/EntitySubscriptionTest.java
@@ -32,7 +32,7 @@ import org.apache.brooklyn.test.Asserts;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/core/EntitySuppliersTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/core/EntitySuppliersTest.java b/core/src/test/java/org/apache/brooklyn/entity/core/EntitySuppliersTest.java
index 9c4bb9e..f75686c 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/core/EntitySuppliersTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/core/EntitySuppliersTest.java
@@ -29,7 +29,7 @@ import org.apache.brooklyn.core.test.entity.TestEntity;
 import org.apache.brooklyn.entity.core.EntitySuppliers;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/core/internal/EntityConfigMapUsageLegacyTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/core/internal/EntityConfigMapUsageLegacyTest.java b/core/src/test/java/org/apache/brooklyn/entity/core/internal/EntityConfigMapUsageLegacyTest.java
index 7120199..642e8c5 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/core/internal/EntityConfigMapUsageLegacyTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/core/internal/EntityConfigMapUsageLegacyTest.java
@@ -35,7 +35,7 @@ import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
 import org.apache.brooklyn.core.test.entity.TestEntity;
 import org.apache.brooklyn.core.test.entity.TestEntityImpl;
 import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Function;
 import com.google.common.base.Predicates;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/core/internal/EntityConfigMapUsageTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/core/internal/EntityConfigMapUsageTest.java b/core/src/test/java/org/apache/brooklyn/entity/core/internal/EntityConfigMapUsageTest.java
index 1b9dd52..f87f182 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/core/internal/EntityConfigMapUsageTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/core/internal/EntityConfigMapUsageTest.java
@@ -37,7 +37,7 @@ import org.apache.brooklyn.sensor.core.DependentConfiguration;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Function;
 import com.google.common.base.Predicates;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/drivers/BasicEntityDriverManagerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/drivers/BasicEntityDriverManagerTest.java b/core/src/test/java/org/apache/brooklyn/entity/drivers/BasicEntityDriverManagerTest.java
index 2ce9245..b4928aa 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/drivers/BasicEntityDriverManagerTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/drivers/BasicEntityDriverManagerTest.java
@@ -29,8 +29,8 @@ import org.apache.brooklyn.entity.drivers.RegistryEntityDriverFactoryTest.MyOthe
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 
 public class BasicEntityDriverManagerTest {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/drivers/EntityDriverRegistryTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/drivers/EntityDriverRegistryTest.java b/core/src/test/java/org/apache/brooklyn/entity/drivers/EntityDriverRegistryTest.java
index 34f14d3..765e40b 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/drivers/EntityDriverRegistryTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/drivers/EntityDriverRegistryTest.java
@@ -31,7 +31,7 @@ import org.apache.brooklyn.util.collections.MutableMap;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 public class EntityDriverRegistryTest {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/drivers/ReflectiveEntityDriverFactoryTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/drivers/ReflectiveEntityDriverFactoryTest.java b/core/src/test/java/org/apache/brooklyn/entity/drivers/ReflectiveEntityDriverFactoryTest.java
index e357695..7303b89 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/drivers/ReflectiveEntityDriverFactoryTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/drivers/ReflectiveEntityDriverFactoryTest.java
@@ -18,8 +18,8 @@
  */
 package org.apache.brooklyn.entity.drivers;
 
-import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.location.paas.PaasLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.entity.drivers.DriverDependentEntity;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/drivers/RegistryEntityDriverFactoryTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/drivers/RegistryEntityDriverFactoryTest.java b/core/src/test/java/org/apache/brooklyn/entity/drivers/RegistryEntityDriverFactoryTest.java
index 59e26c8..00a5a25 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/drivers/RegistryEntityDriverFactoryTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/drivers/RegistryEntityDriverFactoryTest.java
@@ -31,8 +31,8 @@ import org.apache.brooklyn.entity.drivers.ReflectiveEntityDriverFactoryTest.MyDr
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 
 public class RegistryEntityDriverFactoryTest {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/BasicDownloadsRegistryTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/BasicDownloadsRegistryTest.java b/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/BasicDownloadsRegistryTest.java
index 388bd59..386c25b 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/BasicDownloadsRegistryTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/BasicDownloadsRegistryTest.java
@@ -35,7 +35,7 @@ import org.apache.brooklyn.entity.factory.ApplicationBuilder;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/DownloadProducerFromLocalRepoTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/DownloadProducerFromLocalRepoTest.java b/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/DownloadProducerFromLocalRepoTest.java
index 5953583..5e114d4 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/DownloadProducerFromLocalRepoTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/DownloadProducerFromLocalRepoTest.java
@@ -38,7 +38,7 @@ import org.apache.brooklyn.entity.factory.ApplicationBuilder;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/DownloadProducerFromPropertiesTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/DownloadProducerFromPropertiesTest.java b/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/DownloadProducerFromPropertiesTest.java
index 198f041..15b35e3 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/DownloadProducerFromPropertiesTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/DownloadProducerFromPropertiesTest.java
@@ -39,7 +39,7 @@ import org.apache.brooklyn.entity.factory.ApplicationBuilder;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/DownloadSubstitutersTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/DownloadSubstitutersTest.java b/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/DownloadSubstitutersTest.java
index 35a4737..7b75f48 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/DownloadSubstitutersTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/drivers/downloads/DownloadSubstitutersTest.java
@@ -33,7 +33,7 @@ import org.apache.brooklyn.entity.drivers.downloads.BasicDownloadRequirement;
 import org.apache.brooklyn.entity.drivers.downloads.DownloadSubstituters;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Functions;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/group/DynamicClusterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/group/DynamicClusterTest.java b/core/src/test/java/org/apache/brooklyn/entity/group/DynamicClusterTest.java
index 255c930..40dd6dd 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/group/DynamicClusterTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/group/DynamicClusterTest.java
@@ -70,7 +70,7 @@ import org.apache.brooklyn.util.collections.MutableSet;
 import org.apache.brooklyn.util.collections.QuorumCheck.QuorumChecks;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.apache.brooklyn.util.time.Time;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Function;
 import com.google.common.base.Predicates;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/group/DynamicClusterWithAvailabilityZonesTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/group/DynamicClusterWithAvailabilityZonesTest.java b/core/src/test/java/org/apache/brooklyn/entity/group/DynamicClusterWithAvailabilityZonesTest.java
index 9a7e5fa..1cff020 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/group/DynamicClusterWithAvailabilityZonesTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/group/DynamicClusterWithAvailabilityZonesTest.java
@@ -44,10 +44,10 @@ import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.util.time.Duration;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocationInternal;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
 import org.apache.brooklyn.location.cloud.AbstractAvailabilityZoneExtension;
 import org.apache.brooklyn.location.cloud.AvailabilityZoneExtension;
+import org.apache.brooklyn.location.core.SimulatedLocation;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 
 import com.google.common.base.Predicate;
 import com.google.common.base.Ticker;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/group/DynamicFabricTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/group/DynamicFabricTest.java b/core/src/test/java/org/apache/brooklyn/entity/group/DynamicFabricTest.java
index c026eab..c5000ce 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/group/DynamicFabricTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/group/DynamicFabricTest.java
@@ -44,8 +44,8 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.factory.EntityFactory;
 import org.apache.brooklyn.entity.stock.BasicEntity;
 import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.location.basic.PortRanges;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.TestUtils;
 import org.apache.brooklyn.util.collections.MutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/group/DynamicMultiGroupTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/group/DynamicMultiGroupTest.java b/core/src/test/java/org/apache/brooklyn/entity/group/DynamicMultiGroupTest.java
index 514c9ae..c914d98 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/group/DynamicMultiGroupTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/group/DynamicMultiGroupTest.java
@@ -46,7 +46,7 @@ import org.apache.brooklyn.test.Asserts;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/group/DynamicRegionsFabricTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/group/DynamicRegionsFabricTest.java b/core/src/test/java/org/apache/brooklyn/entity/group/DynamicRegionsFabricTest.java
index 0d8e3da..efc93ef 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/group/DynamicRegionsFabricTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/group/DynamicRegionsFabricTest.java
@@ -34,7 +34,7 @@ import org.apache.brooklyn.util.collections.MutableSet;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/group/GroupTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/group/GroupTest.java b/core/src/test/java/org/apache/brooklyn/entity/group/GroupTest.java
index 6c60c1d..bf0a529 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/group/GroupTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/group/GroupTest.java
@@ -37,7 +37,7 @@ import org.testng.annotations.Test;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
 
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 public class GroupTest extends BrooklynAppUnitTestSupport {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/group/MembershipTrackingPolicyTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/group/MembershipTrackingPolicyTest.java b/core/src/test/java/org/apache/brooklyn/entity/group/MembershipTrackingPolicyTest.java
index 7dc9548..4e3b346 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/group/MembershipTrackingPolicyTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/group/MembershipTrackingPolicyTest.java
@@ -41,7 +41,7 @@ import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Objects;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/group/QuarantineGroupTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/group/QuarantineGroupTest.java b/core/src/test/java/org/apache/brooklyn/entity/group/QuarantineGroupTest.java
index 622b667..e85ce29 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/group/QuarantineGroupTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/group/QuarantineGroupTest.java
@@ -29,7 +29,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.group.QuarantineGroup;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/group/zoneaware/BalancingNodePlacementStrategyTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/group/zoneaware/BalancingNodePlacementStrategyTest.java b/core/src/test/java/org/apache/brooklyn/entity/group/zoneaware/BalancingNodePlacementStrategyTest.java
index 21e57bf..738ecfd 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/group/zoneaware/BalancingNodePlacementStrategyTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/group/zoneaware/BalancingNodePlacementStrategyTest.java
@@ -30,7 +30,7 @@ import org.apache.brooklyn.entity.group.zoneaware.BalancingNodePlacementStrategy
 import org.apache.brooklyn.test.Asserts;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.LinkedHashMultimap;



[02/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeEc2LiveTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeEc2LiveTest.java
index 4f54047..907f8b3 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeEc2LiveTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeEc2LiveTest.java
@@ -20,6 +20,7 @@ package org.apache.brooklyn.entity.nosql.riak;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -27,8 +28,6 @@ import org.testng.annotations.Test;
 
 import com.google.common.collect.ImmutableList;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 public class RiakNodeEc2LiveTest extends AbstractEc2LiveTest {
 
     @SuppressWarnings("unused")

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeGoogleComputeLiveTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeGoogleComputeLiveTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeGoogleComputeLiveTest.java
index baed024..6904f0f 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeGoogleComputeLiveTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeGoogleComputeLiveTest.java
@@ -20,14 +20,13 @@ package org.apache.brooklyn.entity.nosql.riak;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractGoogleComputeLiveTest;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.annotations.Test;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 
-import brooklyn.entity.AbstractGoogleComputeLiveTest;
-
 public class RiakNodeGoogleComputeLiveTest extends AbstractGoogleComputeLiveTest {
     @Override
     protected void doTest(Location loc) throws Exception {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeSoftlayerLiveTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeSoftlayerLiveTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeSoftlayerLiveTest.java
index a93c5f4..846801f 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeSoftlayerLiveTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeSoftlayerLiveTest.java
@@ -20,13 +20,12 @@ package org.apache.brooklyn.entity.nosql.riak;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractSoftlayerLiveTest;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.annotations.BeforeMethod;
 
 import com.google.common.collect.ImmutableList;
 
-import brooklyn.entity.AbstractSoftlayerLiveTest;
-
 public class RiakNodeSoftlayerLiveTest extends AbstractSoftlayerLiveTest {
 
     @BeforeMethod(alwaysRun=true)

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/solr/SolrServerEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/solr/SolrServerEc2LiveTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/solr/SolrServerEc2LiveTest.java
index 3035602..0c53637 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/solr/SolrServerEc2LiveTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/solr/SolrServerEc2LiveTest.java
@@ -23,6 +23,7 @@ import static org.testng.Assert.assertTrue;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.apache.brooklyn.util.collections.MutableMap;
@@ -30,8 +31,6 @@ import org.apache.solr.common.SolrDocument;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Iterables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainer.java
----------------------------------------------------------------------
diff --git a/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainer.java b/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainer.java
index d00af57..f21cf1f 100644
--- a/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainer.java
+++ b/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainer.java
@@ -29,15 +29,14 @@ import org.apache.brooklyn.core.config.MapConfigKey;
 import org.apache.brooklyn.effector.core.MethodEffector;
 import org.apache.brooklyn.entity.annotation.Effector;
 import org.apache.brooklyn.entity.annotation.EffectorParam;
+import org.apache.brooklyn.entity.java.UsesJava;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.java.UsesJava;
-import brooklyn.entity.java.UsesJmx;
-
 /**
  * This sets up a Karaf OSGi container
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerImpl.java
----------------------------------------------------------------------
diff --git a/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerImpl.java b/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerImpl.java
index 7cc49eb..6d3c95f 100644
--- a/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerImpl.java
+++ b/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerImpl.java
@@ -37,7 +37,13 @@ import org.apache.brooklyn.api.sensor.SensorEvent;
 import org.apache.brooklyn.api.sensor.SensorEventListener;
 import org.apache.brooklyn.entity.annotation.Effector;
 import org.apache.brooklyn.entity.annotation.EffectorParam;
+import org.apache.brooklyn.entity.java.JmxSupport;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
+import org.apache.brooklyn.sensor.feed.jmx.JmxAttributePollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
+import org.apache.brooklyn.sensor.feed.jmx.JmxHelper;
+import org.apache.brooklyn.sensor.feed.jmx.JmxValueFunctions;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.apache.brooklyn.util.os.Os;
@@ -46,13 +52,6 @@ import org.osgi.jmx.JmxConstants;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
-import brooklyn.entity.java.JmxSupport;
-import brooklyn.event.feed.jmx.JmxAttributePollConfig;
-import brooklyn.event.feed.jmx.JmxFeed;
-import brooklyn.event.feed.jmx.JmxHelper;
-import brooklyn.event.feed.jmx.JmxValueFunctions;
-
 import com.google.common.base.Function;
 import com.google.common.collect.Maps;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafDriver.java
----------------------------------------------------------------------
diff --git a/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafDriver.java b/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafDriver.java
index 80e972d..ec90e45 100644
--- a/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafDriver.java
+++ b/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafDriver.java
@@ -20,7 +20,7 @@ package org.apache.brooklyn.entity.osgi.karaf;
 
 import java.io.File;
 
-import brooklyn.entity.java.JavaSoftwareProcessDriver;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessDriver;
 
 public interface KarafDriver extends JavaSoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafSshDriver.java
----------------------------------------------------------------------
diff --git a/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafSshDriver.java b/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafSshDriver.java
index 0943c12..bb60895 100644
--- a/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafSshDriver.java
+++ b/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafSshDriver.java
@@ -24,9 +24,8 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-import brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/osgi/src/test/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/osgi/src/test/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerEc2LiveTest.java b/software/osgi/src/test/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerEc2LiveTest.java
index 9d55da7..e3d3090 100644
--- a/software/osgi/src/test/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerEc2LiveTest.java
+++ b/software/osgi/src/test/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerEc2LiveTest.java
@@ -20,14 +20,13 @@ package org.apache.brooklyn.entity.osgi.karaf;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.apache.brooklyn.util.text.Identifiers;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.collect.ImmutableList;
 
 public class KarafContainerEc2LiveTest extends AbstractEc2LiveTest {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/osgi/src/test/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerTest.java
----------------------------------------------------------------------
diff --git a/software/osgi/src/test/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerTest.java b/software/osgi/src/test/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerTest.java
index cec795c..b3188eb 100644
--- a/software/osgi/src/test/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerTest.java
+++ b/software/osgi/src/test/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerTest.java
@@ -29,6 +29,7 @@ import org.apache.brooklyn.api.location.NoMachinesAvailableException;
 import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.apache.brooklyn.test.TestResourceUnavailableException;
@@ -37,9 +38,6 @@ import org.apache.brooklyn.util.text.Identifiers;
 import org.testng.Assert;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.software.SshEffectorTasks;
-
 import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/AbstractController.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/AbstractController.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/AbstractController.java
index 42608c0..1e8cc84 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/AbstractController.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/AbstractController.java
@@ -25,11 +25,10 @@ import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.entity.group.Cluster;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
-import brooklyn.entity.basic.SoftwareProcess;
-
 /**
  * Represents a controller mechanism for a {@link Cluster}.
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/AbstractControllerImpl.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/AbstractControllerImpl.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/AbstractControllerImpl.java
index 29c3868..2449184 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/AbstractControllerImpl.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/AbstractControllerImpl.java
@@ -39,12 +39,10 @@ import org.apache.brooklyn.entity.group.AbstractMembershipTrackingPolicy;
 import org.apache.brooklyn.entity.group.Cluster;
 import org.apache.brooklyn.entity.lifecycle.Lifecycle;
 import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
 import org.apache.brooklyn.location.basic.Machines;
 import org.apache.brooklyn.sensor.feed.ConfigToAttributes;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxController.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxController.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxController.java
index 359aef6..0c0309b 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxController.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxController.java
@@ -31,12 +31,11 @@ import org.apache.brooklyn.entity.annotation.Effector;
 import org.apache.brooklyn.entity.annotation.EffectorParam;
 import org.apache.brooklyn.entity.proxy.AbstractController;
 import org.apache.brooklyn.entity.proxy.ProxySslConfig;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.Sensors;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
-import brooklyn.entity.basic.SoftwareProcess;
-
 import com.google.common.collect.ImmutableMap;
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxDriver.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxDriver.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxDriver.java
index 48a0534..57968d1 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxDriver.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.proxy.nginx;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 
 public interface NginxDriver extends SoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxSshDriver.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxSshDriver.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxSshDriver.java
index 9a94cfa..685c593 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxSshDriver.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxSshDriver.java
@@ -32,12 +32,10 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.core.EntityInternal;
 import org.apache.brooklyn.entity.lifecycle.Lifecycle;
 import org.apache.brooklyn.entity.proxy.AbstractController;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-import brooklyn.entity.basic.lifecycle.ScriptHelper;
-
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.task.DynamicTasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppDriver.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppDriver.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppDriver.java
index 822519b..496540b 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppDriver.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppDriver.java
@@ -21,7 +21,7 @@ package org.apache.brooklyn.entity.webapp;
 import java.io.File;
 import java.util.Set;
 
-import brooklyn.entity.java.JavaSoftwareProcessDriver;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessDriver;
 
 public interface JavaWebAppDriver extends JavaSoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppService.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppService.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppService.java
index 1222e5a..d5e2547 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppService.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppService.java
@@ -29,11 +29,10 @@ import org.apache.brooklyn.core.config.BasicConfigKey;
 import org.apache.brooklyn.effector.core.MethodEffector;
 import org.apache.brooklyn.entity.annotation.Effector;
 import org.apache.brooklyn.entity.annotation.EffectorParam;
+import org.apache.brooklyn.entity.java.UsesJava;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
-import brooklyn.entity.java.UsesJava;
-
 public interface JavaWebAppService extends WebAppService, UsesJava {
 
     @SetFromFlag("war")

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSoftwareProcess.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSoftwareProcess.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSoftwareProcess.java
index b0563fd..527f964 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSoftwareProcess.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSoftwareProcess.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.webapp;
 
-import brooklyn.entity.basic.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 
 public interface JavaWebAppSoftwareProcess extends SoftwareProcess, JavaWebAppService, JavaWebAppService.CanDeployAndUndeploy {
     

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSoftwareProcessImpl.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSoftwareProcessImpl.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSoftwareProcessImpl.java
index 2cb81c7..00cd31c 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSoftwareProcessImpl.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSoftwareProcessImpl.java
@@ -29,12 +29,11 @@ import java.util.Set;
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.entity.annotation.Effector;
 import org.apache.brooklyn.entity.annotation.EffectorParam;
+import org.apache.brooklyn.entity.java.JavaAppUtils;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
-import brooklyn.entity.java.JavaAppUtils;
-
 import com.google.common.base.Throwables;
 import com.google.common.collect.Sets;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSshDriver.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSshDriver.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSshDriver.java
index 1002af2..d045305 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSshDriver.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSshDriver.java
@@ -24,9 +24,8 @@ import java.io.File;
 import java.net.URI;
 import java.util.Set;
 
-import brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-
 import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.core.task.DynamicTasks;
 import org.apache.brooklyn.util.core.task.Tasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6Server.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6Server.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6Server.java
index 74f993e..3e3419d 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6Server.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6Server.java
@@ -22,13 +22,12 @@ import org.apache.brooklyn.api.catalog.Catalog;
 import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcess;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.java.UsesJmx;
-
 @Catalog(name="JBoss Application Server 6", description="AS6: an open source Java application server from JBoss", iconUrl="classpath:///jboss-logo.png")
 @ImplementedBy(JBoss6ServerImpl.class)
 public interface JBoss6Server extends JavaWebAppSoftwareProcess, UsesJmx {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerImpl.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerImpl.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerImpl.java
index a819dfb..cd79d3f 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerImpl.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerImpl.java
@@ -26,12 +26,11 @@ import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcessImpl;
 import org.apache.brooklyn.sensor.enricher.Enrichers;
+import org.apache.brooklyn.sensor.feed.jmx.JmxAttributePollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.event.feed.jmx.JmxAttributePollConfig;
-import brooklyn.event.feed.jmx.JmxFeed;
-
 import com.google.common.base.Functions;
 
 public class JBoss6ServerImpl extends JavaWebAppSoftwareProcessImpl implements JBoss6Server {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6SshDriver.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6SshDriver.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6SshDriver.java
index 1ccc1f8..35bc26b 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6SshDriver.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6SshDriver.java
@@ -29,11 +29,9 @@ import java.util.Map;
 
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.entity.java.UsesJmx.JmxAgentModes;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSshDriver;
-
-import brooklyn.entity.java.UsesJmx;
-import brooklyn.entity.java.UsesJmx.JmxAgentModes;
-
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7Server.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7Server.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7Server.java
index 6aac6d6..5fc7a23 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7Server.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7Server.java
@@ -24,6 +24,7 @@ import org.apache.brooklyn.api.objs.HasShortName;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcess;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
@@ -32,8 +33,6 @@ import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey.StringAt
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 import org.apache.brooklyn.util.javalang.JavaClassNames;
 
-import brooklyn.entity.basic.SoftwareProcess;
-
 @Catalog(name="JBoss Application Server 7", description="AS7: an open source Java application server from JBoss", iconUrl="classpath:///jboss-logo.png")
 @ImplementedBy(JBoss7ServerImpl.class)
 public interface JBoss7Server extends JavaWebAppSoftwareProcess, HasShortName {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7SshDriver.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7SshDriver.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7SshDriver.java
index 4707500..0acaa95 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7SshDriver.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7SshDriver.java
@@ -26,12 +26,10 @@ import java.util.List;
 import java.util.Map;
 
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSshDriver;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jetty/Jetty6Server.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jetty/Jetty6Server.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jetty/Jetty6Server.java
index 2ac1ddc..1bce7e7 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jetty/Jetty6Server.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jetty/Jetty6Server.java
@@ -24,15 +24,14 @@ import org.apache.brooklyn.api.objs.HasShortName;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcess;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.Sensors;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 import org.apache.brooklyn.util.time.Duration;
 
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.java.UsesJmx;
-
 /**
  * An {@link org.apache.brooklyn.api.entity.Entity} that represents a single Jetty instance.
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jetty/Jetty6ServerImpl.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jetty/Jetty6ServerImpl.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jetty/Jetty6ServerImpl.java
index 52c11c8..50d6316 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jetty/Jetty6ServerImpl.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jetty/Jetty6ServerImpl.java
@@ -20,17 +20,16 @@ package org.apache.brooklyn.entity.webapp.jetty;
 
 import java.util.concurrent.TimeUnit;
 
+import org.apache.brooklyn.entity.java.JavaAppUtils;
+import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.entity.lifecycle.Lifecycle;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcessImpl;
 import org.apache.brooklyn.sensor.enricher.Enrichers;
+import org.apache.brooklyn.sensor.feed.jmx.JmxAttributePollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.entity.java.JavaAppUtils;
-import brooklyn.entity.java.UsesJmx;
-import brooklyn.event.feed.jmx.JmxAttributePollConfig;
-import brooklyn.event.feed.jmx.JmxFeed;
-
 import com.google.common.base.Functions;
 import com.google.common.base.Predicates;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppDriver.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppDriver.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppDriver.java
index 167f843..01596ab 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppDriver.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.webapp.nodejs;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 
 public interface NodeJsWebAppDriver extends SoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppService.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppService.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppService.java
index d7c705e..25ae613 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppService.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppService.java
@@ -26,10 +26,8 @@ import org.apache.brooklyn.api.location.PortRange;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.WebAppService;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.location.basic.PortRanges;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppServiceImpl.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppServiceImpl.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppServiceImpl.java
index 408762f..e8c517b 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppServiceImpl.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppServiceImpl.java
@@ -19,12 +19,10 @@
 package org.apache.brooklyn.entity.webapp.nodejs;
 
 import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.entity.webapp.WebAppServiceMethods;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
 import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
 import org.apache.brooklyn.sensor.feed.http.HttpFeed;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSshDriver.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSshDriver.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSshDriver.java
index 82d22ed..db3233f 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSshDriver.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSshDriver.java
@@ -24,13 +24,11 @@ import java.util.Map;
 import java.util.Set;
 
 import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.WebAppService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8Server.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8Server.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8Server.java
index 6811cff..d9e2f7f 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8Server.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8Server.java
@@ -22,12 +22,11 @@ import org.apache.brooklyn.api.catalog.Catalog;
 import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 import org.apache.brooklyn.util.javalang.JavaClassNames;
 
-import brooklyn.entity.basic.SoftwareProcess;
-
 /**
  * An {@link org.apache.brooklyn.api.entity.Entity} that represents a single Tomcat instance.
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServer.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServer.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServer.java
index 319ead4..2f0ee58 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServer.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServer.java
@@ -24,11 +24,9 @@ import org.apache.brooklyn.api.objs.HasShortName;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcess;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.java.UsesJmx;
-
 import org.apache.brooklyn.location.basic.PortRanges;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerImpl.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerImpl.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerImpl.java
index c3f1fe8..a55fa44 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerImpl.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerImpl.java
@@ -22,14 +22,13 @@ import static java.lang.String.format;
 
 import java.util.concurrent.TimeUnit;
 
+import org.apache.brooklyn.entity.java.JavaAppUtils;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcessImpl;
+import org.apache.brooklyn.sensor.feed.jmx.JmxAttributePollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.entity.java.JavaAppUtils;
-import brooklyn.event.feed.jmx.JmxAttributePollConfig;
-import brooklyn.event.feed.jmx.JmxFeed;
-
 import com.google.common.base.Functions;
 import com.google.common.base.Predicates;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/TrackingAbstractControllerImpl.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/TrackingAbstractControllerImpl.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/TrackingAbstractControllerImpl.java
index 90fea43..4291e33 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/TrackingAbstractControllerImpl.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/TrackingAbstractControllerImpl.java
@@ -23,11 +23,10 @@ import java.util.List;
 import java.util.Set;
 
 import org.apache.brooklyn.entity.proxy.AbstractControllerImpl;
+import org.apache.brooklyn.entity.software.base.test.driver.MockSshDriver;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.entity.driver.MockSshDriver;
-
 import com.google.common.collect.Lists;
 
 public class TrackingAbstractControllerImpl extends AbstractControllerImpl implements TrackingAbstractController {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxEc2LiveTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxEc2LiveTest.java
index 6f23920..caabac5 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxEc2LiveTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxEc2LiveTest.java
@@ -20,6 +20,8 @@ package org.apache.brooklyn.entity.proxy.nginx;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.WebAppService;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.apache.brooklyn.test.HttpTestUtils;
@@ -27,9 +29,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-import brooklyn.entity.basic.SoftwareProcess;
-
 import com.google.common.collect.ImmutableList;
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxHttpsSslIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxHttpsSslIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxHttpsSslIntegrationTest.java
index 2258f50..1b5826f 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxHttpsSslIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxHttpsSslIntegrationTest.java
@@ -31,6 +31,7 @@ import org.apache.brooklyn.entity.core.EntityInternal;
 import org.apache.brooklyn.entity.group.DynamicCluster;
 import org.apache.brooklyn.entity.proxy.LoadBalancer;
 import org.apache.brooklyn.entity.proxy.ProxySslConfig;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.JavaWebAppService;
 import org.apache.brooklyn.entity.webapp.WebAppService;
 import org.apache.brooklyn.entity.webapp.jboss.JBoss7Server;
@@ -44,9 +45,6 @@ import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.location.basic.PortRanges;
 
 import com.google.common.base.Preconditions;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxIntegrationTest.java
index 5c4c381..b688577 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxIntegrationTest.java
@@ -33,6 +33,7 @@ import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
 import org.apache.brooklyn.entity.factory.EntityFactory;
 import org.apache.brooklyn.entity.group.DynamicCluster;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.JavaWebAppService;
 import org.apache.brooklyn.entity.webapp.WebAppService;
 import org.apache.brooklyn.entity.webapp.jboss.JBoss7Server;
@@ -47,8 +48,6 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.basic.SoftwareProcess;
-
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxRebindIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxRebindIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxRebindIntegrationTest.java
index 1e39ab4..02fde07 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxRebindIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxRebindIntegrationTest.java
@@ -43,6 +43,7 @@ import org.apache.brooklyn.entity.lifecycle.Lifecycle;
 import org.apache.brooklyn.entity.proxy.nginx.NginxController;
 import org.apache.brooklyn.entity.proxy.nginx.UrlMapping;
 import org.apache.brooklyn.entity.proxy.nginx.UrlRewriteRule;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.tomcat.Tomcat8Server;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.EntityTestUtils;
@@ -53,9 +54,6 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Predicates;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/AbstractWebAppFixtureIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/AbstractWebAppFixtureIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/AbstractWebAppFixtureIntegrationTest.java
index f164aa6..c00b514 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/AbstractWebAppFixtureIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/AbstractWebAppFixtureIntegrationTest.java
@@ -37,8 +37,6 @@ import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterClass;
@@ -46,9 +44,6 @@ import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.api.entity.Application;
 import org.apache.brooklyn.api.entity.Entity;
@@ -66,6 +61,8 @@ import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.core.EntityInternal;
 import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.entity.webapp.JavaWebAppService;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcess;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ControlledDynamicWebAppClusterTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ControlledDynamicWebAppClusterTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ControlledDynamicWebAppClusterTest.java
index 36b59bf..261b0fd 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ControlledDynamicWebAppClusterTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ControlledDynamicWebAppClusterTest.java
@@ -32,6 +32,7 @@ import org.apache.brooklyn.entity.lifecycle.Lifecycle;
 import org.apache.brooklyn.entity.proxy.AbstractController;
 import org.apache.brooklyn.entity.proxy.LoadBalancer;
 import org.apache.brooklyn.entity.proxy.TrackingAbstractController;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.jboss.JBoss7Server;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.EntityTestUtils;
@@ -41,9 +42,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/ControlledDynamicWebAppClusterRebindIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/ControlledDynamicWebAppClusterRebindIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/ControlledDynamicWebAppClusterRebindIntegrationTest.java
index 4d20af0..5ce5f84 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/ControlledDynamicWebAppClusterRebindIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/ControlledDynamicWebAppClusterRebindIntegrationTest.java
@@ -37,6 +37,7 @@ import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.factory.ApplicationBuilder;
 import org.apache.brooklyn.entity.proxy.nginx.NginxController;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.ControlledDynamicWebAppCluster;
 import org.apache.brooklyn.test.TestResourceUnavailableException;
 import org.apache.brooklyn.test.WebAppMonitor;
@@ -46,9 +47,6 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Predicates;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerAwsEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerAwsEc2LiveTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerAwsEc2LiveTest.java
index 6af4304..084d2af 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerAwsEc2LiveTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerAwsEc2LiveTest.java
@@ -23,13 +23,12 @@ import static org.testng.Assert.assertNotNull;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.HttpTestUtils;
 import org.apache.brooklyn.test.TestResourceUnavailableException;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.collect.ImmutableList;
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerNonInheritingIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerNonInheritingIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerNonInheritingIntegrationTest.java
index 8c1960b..f47a38b 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerNonInheritingIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerNonInheritingIntegrationTest.java
@@ -23,14 +23,12 @@ import static org.testng.Assert.assertNotNull;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
+import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.HttpTestUtils;
 import org.apache.brooklyn.test.TestResourceUnavailableException;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.java.UsesJmx;
-
 import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerAwsEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerAwsEc2LiveTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerAwsEc2LiveTest.java
index e73ef09..5a63eca 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerAwsEc2LiveTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerAwsEc2LiveTest.java
@@ -23,13 +23,12 @@ import static org.testng.Assert.assertNotNull;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.HttpTestUtils;
 import org.apache.brooklyn.test.TestResourceUnavailableException;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.collect.ImmutableList;
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerDockerLiveTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerDockerLiveTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerDockerLiveTest.java
index adf7ed7..760c1dd 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerDockerLiveTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerDockerLiveTest.java
@@ -18,10 +18,9 @@
  */
 package org.apache.brooklyn.entity.webapp.jboss;
 
-import brooklyn.entity.software.AbstractDockerLiveTest;
-
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.software.base.AbstractDockerLiveTest;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.HttpTestUtils;
 import org.apache.brooklyn.test.TestResourceUnavailableException;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerRebindingIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerRebindingIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerRebindingIntegrationTest.java
index ffd7b92..58dc04d 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerRebindingIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerRebindingIntegrationTest.java
@@ -29,6 +29,7 @@ import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.core.mgmt.rebind.RebindOptions;
 import org.apache.brooklyn.core.mgmt.rebind.RebindTestFixtureWithApp;
 import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.apache.brooklyn.test.HttpTestUtils;
 import org.apache.brooklyn.test.TestResourceUnavailableException;
@@ -38,9 +39,6 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Predicates;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBossServersMultiVersionWebAppFixtureIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBossServersMultiVersionWebAppFixtureIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBossServersMultiVersionWebAppFixtureIntegrationTest.java
index 9517df4..bda60b0 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBossServersMultiVersionWebAppFixtureIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBossServersMultiVersionWebAppFixtureIntegrationTest.java
@@ -20,13 +20,11 @@ package org.apache.brooklyn.entity.webapp.jboss;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.AbstractWebAppFixtureIntegrationTest;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcess;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.location.basic.PortRanges;
 
 public class JBossServersMultiVersionWebAppFixtureIntegrationTest extends AbstractWebAppFixtureIntegrationTest {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/Jboss7ServerGoogleComputeLiveTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/Jboss7ServerGoogleComputeLiveTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/Jboss7ServerGoogleComputeLiveTest.java
index 6b37ff2..bb33c57 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/Jboss7ServerGoogleComputeLiveTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/Jboss7ServerGoogleComputeLiveTest.java
@@ -23,13 +23,12 @@ import static org.testng.Assert.assertNotNull;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractGoogleComputeLiveTest;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.HttpTestUtils;
 import org.apache.brooklyn.test.TestResourceUnavailableException;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.AbstractGoogleComputeLiveTest;
-
 import com.google.common.collect.ImmutableList;
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jetty/JettyWebAppFixtureIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jetty/JettyWebAppFixtureIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jetty/JettyWebAppFixtureIntegrationTest.java
index 1f86073..38f8eda 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jetty/JettyWebAppFixtureIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jetty/JettyWebAppFixtureIntegrationTest.java
@@ -20,13 +20,11 @@ package org.apache.brooklyn.entity.webapp.jetty;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.AbstractWebAppFixtureIntegrationTest;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcess;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.location.basic.PortRanges;
 
 public class JettyWebAppFixtureIntegrationTest extends AbstractWebAppFixtureIntegrationTest {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppEc2LiveTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppEc2LiveTest.java
index eb60ad9..0c07c76 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppEc2LiveTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppEc2LiveTest.java
@@ -24,11 +24,10 @@ import static org.apache.brooklyn.entity.webapp.nodejs.NodeJsWebAppFixtureIntegr
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.test.HttpTestUtils;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.collect.ImmutableList;
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppFixtureIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppFixtureIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppFixtureIntegrationTest.java
index fd4c639..898472f 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppFixtureIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppFixtureIntegrationTest.java
@@ -18,8 +18,6 @@
  */
 package org.apache.brooklyn.entity.webapp.nodejs;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
-
 import org.apache.brooklyn.location.basic.PortRanges;
 
 import com.google.common.collect.ImmutableList;
@@ -31,6 +29,7 @@ import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.api.mgmt.ManagementContext;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.entity.webapp.WebAppService;
 import org.apache.brooklyn.entity.webapp.nodejs.NodeJsWebAppService;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSoftlayerLiveTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSoftlayerLiveTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSoftlayerLiveTest.java
index 193ca43..8b21286 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSoftlayerLiveTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSoftlayerLiveTest.java
@@ -24,11 +24,10 @@ import static org.apache.brooklyn.entity.webapp.nodejs.NodeJsWebAppFixtureIntegr
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractSoftlayerLiveTest;
 import org.apache.brooklyn.test.HttpTestUtils;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.AbstractSoftlayerLiveTest;
-
 import com.google.common.collect.ImmutableList;
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerEc2LiveTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerEc2LiveTest.java
index c1ce1ab..2b89ad4 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerEc2LiveTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerEc2LiveTest.java
@@ -21,11 +21,9 @@ package org.apache.brooklyn.entity.webapp.tomcat;
 import static org.testng.Assert.assertNotNull;
 
 import org.testng.annotations.Test;
-
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.HttpTestUtils;
 import org.apache.brooklyn.test.TestResourceUnavailableException;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerRestartIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerRestartIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerRestartIntegrationTest.java
index 33f1f6e..2fbf83a 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerRestartIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerRestartIntegrationTest.java
@@ -19,14 +19,13 @@
 package org.apache.brooklyn.entity.webapp.tomcat;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessRestartIntegrationTest;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.tomcat.Tomcat8Server;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.basic.AbstractSoftwareProcessRestartIntegrationTest;
-import brooklyn.entity.basic.SoftwareProcess;
-
 /**
  * Tests restart of the software *process* (as opposed to the VM).
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerSoftlayerLiveTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerSoftlayerLiveTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerSoftlayerLiveTest.java
index c34385e..bbeb457 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerSoftlayerLiveTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerSoftlayerLiveTest.java
@@ -21,11 +21,9 @@ package org.apache.brooklyn.entity.webapp.tomcat;
 import static org.testng.Assert.assertNotNull;
 
 import org.testng.annotations.Test;
-
-import brooklyn.entity.AbstractSoftlayerLiveTest;
-
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractSoftlayerLiveTest;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.HttpTestUtils;
 import org.apache.brooklyn.test.TestResourceUnavailableException;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerWebAppFixtureIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerWebAppFixtureIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerWebAppFixtureIntegrationTest.java
index 6f28a2b..c6af8c0 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerWebAppFixtureIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerWebAppFixtureIntegrationTest.java
@@ -33,12 +33,10 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.location.basic.PortRanges;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.AbstractWebAppFixtureIntegrationTest;
 import org.apache.brooklyn.entity.webapp.HttpsSslConfig;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcess;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerDisableRetrieveUsageMetricsIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerDisableRetrieveUsageMetricsIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerDisableRetrieveUsageMetricsIntegrationTest.java
index 822ee37..4d17684 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerDisableRetrieveUsageMetricsIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerDisableRetrieveUsageMetricsIntegrationTest.java
@@ -23,12 +23,10 @@ import static org.testng.Assert.assertNull;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerEc2LiveTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerEc2LiveTest.java
index 8a88352..d1eab41 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerEc2LiveTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerEc2LiveTest.java
@@ -23,13 +23,12 @@ import static org.testng.Assert.assertNotNull;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.HttpTestUtils;
 import org.apache.brooklyn.test.TestResourceUnavailableException;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.collect.ImmutableList;
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerRestartIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerRestartIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerRestartIntegrationTest.java
index 173bad8..2f40d6c 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerRestartIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerRestartIntegrationTest.java
@@ -19,14 +19,13 @@
 package org.apache.brooklyn.entity.webapp.tomcat;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessRestartIntegrationTest;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.tomcat.TomcatServer;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.basic.AbstractSoftwareProcessRestartIntegrationTest;
-import brooklyn.entity.basic.SoftwareProcess;
-
 /**
  * Tests restart of the software *process* (as opposed to the VM).
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerSoftlayerLiveTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerSoftlayerLiveTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerSoftlayerLiveTest.java
index f74fde5..a8da230 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerSoftlayerLiveTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerSoftlayerLiveTest.java
@@ -23,13 +23,12 @@ import static org.testng.Assert.assertNotNull;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractSoftlayerLiveTest;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.HttpTestUtils;
 import org.apache.brooklyn.test.TestResourceUnavailableException;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.AbstractSoftlayerLiveTest;
-
 import com.google.common.collect.ImmutableList;
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerWebAppFixtureIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerWebAppFixtureIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerWebAppFixtureIntegrationTest.java
index b288927..43b3143 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerWebAppFixtureIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerWebAppFixtureIntegrationTest.java
@@ -29,6 +29,7 @@ import java.util.concurrent.atomic.AtomicReference;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.AbstractWebAppFixtureIntegrationTest;
 import org.apache.brooklyn.entity.webapp.HttpsSslConfig;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcess;
@@ -41,9 +42,6 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.location.basic.PortRanges;
 
 import com.google.common.collect.ImmutableSet;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/test/entity/TestJavaWebAppEntity.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/test/entity/TestJavaWebAppEntity.java b/software/webapp/src/test/java/org/apache/brooklyn/test/entity/TestJavaWebAppEntity.java
index 89782f5..fc69fd6 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/test/entity/TestJavaWebAppEntity.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/test/entity/TestJavaWebAppEntity.java
@@ -24,17 +24,16 @@ import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.java.VanillaJavaApp;
 import org.apache.brooklyn.entity.lifecycle.Lifecycle;
 import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriverLifecycleEffectorTasks;
 import org.apache.brooklyn.entity.webapp.WebAppService;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.basic.SoftwareProcessDriverLifecycleEffectorTasks;
-import brooklyn.entity.java.VanillaJavaApp;
-
 /**
  * Mock web application server entity for testing.
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/webapp/src/test/java/org/apache/brooklyn/test/entity/TestJavaWebAppEntityImpl.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/test/entity/TestJavaWebAppEntityImpl.java b/software/webapp/src/test/java/org/apache/brooklyn/test/entity/TestJavaWebAppEntityImpl.java
index 7118287..a0f53f6 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/test/entity/TestJavaWebAppEntityImpl.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/test/entity/TestJavaWebAppEntityImpl.java
@@ -21,11 +21,10 @@ package org.apache.brooklyn.test.entity;
 import java.util.Map;
 
 import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.entity.java.VanillaJavaAppImpl;
 import org.apache.brooklyn.entity.webapp.WebAppServiceConstants;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
-import brooklyn.entity.java.VanillaJavaAppImpl;
-
 public class TestJavaWebAppEntityImpl extends VanillaJavaAppImpl implements TestJavaWebAppEntity {
 
     @SetFromFlag public int a;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/camp/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/service/CatalogServiceTypeResolver.java
----------------------------------------------------------------------
diff --git a/usage/camp/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/service/CatalogServiceTypeResolver.java b/usage/camp/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/service/CatalogServiceTypeResolver.java
index 3290ca7..08a04e5 100644
--- a/usage/camp/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/service/CatalogServiceTypeResolver.java
+++ b/usage/camp/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/service/CatalogServiceTypeResolver.java
@@ -22,15 +22,14 @@ import java.util.Map;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.camp.spi.PlatformComponentTemplate;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
 import org.apache.brooklyn.entity.group.DynamicCluster;
 import org.apache.brooklyn.entity.group.DynamicRegionsFabric;
+import org.apache.brooklyn.entity.java.VanillaJavaApp;
+import org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.entity.basic.VanillaSoftwareProcess;
-import brooklyn.entity.brooklynnode.BrooklynNode;
-import brooklyn.entity.java.VanillaJavaApp;
-
 import com.google.common.base.CaseFormat;
 import com.google.common.base.Converter;
 import com.google.common.collect.ImmutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/usage/camp/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/service/ChefServiceTypeResolver.java
----------------------------------------------------------------------
diff --git a/usage/camp/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/service/ChefServiceTypeResolver.java b/usage/camp/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/service/ChefServiceTypeResolver.java
index 00f9582..c0fb5f9 100644
--- a/usage/camp/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/service/ChefServiceTypeResolver.java
+++ b/usage/camp/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/creation/service/ChefServiceTypeResolver.java
@@ -25,11 +25,10 @@ import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.camp.brooklyn.spi.creation.BrooklynComponentTemplateResolver;
 import org.apache.brooklyn.camp.spi.PlatformComponentTemplate;
+import org.apache.brooklyn.entity.chef.ChefConfig;
+import org.apache.brooklyn.entity.chef.ChefEntity;
 import org.apache.brooklyn.util.text.Strings;
 
-import brooklyn.entity.chef.ChefConfig;
-import brooklyn.entity.chef.ChefEntity;
-
 /**
  * This converts {@link PlatformComponentTemplate} instances whose type is prefixed {@code chef:}
  * to Brooklyn {@link EntitySpec} instances.



[43/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/brooklyn/policy/os/AdvertiseWinrmLoginPolicyTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/brooklyn/policy/os/AdvertiseWinrmLoginPolicyTest.java b/locations/jclouds/src/test/java/brooklyn/policy/os/AdvertiseWinrmLoginPolicyTest.java
deleted file mode 100644
index 9646825..0000000
--- a/locations/jclouds/src/test/java/brooklyn/policy/os/AdvertiseWinrmLoginPolicyTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.policy.os;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.policy.PolicySpec;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.WinRmMachineLocation;
-
-import com.google.common.collect.ImmutableList;
-
-public class AdvertiseWinrmLoginPolicyTest extends BrooklynAppUnitTestSupport {
-
-    @Test
-    public void testAdvertisesMachineLoginDetails() throws Exception {
-        TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class)
-                .policy(PolicySpec.create(AdvertiseWinrmLoginPolicy.class)));
-        
-        WinRmMachineLocation machine = mgmt.getLocationManager().createLocation(LocationSpec.create(WinRmMachineLocation.class)
-                .configure("address", "1.2.3.4")
-                .configure("user", "myuser")
-                .configure("port", 5678)
-                .configure("password", "mypassword"));
-        app.start(ImmutableList.of(machine));
-        
-        String expected = "myuser : mypassword @ 1.2.3.4:5678";
-
-        EntityTestUtils.assertAttributeEqualsEventually(entity, AdvertiseWinrmLoginPolicy.VM_USER_CREDENTIALS, expected);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/brooklyn/policy/os/CreateUserPolicyLiveTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/brooklyn/policy/os/CreateUserPolicyLiveTest.java b/locations/jclouds/src/test/java/brooklyn/policy/os/CreateUserPolicyLiveTest.java
deleted file mode 100644
index ff15871..0000000
--- a/locations/jclouds/src/test/java/brooklyn/policy/os/CreateUserPolicyLiveTest.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.policy.os;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.policy.PolicySpec;
-import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.core.internal.ssh.SshTool;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-
-public class CreateUserPolicyLiveTest extends BrooklynAppLiveTestSupport {
-
-    private static final Logger LOG = LoggerFactory.getLogger(CreateUserPolicyLiveTest.class);
-
-    // TODO Fails on OS X
-    @Test(groups={"Integration", "WIP"})
-    public void testIntegrationCreatesUser() throws Exception {
-        LocalhostMachineProvisioningLocation loc = app.newLocalhostProvisioningLocation();
-        runTestCreatesUser(loc);
-    }
-    
-    @Test(groups="Live")
-    @SuppressWarnings("unchecked")
-    public void testLiveCreatesUser() throws Exception {
-        String locSpec = "jclouds:softlayer:ams01";
-        ImmutableMap<String, String> locArgs = ImmutableMap.of("imageId", "CENTOS_6_64");
-        Location loc = mgmt.getLocationRegistry().resolve(locSpec, locArgs);
-        runTestCreatesUser((MachineProvisioningLocation<SshMachineLocation>) loc);
-    }
-    
-    public void runTestCreatesUser(MachineProvisioningLocation<SshMachineLocation> loc) throws Exception {
-        String newUsername = Identifiers.makeRandomId(16);
-        SshMachineLocation machine = loc.obtain(ImmutableMap.of());
-        
-        try {
-            app.createAndManageChild(EntitySpec.create(TestEntity.class)
-                    .policy(PolicySpec.create(CreateUserPolicy.class)
-                            .configure(CreateUserPolicy.GRANT_SUDO, true)
-                            .configure(CreateUserPolicy.VM_USERNAME, newUsername)));
-            TestEntity entity = (TestEntity) Iterables.getOnlyElement(app.getChildren());
-
-            app.start(ImmutableList.of(machine));
-            
-            String creds = EntityTestUtils.assertAttributeEventuallyNonNull(entity, CreateUserPolicy.VM_USER_CREDENTIALS);
-            Pattern pattern = Pattern.compile("(.*) : (.*) @ (.*):(.*)");
-            Matcher matcher = pattern.matcher(creds);
-            assertTrue(matcher.matches());
-            String username = matcher.group(1).trim();
-            String password = matcher.group(2).trim();
-            String hostname = matcher.group(3).trim();
-            String port = matcher.group(4).trim();
-            
-            assertEquals(newUsername, username);
-            assertEquals(hostname, machine.getAddress().getHostName());
-            assertEquals(port, ""+machine.getPort());
-    
-            SshMachineLocation machine2 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                    .configure(SshTool.PROP_USER, newUsername)
-                    .configure(SshMachineLocation.PASSWORD, password)
-                    .configure("address", hostname)
-                    .configure(SshMachineLocation.SSH_PORT, Integer.parseInt(port)));
-            
-            LOG.info("Checking ssh'able for auto-generated user: machine="+machine+"; creds="+creds);
-            assertTrue(machine2.isSshable(), "machine="+machine+"; creds="+creds);
-            
-        } catch (Exception e) {
-            throw e;
-        } finally {
-            LOG.info("Deleting auto-generated user "+newUsername);
-            machine.execScript("delete-user-"+newUsername, ImmutableList.of("sudo userdel -f "+newUsername));
-            
-            loc.release(machine);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/brooklyn/policy/os/CreateUserPolicyTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/brooklyn/policy/os/CreateUserPolicyTest.java b/locations/jclouds/src/test/java/brooklyn/policy/os/CreateUserPolicyTest.java
deleted file mode 100644
index 9e876c4..0000000
--- a/locations/jclouds/src/test/java/brooklyn/policy/os/CreateUserPolicyTest.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.policy.os;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.policy.PolicySpec;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.core.internal.ssh.SshTool;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
-public class CreateUserPolicyTest extends BrooklynAppUnitTestSupport {
-
-    @SuppressWarnings("unused")
-    private static final Logger LOG = LoggerFactory.getLogger(CreateUserPolicyTest.class);
-
-    public static class RecordingSshMachineLocation extends SshMachineLocation {
-        private static final long serialVersionUID = 1641930081769106380L;
-        
-        public static List<List<String>> execScriptCalls = Lists.newArrayList();
-
-        @Override 
-        public int execScript(String summary, List<String> cmds) {
-            execScriptCalls.add(cmds);
-            return 0;
-        }
-        @Override 
-        public int execScript(Map<String,?> props, String summaryForLogging, List<String> cmds) {
-            execScriptCalls.add(cmds);
-            return 0;
-        }
-        @Override 
-        public int execScript(String summaryForLogging, List<String> cmds, Map<String,?> env) {
-            execScriptCalls.add(cmds);
-            return 0;
-        }
-        @Override 
-        public int execScript(Map<String,?> props, String summaryForLogging, List<String> cmds, Map<String,?> env) {
-            execScriptCalls.add(cmds);
-            return 0;
-        }
-    }
-
-    @BeforeMethod(alwaysRun=true)
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-        RecordingSshMachineLocation.execScriptCalls.clear();
-    }
-
-    @AfterMethod(alwaysRun=true)
-    @Override
-    public void tearDown() throws Exception {
-        try {
-            super.tearDown();
-        } finally {
-            RecordingSshMachineLocation.execScriptCalls.clear();
-        }
-    }
-    
-    @Test
-    public void testCallsCreateUser() throws Exception {
-        SshMachineLocation machine = mgmt.getLocationManager().createLocation(LocationSpec.create(RecordingSshMachineLocation.class)
-                .configure(SshTool.PROP_USER, "myuser")
-                .configure(SshTool.PROP_PASSWORD, "mypassword")
-                .configure("address", "1.2.3.4")
-                .configure(SshTool.PROP_PORT, 1234));
-    
-        String newUsername = "mynewuser";
-        
-        app.createAndManageChild(EntitySpec.create(TestEntity.class)
-                .policy(PolicySpec.create(CreateUserPolicy.class)
-                        .configure(CreateUserPolicy.GRANT_SUDO, true)
-                        .configure(CreateUserPolicy.VM_USERNAME, newUsername)));
-        TestEntity entity = (TestEntity) Iterables.getOnlyElement(app.getChildren());
-        app.start(ImmutableList.of(machine));
-        
-        String creds = EntityTestUtils.assertAttributeEventuallyNonNull(entity, CreateUserPolicy.VM_USER_CREDENTIALS);
-        Pattern pattern = Pattern.compile("(.*) : (.*) @ (.*):(.*)");
-        Matcher matcher = pattern.matcher(creds);
-        assertTrue(matcher.matches());
-        String username2 = matcher.group(1).trim();
-        String password = matcher.group(2).trim();
-        String hostname = matcher.group(3).trim();
-        String port = matcher.group(4).trim();
-        
-        assertEquals(newUsername, username2);
-        assertEquals(hostname, "1.2.3.4");
-        assertEquals(password.length(), 12);
-        assertEquals(port, "1234");
-
-        boolean found = false;
-        for (List<String> cmds : RecordingSshMachineLocation.execScriptCalls) {
-            if (cmds.toString().contains("useradd")) {
-                found = true;
-                break;
-            }
-        }
-        assertTrue(found, "useradd not found in: "+RecordingSshMachineLocation.execScriptCalls);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BlobStoreCleaner.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BlobStoreCleaner.java b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BlobStoreCleaner.java
new file mode 100644
index 0000000..8a75382
--- /dev/null
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BlobStoreCleaner.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist.jclouds;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import org.jclouds.ContextBuilder;
+import org.jclouds.blobstore.BlobStoreContext;
+import org.jclouds.blobstore.domain.PageSet;
+import org.jclouds.blobstore.domain.StorageMetadata;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.location.cloud.CloudLocationConfig;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.apache.brooklyn.location.jclouds.JcloudsLocation;
+
+/** Utility for cleaning up after test leaks. Most should not leak of course, but if they do... */
+public class BlobStoreCleaner {
+
+    private static String locationSpec = BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC;
+
+    private static final Logger log = LoggerFactory.getLogger(BlobStoreCleaner.class);
+    
+    public static void main(String[] args) {
+        LocalManagementContextForTests mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault()); 
+        JcloudsLocation location = (JcloudsLocation) mgmt.getLocationRegistry().resolve(locationSpec);
+            
+        String identity = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_IDENTITY), "identity must not be null");
+        String credential = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_CREDENTIAL), "credential must not be null");
+        String provider = checkNotNull(location.getConfig(LocationConfigKeys.CLOUD_PROVIDER), "provider must not be null");
+        String endpoint = location.getConfig(CloudLocationConfig.CLOUD_ENDPOINT);
+
+        BlobStoreContext context = ContextBuilder.newBuilder(provider)
+                .credentials(identity, credential)
+                .endpoint(endpoint)
+                .buildView(BlobStoreContext.class);
+        
+        PageSet<? extends StorageMetadata> containers = context.getBlobStore().list();
+        for (StorageMetadata container: containers) {
+            if (container.getName().matches("brooklyn.*-test.*")
+                // to kill all containers here
+//                || container.getName().matches(".*")
+                ) {
+                log.info("killing - "+container.getName());
+                context.getBlobStore().deleteContainer(container.getName());
+            } else {
+                log.info("KEEPING - "+container.getName());
+            }
+        }
+        context.close();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BlobStoreExpiryTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BlobStoreExpiryTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BlobStoreExpiryTest.java
new file mode 100644
index 0000000..d86fc74
--- /dev/null
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BlobStoreExpiryTest.java
@@ -0,0 +1,196 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist.jclouds;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.jclouds.openstack.reference.AuthHeaders.URL_SUFFIX;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.List;
+import java.util.Map.Entry;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.http.HttpTool;
+import org.apache.brooklyn.util.core.http.HttpToolResponse;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+import org.apache.http.client.HttpClient;
+import org.jclouds.blobstore.BlobStoreContext;
+import org.jclouds.blobstore.domain.PageSet;
+import org.jclouds.blobstore.domain.StorageMetadata;
+import org.jclouds.domain.Credentials;
+import org.jclouds.openstack.domain.AuthenticationResponse;
+import org.jclouds.openstack.reference.AuthHeaders;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.cloud.CloudLocationConfig;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.apache.brooklyn.location.jclouds.JcloudsLocation;
+import org.apache.brooklyn.location.jclouds.JcloudsUtil;
+
+import com.google.common.base.Preconditions;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableMap.Builder;
+import com.google.inject.Inject;
+
+@Test(groups={"Live", "Live-sanity"})
+public class BlobStoreExpiryTest {
+
+    private static final Logger log = LoggerFactory.getLogger(BlobStoreExpiryTest.class);
+    
+    /**
+     * Live tests as written require a location defined as follows:
+     * 
+     * <code>
+     * brooklyn.location.named.brooklyn-jclouds-objstore-test-1==jclouds:swift:https://ams01.objectstorage.softlayer.net/auth/v1.0
+     * brooklyn.location.named.brooklyn-jclouds-objstore-test-1.identity=IBMOS1234-5:yourname
+     * brooklyn.location.named.brooklyn-jclouds-objstore-test-1.credential=0123abcd.......
+     * </code>
+     */
+    
+    public static final String PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC = BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC;
+    public static final String CONTAINER_PREFIX = "brooklyn-persistence-test";
+    private String locationSpec = PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC;
+    
+    private JcloudsLocation location;
+    private BlobStoreContext context;
+
+    private ManagementContext mgmt;
+    private String testContainerName;
+
+    private String identity;
+    private String credential;
+    private String provider;
+    private String endpoint;
+
+    public synchronized BlobStoreContext getSwiftBlobStoreContext() {
+        if (context==null) {
+            if (location==null) {
+                Preconditions.checkNotNull(locationSpec, "locationSpec required for remote object store when location is null");
+                Preconditions.checkNotNull(mgmt, "mgmt required for remote object store when location is null");
+                location = (JcloudsLocation) mgmt.getLocationRegistry().resolve(locationSpec);
+            }
+            
+            identity = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_IDENTITY), "identity must not be null");
+            credential = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_CREDENTIAL), "credential must not be null");
+            provider = checkNotNull(location.getConfig(LocationConfigKeys.CLOUD_PROVIDER), "provider must not be null");
+            endpoint = location.getConfig(CloudLocationConfig.CLOUD_ENDPOINT);
+
+            context = JcloudsUtil.newBlobstoreContext(provider, endpoint, identity, credential);
+        }
+        return context;
+    }
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setup() {
+        testContainerName = CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(8);
+        mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void teardown() {
+        Entities.destroyAll(mgmt);
+        if (context!=null) context.close();
+        context = null;
+    }
+
+    public void testRenewAuthSucceedsInSwiftObjectStore() throws Exception {
+        doTestRenewAuth();
+    }
+    
+    protected void doTestRenewAuth() throws Exception {
+        getSwiftBlobStoreContext();
+        
+        injectShortLivedTokenForSwiftAuth();
+        
+        context.getBlobStore().createContainerInLocation(null, testContainerName);
+        
+        assertContainerFound();
+        
+        log.info("created container, now sleeping for expiration");
+        
+        Time.sleep(Duration.TEN_SECONDS);
+        
+        assertContainerFound();
+
+        context.getBlobStore().deleteContainer(testContainerName);
+    }
+
+    private void assertContainerFound() {
+        PageSet<? extends StorageMetadata> ps = context.getBlobStore().list();
+        BlobStoreTest.assertHasItemNamed(ps, testContainerName);
+    }
+
+    private void injectShortLivedTokenForSwiftAuth() throws Exception {
+        URL endpointUrl = new URL(endpoint);
+
+        HttpToolResponse tokenHttpResponse1 = requestTokenWithExplicitLifetime(endpointUrl,
+            identity, credential, Duration.FIVE_SECONDS);
+        
+        Builder<String, URI> servicesMapBuilder = ImmutableMap.builder();
+        for (Entry<String, List<String>> entry : tokenHttpResponse1.getHeaderLists().entrySet()) {
+            if (entry.getKey().toLowerCase().endsWith(URL_SUFFIX.toLowerCase()) ||
+                    entry.getKey().toLowerCase().endsWith("X-Auth-Token-Expires".toLowerCase())){
+                servicesMapBuilder.put(entry.getKey(), URI.create(entry.getValue().iterator().next()));
+            }
+        }
+        AuthenticationResponse authResponse = new AuthenticationResponse(tokenHttpResponse1.getHeaderLists().get(AuthHeaders.AUTH_TOKEN).get(0), servicesMapBuilder.build());
+
+        getAuthCache().put(new Credentials(identity, credential), authResponse);
+    }
+
+    private LoadingCache<Credentials, AuthenticationResponse> getAuthCache() {
+        return context.utils().injector().getInstance(CachePeeker.class).authenticationResponseCache;
+    }
+    
+    public static class CachePeeker {
+        private final LoadingCache<Credentials, AuthenticationResponse> authenticationResponseCache;
+
+        @Inject
+        protected CachePeeker(LoadingCache<Credentials, AuthenticationResponse> authenticationResponseCache) {
+           this.authenticationResponseCache = authenticationResponseCache;
+        }
+    }
+    
+    public static HttpToolResponse requestTokenWithExplicitLifetime(URL url, String user, String key, Duration expiration) throws URISyntaxException {
+        HttpClient client = HttpTool.httpClientBuilder().build();
+        HttpToolResponse response = HttpTool.httpGet(client, url.toURI(), MutableMap.<String,String>of()
+            .add(AuthHeaders.AUTH_USER, user)
+            .add(AuthHeaders.AUTH_KEY, key)
+            .add("Host", url.getHost())
+            .add("X-Auth-New-Token", "" + true)
+            .add("X-Auth-Token-Lifetime", "" + expiration.toSeconds())
+            );
+//        curl -v https://ams01.objectstorage.softlayer.net/auth/v1.0/v1.0 -H "X-Auth-User: IBMOS12345-2:username" -H "X-Auth-Key: <API KEY>" -H "Host: ams01.objectstorage.softlayer.net" -H "X-Auth-New-Token: true" -H "X-Auth-Token-Lifetime: 15"
+        log.info("Requested token with explicit lifetime: "+expiration+" at "+url+"\n"+response+"\n"+response.getHeaderLists());
+        return response;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BlobStorePersistencePerformanceTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BlobStorePersistencePerformanceTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BlobStorePersistencePerformanceTest.java
new file mode 100644
index 0000000..9690c00
--- /dev/null
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BlobStorePersistencePerformanceTest.java
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+*/
+package org.apache.brooklyn.core.mgmt.persist.jclouds;
+
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore.StoreObjectAccessor;
+import org.apache.brooklyn.core.mgmt.persist.jclouds.JcloudsBlobStoreBasedObjectStore;
+import org.apache.brooklyn.core.test.qa.performance.AbstractPerformanceTest;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+public class BlobStorePersistencePerformanceTest extends AbstractPerformanceTest {
+
+    public static final String LOCATION_SPEC = "named:brooklyn-jclouds-objstore-test-1";
+    
+    JcloudsBlobStoreBasedObjectStore objectStore;
+    StoreObjectAccessor blobstoreAccessor;
+    
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+
+        objectStore = new JcloudsBlobStoreBasedObjectStore(LOCATION_SPEC, "BlobStorePersistencePerformanceTest");
+        objectStore.injectManagementContext(mgmt);
+        objectStore.prepareForSharedUse(PersistMode.AUTO, HighAvailabilityMode.AUTO);
+        blobstoreAccessor = objectStore.newAccessor(Identifiers.makeRandomId(8));
+        
+        app.start(ImmutableList.of(loc));
+    }
+
+    @AfterMethod(alwaysRun=true)
+    @Override
+    public void tearDown() throws Exception {
+        super.tearDown();
+        if (blobstoreAccessor != null) blobstoreAccessor.delete();
+        if (objectStore != null) {
+            objectStore.deleteCompletely();
+            objectStore.close();
+        }
+    }
+    
+    protected int numIterations() {
+        return 100;
+    }
+    
+     @Test(groups={"Live", "Acceptance"})
+     public void testStoreObjectPuts() throws Exception {
+         int numIterations = numIterations();
+         double minRatePerSec = 10 * PERFORMANCE_EXPECTATION;
+         final AtomicInteger i = new AtomicInteger();
+         
+         measureAndAssert("StoreObjectAccessor.put", numIterations, minRatePerSec, new Runnable() {
+             public void run() {
+                 blobstoreAccessor.put(""+i.incrementAndGet());
+             }});
+     }
+ 
+     @Test(groups={"Live", "Acceptance"})
+     public void testStoreObjectGet() throws Exception {
+         // The file system will have done a lot of caching here - we are unlikely to touch the disk more than once.
+         int numIterations = numIterations();
+         double minRatePerSec = 10 * PERFORMANCE_EXPECTATION;
+
+         measureAndAssert("FileBasedStoreObjectAccessor.get", numIterations, minRatePerSec, new Runnable() {
+             public void run() {
+                 blobstoreAccessor.get();
+             }});
+     }
+ 
+     @Test(groups={"Live", "Acceptance"})
+     public void testStoreObjectDelete() throws Exception {
+         int numIterations = numIterations();
+         double minRatePerSec = 10 * PERFORMANCE_EXPECTATION;
+
+         // Will do 10% warm up runs first
+         final List<StoreObjectAccessor> blobstoreAccessors = Lists.newArrayList();
+         for (int i = 0; i < (numIterations * 1.1 + 1); i++) {
+             blobstoreAccessors.add(objectStore.newAccessor("storeObjectDelete-"+i));
+         }
+         
+         final AtomicInteger i = new AtomicInteger();
+
+         try {
+             measureAndAssert("FileBasedStoreObjectAccessor.delete", numIterations, minRatePerSec, new Runnable() {
+                 public void run() {
+                     StoreObjectAccessor blobstoreAccessor = blobstoreAccessors.get(i.getAndIncrement());
+                     blobstoreAccessor.delete();
+                 }});
+         } finally {
+             for (StoreObjectAccessor blobstoreAccessor : blobstoreAccessors) {
+                 blobstoreAccessor.delete();
+             }
+         }
+     }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BlobStoreTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BlobStoreTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BlobStoreTest.java
new file mode 100644
index 0000000..c8e7309
--- /dev/null
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BlobStoreTest.java
@@ -0,0 +1,150 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist.jclouds;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.io.IOException;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.util.stream.Streams;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.jclouds.blobstore.BlobStoreContext;
+import org.jclouds.blobstore.domain.Blob;
+import org.jclouds.blobstore.domain.PageSet;
+import org.jclouds.blobstore.domain.StorageMetadata;
+import org.jclouds.blobstore.options.ListContainerOptions;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.cloud.CloudLocationConfig;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.apache.brooklyn.location.jclouds.JcloudsLocation;
+import org.apache.brooklyn.location.jclouds.JcloudsUtil;
+
+import com.google.common.base.Preconditions;
+
+@Test(groups={"Live", "Live-sanity"})
+public class BlobStoreTest {
+
+    /**
+     * Live tests as written require a location defined as follows:
+     * 
+     * <code>
+     * brooklyn.location.named.brooklyn-jclouds-objstore-test-1==jclouds:swift:https://ams01.objectstorage.softlayer.net/auth/v1.0
+     * brooklyn.location.named.brooklyn-jclouds-objstore-test-1.identity=IBMOS1234-5:yourname
+     * brooklyn.location.named.brooklyn-jclouds-objstore-test-1.credential=0123abcd.......
+     * </code>
+     */
+    public static final String PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC = "named:brooklyn-jclouds-objstore-test-1";
+    
+    public static final String CONTAINER_PREFIX = "brooklyn-persistence-test";
+    
+    private String locationSpec = PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC;
+    
+    private JcloudsLocation location;
+    private BlobStoreContext context;
+
+    private ManagementContext mgmt;
+    private String testContainerName;
+
+    public synchronized BlobStoreContext getBlobStoreContext() {
+        if (context==null) {
+            if (location==null) {
+                Preconditions.checkNotNull(locationSpec, "locationSpec required for remote object store when location is null");
+                Preconditions.checkNotNull(mgmt, "mgmt required for remote object store when location is null");
+                location = (JcloudsLocation) mgmt.getLocationRegistry().resolve(locationSpec);
+            }
+            
+            String identity = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_IDENTITY), "identity must not be null");
+            String credential = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_CREDENTIAL), "credential must not be null");
+            String provider = checkNotNull(location.getConfig(LocationConfigKeys.CLOUD_PROVIDER), "provider must not be null");
+            String endpoint = location.getConfig(CloudLocationConfig.CLOUD_ENDPOINT);
+
+            context = JcloudsUtil.newBlobstoreContext(provider, endpoint, identity, credential);
+        }
+        return context;
+    }
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setup() {
+        testContainerName = CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(8);
+        mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());
+        getBlobStoreContext();
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void teardown() {
+        Entities.destroyAll(mgmt);
+    }
+    
+    public void testCreateListDestroyContainer() throws IOException {
+        context.getBlobStore().createContainerInLocation(null, testContainerName);
+        context.getBlobStore().list(testContainerName);
+        PageSet<? extends StorageMetadata> ps = context.getBlobStore().list();
+        assertHasItemNamed(ps, testContainerName);
+        
+        Blob b = context.getBlobStore().blobBuilder("my-blob-1").payload(Streams.newInputStreamWithContents("hello world")).build();
+        context.getBlobStore().putBlob(testContainerName, b);
+        
+        Blob b2 = context.getBlobStore().getBlob(testContainerName, "my-blob-1");
+        Assert.assertEquals(Streams.readFullyString(b2.getPayload().openStream()), "hello world");
+        
+        context.getBlobStore().deleteContainer(testContainerName);
+    }
+    
+    public void testCreateListDestroySimpleDirInContainer() throws IOException {
+        context.getBlobStore().createContainerInLocation(null, testContainerName);
+        context.getBlobStore().createDirectory(testContainerName, "my-dir-1");
+        
+        PageSet<? extends StorageMetadata> ps = context.getBlobStore().list(testContainerName);
+        assertHasItemNamed(ps, "my-dir-1");
+        
+        Blob b = context.getBlobStore().blobBuilder("my-blob-1").payload(Streams.newInputStreamWithContents("hello world")).build();
+        context.getBlobStore().putBlob(testContainerName+"/"+"my-dir-1", b);
+        
+        ps = context.getBlobStore().list(testContainerName, ListContainerOptions.Builder.inDirectory("my-dir-1"));
+        assertHasItemNamed(ps, "my-dir-1/my-blob-1");
+
+        // both these syntaxes work:
+        Blob b2 = context.getBlobStore().getBlob(testContainerName+"/"+"my-dir-1", "my-blob-1");
+        Assert.assertEquals(Streams.readFullyString(b2.getPayload().openStream()), "hello world");
+
+        Blob b3 = context.getBlobStore().getBlob(testContainerName, "my-dir-1"+"/"+"my-blob-1");
+        Assert.assertEquals(Streams.readFullyString(b3.getPayload().openStream()), "hello world");
+
+        context.getBlobStore().deleteContainer(testContainerName);
+    }
+
+    static void assertHasItemNamed(PageSet<? extends StorageMetadata> ps, String name) {
+        if (!hasItemNamed(ps, name))
+            Assert.fail("No item named '"+name+"' in "+ps);
+    }
+
+    static boolean hasItemNamed(PageSet<? extends StorageMetadata> ps, String name) {
+        for (StorageMetadata sm: ps)
+            if (name==null || name.equals(sm.getName())) return true;
+        return false;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BrooklynMementoPersisterJcloudsObjectStoreTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BrooklynMementoPersisterJcloudsObjectStoreTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BrooklynMementoPersisterJcloudsObjectStoreTest.java
new file mode 100644
index 0000000..a94424e
--- /dev/null
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/BrooklynMementoPersisterJcloudsObjectStoreTest.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist.jclouds;
+
+
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterTestFixture;
+import org.apache.brooklyn.core.mgmt.persist.jclouds.JcloudsBlobStoreBasedObjectStore;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.apache.brooklyn.util.time.Duration;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+/**
+ * @author Andrea Turli
+ */
+@Test(groups={"Live", "Live-sanity"})
+public class BrooklynMementoPersisterJcloudsObjectStoreTest extends BrooklynMementoPersisterTestFixture {
+
+    @Override @BeforeMethod
+    public void setUp() throws Exception { super.setUp(); }
+    
+    protected LocalManagementContext newPersistingManagementContext() {
+        objectStore = new JcloudsBlobStoreBasedObjectStore(
+            BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4));
+        return RebindTestUtils.managementContextBuilder(classLoader, objectStore)
+            .persistPeriod(Duration.ONE_MILLISECOND)
+            .properties(BrooklynProperties.Factory.newDefault())
+            .buildStarted();
+    }
+    
+    @Test(groups={"Live", "Live-sanity"})
+    @Override
+    public void testCheckPointAndLoadMemento() throws Exception {
+        super.testCheckPointAndLoadMemento();
+    }
+    
+    @Test(groups={"Live", "Live-sanity"})
+    @Override
+    public void testDeleteAndLoadMemento() throws Exception {
+        super.testDeleteAndLoadMemento();
+    }
+    
+    @Test(groups={"Live", "Live-sanity"})
+    @Override
+    public void testLoadAndCheckpointRawMemento() throws Exception {
+        super.testLoadAndCheckpointRawMemento();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/EntityToBlobStorePersistencePerformanceTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/EntityToBlobStorePersistencePerformanceTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/EntityToBlobStorePersistencePerformanceTest.java
new file mode 100644
index 0000000..24a38a2
--- /dev/null
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/EntityToBlobStorePersistencePerformanceTest.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+*/
+package org.apache.brooklyn.core.mgmt.persist.jclouds;
+
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.mgmt.persist.jclouds.JcloudsBlobStoreBasedObjectStore;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
+import org.apache.brooklyn.core.test.qa.performance.EntityPersistencePerformanceTest;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.Test;
+
+public class EntityToBlobStorePersistencePerformanceTest extends EntityPersistencePerformanceTest {
+
+    private static final String LOCATION_SPEC = BlobStorePersistencePerformanceTest.LOCATION_SPEC;
+    
+    private JcloudsBlobStoreBasedObjectStore objectStore;
+
+    @Override
+    protected LocalManagementContext createOrigManagementContext() {
+        objectStore = new JcloudsBlobStoreBasedObjectStore(LOCATION_SPEC, "EntityToBlobStorePersistencePerformanceTest");
+        
+        return RebindTestUtils.managementContextBuilder(classLoader, objectStore)
+                .forLive(true)
+                .persistPeriodMillis(getPersistPeriodMillis())
+                .buildStarted();
+    }
+
+    @AfterMethod(alwaysRun=true)
+    @Override
+    public void tearDown() throws Exception {
+        super.tearDown();
+        if (objectStore != null) {
+            objectStore.deleteCompletely();
+            objectStore.close();
+        }
+    }
+
+    @Test(groups="Live")
+    @Override
+    public void testManyEntities() throws Exception {
+        super.testManyEntities();
+    }
+    
+    @Test(groups="Live")
+    @Override
+    public void testRapidChanges() throws Exception {
+        super.testRapidChanges();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/HighAvailabilityManagerJcloudsObjectStoreTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/HighAvailabilityManagerJcloudsObjectStoreTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/HighAvailabilityManagerJcloudsObjectStoreTest.java
new file mode 100644
index 0000000..c89064b
--- /dev/null
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/HighAvailabilityManagerJcloudsObjectStoreTest.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist.jclouds;
+
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.ha.HighAvailabilityManagerTestFixture;
+import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.jclouds.JcloudsBlobStoreBasedObjectStore;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+@Test(groups={"Live", "Live-sanity"})
+public class HighAvailabilityManagerJcloudsObjectStoreTest extends HighAvailabilityManagerTestFixture {
+
+    protected ManagementContextInternal newLocalManagementContext() {
+        return new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());
+    }
+
+    @Override @BeforeMethod
+    public void setUp() throws Exception { super.setUp(); }
+    
+    protected PersistenceObjectStore newPersistenceObjectStore() {
+        return new JcloudsBlobStoreBasedObjectStore(
+            BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4));
+    }
+
+    @Test(groups="Live", invocationCount=5) //run fewer times w softlayer... 
+    public void testGetManagementPlaneStatusManyTimes() throws Exception {
+        testGetManagementPlaneStatus();
+    }
+    
+    @Test(groups={"Live", "Live-sanity"})
+    @Override
+    public void testDoesNotPromoteIfMasterTimeoutNotExpired() throws Exception {
+        super.testDoesNotPromoteIfMasterTimeoutNotExpired();
+    }
+    
+    @Test(groups={"Live", "Live-sanity"})
+    @Override
+    public void testGetManagementPlaneStatus() throws Exception {
+        super.testGetManagementPlaneStatus();
+    }
+    
+    @Test(groups={"Live", "Live-sanity"})
+    @Override
+    public void testPromotes() throws Exception {
+        super.testPromotes();
+    }
+
+    @Test(groups={"Live", "Live-sanity"})
+    @Override
+    public void testGetManagementPlaneSyncStateInfersTimedOutNodeAsFailed() throws Exception {
+        super.testGetManagementPlaneSyncStateInfersTimedOutNodeAsFailed();
+    }
+    
+    @Test(groups={"Live", "Live-sanity"})
+    @Override
+    public void testGetManagementPlaneSyncStateDoesNotThrowNpeBeforePersisterSet() throws Exception {
+        super.testGetManagementPlaneSyncStateDoesNotThrowNpeBeforePersisterSet();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsBlobStoreBasedObjectStoreTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsBlobStoreBasedObjectStoreTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsBlobStoreBasedObjectStoreTest.java
new file mode 100644
index 0000000..89c9040
--- /dev/null
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsBlobStoreBasedObjectStoreTest.java
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist.jclouds;
+
+
+import java.util.List;
+
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynPersistenceUtils;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore.StoreObjectAccessor;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.apache.brooklyn.util.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Stopwatch;
+
+/**
+ * @author Andrea Turli
+ */
+@Test(groups={"Live", "Live-sanity"})
+public class JcloudsBlobStoreBasedObjectStoreTest {
+
+    private static final Logger log = LoggerFactory.getLogger(JcloudsBlobStoreBasedObjectStoreTest.class);
+    
+    private List<PersistenceObjectStore> objectStores = MutableList.of();;
+    private LocalManagementContext mgmt;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception { 
+        mgmt = LocalManagementContextForTests.builder(true).useDefaultProperties().build();
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        for (PersistenceObjectStore store: objectStores) store.deleteCompletely();
+        Entities.destroyAll(mgmt);
+        objectStores.clear();
+    }
+
+    public PersistenceObjectStore newObjectStore(String spec, String container) {
+        PersistenceObjectStore newObjectStore = BrooklynPersistenceUtils.newPersistenceObjectStore(mgmt, spec, container);
+        objectStores.add(newObjectStore);
+        return newObjectStore;
+    }
+    
+    @Test(groups={"Integration"})
+    public void testLocalhost() throws Exception {
+        doTestWithStore( newObjectStore(null, 
+            BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4)) );
+    }
+    
+    @Test(groups={"Integration"})
+    public void testLocalhostWithSubPathInContainerName() throws Exception {
+        doTestWithStore( newObjectStore(null, 
+            BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4)+"/subpath1/subpath2") );
+    }
+    
+    @Test(groups={"Live", "Live-sanity"})
+    public void testJclouds() throws Exception {
+        doTestWithStore( newObjectStore(BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, 
+            BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4)) );
+    }
+    
+    @Test(groups={"Live", "Live-sanity"})
+    public void testJcloudsWithSubPathInContainerName() throws Exception {
+        doTestWithStore( newObjectStore(BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, 
+            BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4)+"/subpath1/subpath2") );
+    }
+    
+    protected void doTestWithStore(PersistenceObjectStore objectStore) {
+        log.info("testing against "+objectStore.getSummaryName());
+        
+        objectStore.createSubPath("foo");
+        StoreObjectAccessor f = objectStore.newAccessor("foo/file1.txt");
+        Assert.assertFalse(f.exists());
+
+        Stopwatch timer = Stopwatch.createStarted();
+        f.append("Hello world");
+        log.info("created in "+Duration.of(timer));
+        timer.reset();
+        Assert.assertEquals(f.get(), "Hello world");
+        log.info("retrieved in "+Duration.of(timer));
+        Assert.assertTrue(f.exists());
+        
+        timer.reset();
+        List<String> files = objectStore.listContentsWithSubPath("foo");
+        log.info("list retrieved in "+Duration.of(timer)+"; is: "+files);
+        Assert.assertEquals(files, MutableList.of("foo/file1.txt"));
+        
+        f.delete();
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsExpect100ContinueTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsExpect100ContinueTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsExpect100ContinueTest.java
new file mode 100644
index 0000000..b78cc48
--- /dev/null
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsExpect100ContinueTest.java
@@ -0,0 +1,148 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist.jclouds;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.jclouds.blobstore.BlobStore;
+import org.jclouds.blobstore.BlobStoreContext;
+import org.jclouds.blobstore.domain.Blob;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.jclouds.JcloudsLocation;
+import org.apache.brooklyn.location.jclouds.JcloudsUtil;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+
+import com.google.common.base.Charsets;
+import com.google.common.io.ByteSource;
+
+public class JcloudsExpect100ContinueTest {
+    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(JcloudsExpect100ContinueTest.class);
+
+    private static String LOCATION_SPEC = BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC;
+    private static final String OBJECT_NAME_PUT = "test_put";
+    private static final String OBJECT_NAME_GET = "test_get";
+    
+    private ManagementContext mgmt;
+    private BlobStoreContext context;
+    private String containerName;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        // It's important to disable jclouds debug logging
+        // as it "fixes" the issue.
+        setInfoLevel(Logger.ROOT_LOGGER_NAME);
+        setInfoLevel("jclouds");
+        setInfoLevel("org.jclouds");
+
+        mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());
+        JcloudsLocation jcloudsLocation = (JcloudsLocation) mgmt.getLocationRegistry().resolve(LOCATION_SPEC);
+        context = JcloudsUtil.newBlobstoreContext(
+                jcloudsLocation.getProvider(),
+                jcloudsLocation.getEndpoint(),
+                jcloudsLocation.getIdentity(),
+                jcloudsLocation.getCredential());
+        containerName = BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(8);
+        context.getBlobStore().createContainerInLocation(null, containerName);
+    }
+
+    private void setInfoLevel(String loggerName) {
+        Logger logger = (Logger) LoggerFactory.getLogger(loggerName);
+        logger.setLevel(Level.INFO);
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        try {
+            context.getBlobStore().deleteContainer(containerName);
+        } catch (Exception e){}
+        context.close();
+        Entities.destroyAll(mgmt);
+    }
+    
+    @Test(groups = "Live", timeOut=240000)
+    public void testPutAfterUnclosedGet() {
+        put(OBJECT_NAME_PUT, getContent());
+        put(OBJECT_NAME_GET, getContent());
+
+        for (int i = 1; i <= 50; i++) {
+            long start = System.currentTimeMillis();
+            get(OBJECT_NAME_GET);
+            long afterGet = System.currentTimeMillis();
+            LOG.info(i + ". GET @" + (afterGet - start));
+
+            System.gc();
+            System.gc();
+            System.gc();
+            sleep(1000);
+
+            // Without excluding Expect: 100-Continue header
+            // the PUT is supposed to block until the server
+            // times out
+
+            long beforePut = System.currentTimeMillis();
+            put(OBJECT_NAME_PUT, getContent());
+            long end = System.currentTimeMillis();
+            LOG.info(i + ". PUT @" + (end - beforePut));
+        }
+    }
+
+    private String getContent() {
+        return "1234567890";
+    }
+
+    private void put(String name, String content) {
+        BlobStore blobStore = context.getBlobStore();
+        byte[] bytes = content.getBytes(Charsets.UTF_8);
+        Blob blob = blobStore.blobBuilder(name)
+                .payload(ByteSource.wrap(bytes))
+                .contentLength(bytes.length)
+                .build();
+        try {
+            blobStore.putBlob(containerName, blob);
+        } catch (Exception e) {
+            LOG.error("PUT " + name + " failed", e);
+        }
+    }
+
+    private Blob get(String name) {
+        try {
+            BlobStore blobStore = context.getBlobStore();
+            return blobStore.getBlob(containerName, name);
+        } catch (Exception e) {
+            LOG.error("GET " + name + " failed", e);
+            return null;
+        }
+    }
+
+    private void sleep(long millis) {
+        try {
+            Thread.sleep(millis);
+        } catch (InterruptedException e) {
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsObjectStoreAccessorWriterTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsObjectStoreAccessorWriterTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsObjectStoreAccessorWriterTest.java
new file mode 100644
index 0000000..446fd4a
--- /dev/null
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsObjectStoreAccessorWriterTest.java
@@ -0,0 +1,182 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist.jclouds;
+
+import java.io.IOException;
+
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceStoreObjectAccessorWriterTestFixture;
+import org.apache.brooklyn.core.mgmt.persist.StoreObjectAccessorLocking;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore.StoreObjectAccessorWithLock;
+import org.apache.brooklyn.core.mgmt.persist.jclouds.JcloudsBlobStoreBasedObjectStore;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.net.Urls;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.apache.brooklyn.util.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+@Test(groups={"Live", "Live-sanity"})
+public class JcloudsObjectStoreAccessorWriterTest extends PersistenceStoreObjectAccessorWriterTestFixture {
+
+    private static final Logger log = LoggerFactory.getLogger(JcloudsObjectStoreAccessorWriterTest.class);
+    
+    private JcloudsBlobStoreBasedObjectStore store;
+    private LocalManagementContextForTests mgmt;
+
+    @Override @BeforeMethod
+    public void setUp() throws Exception {
+        store = new JcloudsBlobStoreBasedObjectStore(
+            BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4));
+        store.injectManagementContext(mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault()));
+        store.prepareForSharedUse(PersistMode.CLEAN, HighAvailabilityMode.DISABLED);
+        super.setUp();
+    }
+
+    @Override @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        super.tearDown();
+        if (mgmt!=null) Entities.destroyAll(mgmt);
+        if (store!=null) store.deleteCompletely();
+    }
+    
+    protected StoreObjectAccessorWithLock newPersistenceStoreObjectAccessor() throws IOException {
+        return newPersistenceStoreObjectAccessor(store, "");
+    }
+    protected StoreObjectAccessorWithLock newPersistenceStoreObjectAccessor(JcloudsBlobStoreBasedObjectStore aStore, String prefix) throws IOException {
+        return new StoreObjectAccessorLocking(aStore.newAccessor(prefix+"sample-file-"+Identifiers.makeRandomId(4)));
+    }
+
+    @Override
+    protected Duration getLastModifiedResolution() {
+        // Not sure what timing resolution is on things like Softlayer's Swift.
+        // It passed for Aled repeatedly on 2014-11-05 with 2 seconds.
+        return Duration.seconds(2);
+    }
+    
+    protected int biggishSize() {
+        // bit smaller since it's actually uploading here!
+        return 10000;
+    }
+
+    /** Tests what happen when we ask the store to be in a container with a path, e.g. path1/path2 
+     * and then the accessor to a file within that (path3/file) --
+     * this does it an emulated way, where the store tracks the subpath so we don't have to */
+    @Test(groups={"Live"})
+    public void testNestedPath1() throws IOException {
+        mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());
+        String path1 = BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4);
+        String path2 = BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4);
+        String path3 = BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4);
+        JcloudsBlobStoreBasedObjectStore store0 = null;
+        try {
+            store0 = new JcloudsBlobStoreBasedObjectStore(BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, Urls.mergePaths(path1, path2));
+            store0.injectManagementContext(mgmt);
+            store0.prepareForSharedUse(PersistMode.CLEAN, HighAvailabilityMode.DISABLED);
+
+            newPersistenceStoreObjectAccessor(store0, path3+"/").put("hello world");
+        } catch (Exception e) {
+            log.warn("Failed with: "+e, e);
+            throw Exceptions.propagate(e);
+            
+        } finally {
+            store0.deleteCompletely();
+            
+            JcloudsBlobStoreBasedObjectStore storeD = new JcloudsBlobStoreBasedObjectStore(BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, path1);
+            storeD.injectManagementContext(mgmt);
+            storeD.prepareForSharedUse(PersistMode.CLEAN, HighAvailabilityMode.DISABLED);
+            storeD.deleteCompletely();
+        }
+    }
+
+    /** Tests what happen when we ask the store to be in a container with a path, e.g. path1/path2 
+     * and then the accessor to a file within that (path3/file) --
+     * this does it the "official" way, where we ask for the store's container
+     * to be the first path segment */
+    @Test(groups={"Live"})
+    public void testNestedPath2() throws IOException {
+        mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());
+        String path1 = BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4);
+        String path2 = BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4);
+        String path3 = BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4);
+        JcloudsBlobStoreBasedObjectStore store1 = null, store2 = null;
+        try {
+            store1 = new JcloudsBlobStoreBasedObjectStore(BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, 
+                path1);
+            store1.injectManagementContext(mgmt);
+            store1.prepareForSharedUse(PersistMode.CLEAN, HighAvailabilityMode.DISABLED);
+            store1.createSubPath(path2);
+            newPersistenceStoreObjectAccessor(store1, path2+"/"+path3+"/").put("hello world");
+            
+            store2 = new JcloudsBlobStoreBasedObjectStore(BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, 
+                Urls.mergePaths(path1, path2));
+            store2.injectManagementContext(mgmt);
+            store2.prepareForSharedUse(PersistMode.CLEAN, HighAvailabilityMode.DISABLED);
+
+            newPersistenceStoreObjectAccessor(store2, path3+"/").put("hello world");
+            
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            // this doesn't work
+//            store2.deleteCompletely();
+            // this is how you have to do it:
+            store1.newAccessor(path2).delete();
+            
+            store1.deleteCompletely();
+        }
+    }
+
+    @Test(groups={"Live", "Live-sanity"})
+    @Override
+    public void testWriteBacklogThenDeleteWillLeaveFileDeleted() throws Exception {
+        super.testWriteBacklogThenDeleteWillLeaveFileDeleted();
+    }
+    
+    @Test(groups={"Live", "Live-sanity"})
+    @Override
+    public void testWritesFile() throws Exception {
+        super.testWritesFile();
+    }
+
+    @Test(groups={"Live", "Live-sanity"})
+    @Override
+    public void testLastModifiedTime() throws Exception {
+        super.testLastModifiedTime();
+    }
+    
+    @Test(groups={"Live", "Live-sanity"})
+    @Override
+    public void testExists() throws Exception {
+        super.testExists();
+    }
+    
+    @Test(groups={"Live", "Live-sanity"})
+    @Override
+    public void testAppendsFile() throws Exception {
+        super.testAppendsFile();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/AbstractJcloudsLiveTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/AbstractJcloudsLiveTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/AbstractJcloudsLiveTest.java
index 0f8518a..ae8e254 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/AbstractJcloudsLiveTest.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/AbstractJcloudsLiveTest.java
@@ -34,7 +34,7 @@ import org.apache.brooklyn.core.internal.BrooklynProperties;
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
 import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/BailOutJcloudsLocation.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/BailOutJcloudsLocation.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/BailOutJcloudsLocation.java
index bec2262..d31d7e5 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/BailOutJcloudsLocation.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/BailOutJcloudsLocation.java
@@ -46,9 +46,11 @@ import com.google.common.reflect.TypeToken;
 
 public class BailOutJcloudsLocation extends JcloudsLocation {
 
+    public static final String ERROR_MESSAGE = "early termination for test";
+    public static final RuntimeException BAIL_OUT_FOR_TESTING = new RuntimeException(ERROR_MESSAGE);
+    
     // Don't care which image; not actually provisioning
     private static final String US_EAST_IMAGE_ID = "us-east-1/ami-7d7bfc14";
-    public static final RuntimeException BAIL_OUT_FOR_TESTING = new RuntimeException("early termination for test");
 
     public static final ConfigKey<Function<ConfigBag, Void>> BUILD_TEMPLATE_INTERCEPTOR = ConfigKeys.newConfigKey(
             new TypeToken<Function<ConfigBag, Void>>() {},

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/BrooklynMachinePoolLiveTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/BrooklynMachinePoolLiveTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/BrooklynMachinePoolLiveTest.java
index e379df1..2f6afcb 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/BrooklynMachinePoolLiveTest.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/BrooklynMachinePoolLiveTest.java
@@ -26,9 +26,9 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.location.jclouds.pool.MachinePoolPredicates;
 import org.apache.brooklyn.location.jclouds.pool.ReusableMachineTemplate;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 public class BrooklynMachinePoolLiveTest {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsAddressesLiveTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsAddressesLiveTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsAddressesLiveTest.java
index 86cd8a4..0d1ed21 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsAddressesLiveTest.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsAddressesLiveTest.java
@@ -29,8 +29,8 @@ import java.util.Map;
 import java.util.Set;
 
 import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.Locations;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.stream.Streams;
 import org.slf4j.Logger;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolverAwsLiveTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolverAwsLiveTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolverAwsLiveTest.java
index 755c74a..486f5e7 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolverAwsLiveTest.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolverAwsLiveTest.java
@@ -29,7 +29,7 @@ import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolverSoftlayerLiveTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolverSoftlayerLiveTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolverSoftlayerLiveTest.java
index e0ccaec..112e039 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolverSoftlayerLiveTest.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolverSoftlayerLiveTest.java
@@ -24,7 +24,7 @@ import static org.testng.Assert.assertTrue;
 import java.util.Set;
 
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolverTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolverTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolverTest.java
index 6377d47..6b70773 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolverTest.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsByonLocationResolverTest.java
@@ -25,7 +25,7 @@ import java.util.NoSuchElementException;
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
 import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationMetadataTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationMetadataTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationMetadataTest.java
index da4979d..ebbec3f 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationMetadataTest.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationMetadataTest.java
@@ -28,7 +28,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
 
 import com.google.common.collect.ImmutableSet;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationRebindMachineLiveTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationRebindMachineLiveTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationRebindMachineLiveTest.java
index 006f62e..bf9ad59 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationRebindMachineLiveTest.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationRebindMachineLiveTest.java
@@ -26,7 +26,7 @@ import static org.testng.Assert.assertTrue;
 import java.net.InetAddress;
 import java.util.Collections;
 
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationResolverTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationResolverTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationResolverTest.java
index df9a988..779bf6b 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationResolverTest.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationResolverTest.java
@@ -30,8 +30,8 @@ import org.apache.brooklyn.core.config.SetConfigKey;
 import org.apache.brooklyn.core.internal.BrooklynProperties;
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.location.basic.LocationInternal;
 import org.apache.brooklyn.location.cloud.CloudLocationConfig;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.collections.MutableSet;
 import org.slf4j.Logger;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationTest.java
index af47ccc..8f4129d 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationTest.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLocationTest.java
@@ -38,6 +38,7 @@ import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.location.cloud.names.CustomMachineNamer;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.config.ConfigBag;
@@ -58,7 +59,6 @@ import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.reflect.TypeToken;
 
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
 import org.apache.brooklyn.location.geo.HostGeoInfo;
 import org.apache.brooklyn.location.jclouds.JcloudsLocation.UserCreation;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLoginLiveTest.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLoginLiveTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLoginLiveTest.java
index 9b0c873..aa61487 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLoginLiveTest.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/JcloudsLoginLiveTest.java
@@ -28,7 +28,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.Test;
 import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.os.Os;
 import org.apache.brooklyn.util.stream.Streams;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/LiveTestEntity.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/LiveTestEntity.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/LiveTestEntity.java
index 98082c9..4bbf385 100644
--- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/LiveTestEntity.java
+++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/LiveTestEntity.java
@@ -29,7 +29,7 @@ import org.apache.brooklyn.core.test.entity.TestEntityImpl;
 import org.apache.brooklyn.entity.lifecycle.Lifecycle;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.LocationInternal;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 
 import com.google.common.base.Predicates;
 import com.google.common.base.Throwables;



[19/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricher.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricher.java b/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricher.java
new file mode 100644
index 0000000..0bc98d1
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricher.java
@@ -0,0 +1,152 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.system_service;
+
+import java.util.Set;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.mgmt.ExecutionContext;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.api.sensor.Enricher;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags.WrappedStream;
+import org.apache.brooklyn.effector.core.EffectorTasks;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.sensor.enricher.AbstractEnricher;
+import org.apache.brooklyn.util.core.task.BasicExecutionManager;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.TaskBuilder;
+import org.apache.brooklyn.util.core.task.ssh.SshPutTaskWrapper;
+import org.apache.brooklyn.util.core.task.ssh.SshTasks;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskFactory;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.apache.brooklyn.util.net.Urls;
+
+import com.google.common.collect.ImmutableSet;
+
+public class SystemServiceEnricher extends AbstractEnricher implements Enricher {
+    public static final String DEFAULT_ENRICHER_UNIQUE_TAG = "systemService.tag";
+    protected static final Set<String> LAUNCH_EFFECTOR_NAMES = ImmutableSet.of("start", "restart");
+    public static final ConfigKey<String> LAUNCH_SCRIPT_NAME = ConfigKeys.newStringConfigKey(
+            "service.script_name", "The name of the launch script to be created in the runtime directory of the entity.", "service-launch.sh");
+    public static final ConfigKey<String> SERVICE_NAME = ConfigKeys.newStringConfigKey(
+            "service.name", "The name of the system service. Can use ${entity_name} and ${id} variables to template the value.", "${entity_name}-${id}");
+
+    @Override
+    public void setEntity(EntityLocal entity) {
+        super.setEntity(entity);
+        subscribeLaunch();
+        uniqueTag = DEFAULT_ENRICHER_UNIQUE_TAG;
+    }
+
+    private void subscribeLaunch() {
+        subscribe(entity, Attributes.SERVICE_STATE_ACTUAL, new EntityLaunchListener(this));
+    }
+
+    public void onLaunched(Task<?> task) {
+        WrappedStream streamStdin = BrooklynTaskTags.stream(task, BrooklynTaskTags.STREAM_STDIN);
+        if (streamStdin == null) return;
+
+        WrappedStream streamEnv = BrooklynTaskTags.stream(task, BrooklynTaskTags.STREAM_ENV);
+        String stdin = streamStdin.streamContents.get();
+        String env = streamEnv.streamContents.get();
+
+        final SshMachineLocation sshMachine = EffectorTasks.getSshMachine(entity);
+        final String launchScriptPath = Urls.mergePaths(getRunDir(), getStartScriptName());
+
+        Task<Void> installerTask = TaskBuilder.<Void>builder()
+                .name("install (service)")
+                .description("Install as a system service")
+                .body(new Runnable() {
+                    @Override
+                    public void run() {
+                        ProcessTaskFactory<Integer> taskFactory = SshTasks.newSshExecTaskFactory(sshMachine, "[ -e '" + launchScriptPath + "' ]")
+                                .summary("check installed")
+                                .allowingNonZeroExitCode();
+                        boolean isInstalled = DynamicTasks.queue(taskFactory).get() == 0;
+                        if (!isInstalled) {
+                            Task<?> serviceInstallTask = SystemServiceInstallerFactory.of(entity, SystemServiceEnricher.this).getServiceInstallTask();
+                            DynamicTasks.queue(serviceInstallTask);
+                        }
+                    }
+                })
+                .build();
+
+        SshPutTaskWrapper updateLaunchScriptTask = SshTasks.newSshPutTaskFactory(sshMachine, launchScriptPath).contents(getLaunchScript(stdin, env)).newTask();
+        ProcessTaskWrapper<Integer> makeExecutableTask = SshTasks.newSshExecTaskFactory(sshMachine, "chmod +x " + launchScriptPath)
+                .requiringExitCodeZero()
+                .newTask();
+        Task<Void> udpateTask = TaskBuilder.<Void>builder()
+                .name("update-launch")
+                .description("Update launch script used by the system service")
+                .add(updateLaunchScriptTask)
+                .add(makeExecutableTask)
+                .build();
+
+        Task<Void> updateService = TaskBuilder.<Void>builder()
+                .name("update-system-service")
+                .description("Update system service")
+                .add(installerTask)
+                .add(udpateTask)
+                .tag(BrooklynTaskTags.tagForContextEntity(entity))
+                .tag(BrooklynTaskTags.NON_TRANSIENT_TASK_TAG)
+                .build();
+
+        submitTopLevel(updateService);
+    }
+
+    private void submitTopLevel(Task<Void> updateService) {
+        Task<?> currentTask = BasicExecutionManager.getPerThreadCurrentTask().get();
+        BasicExecutionManager.getPerThreadCurrentTask().set(null);
+        try {
+            Entities.submit(entity, updateService);
+        } finally {
+            BasicExecutionManager.getPerThreadCurrentTask().set(currentTask);
+        }
+    }
+
+    private String getLaunchScript(String stdin, String env) {
+        // (?m) - multiline enable
+        // insert export at beginning of each line
+        return env.replaceAll("(?m)^", "export ") + "\n" + stdin;
+    }
+
+    private String getRunDir() {
+        return entity.getAttribute(SoftwareProcess.RUN_DIR);
+    }
+
+    private String getStartScriptName() {
+        return config().get(LAUNCH_SCRIPT_NAME);
+    }
+
+    ExecutionContext getEntityExecutionContext() {
+        return getManagementContext().getExecutionContext(entity);
+    }
+
+    protected Entity getEntity() {
+        return entity;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceInstaller.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceInstaller.java b/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceInstaller.java
new file mode 100644
index 0000000..ee4f242
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceInstaller.java
@@ -0,0 +1,25 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.system_service;
+
+import org.apache.brooklyn.api.mgmt.Task;
+
+public interface SystemServiceInstaller {
+    Task<?> getServiceInstallTask();
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceInstallerFactory.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceInstallerFactory.java b/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceInstallerFactory.java
new file mode 100644
index 0000000..20edfd2
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/system_service/SystemServiceInstallerFactory.java
@@ -0,0 +1,28 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.system_service;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.sensor.Enricher;
+
+public class SystemServiceInstallerFactory {
+    public static SystemServiceInstaller of(Entity entity, Enricher systemServiceEnricher) {
+        return new InitdServiceInstaller(entity, systemServiceEnricher);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxAttributePollConfig.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxAttributePollConfig.java b/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxAttributePollConfig.java
new file mode 100644
index 0000000..02bbbeb
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxAttributePollConfig.java
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.feed.jmx;
+
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.sensor.feed.PollConfig;
+
+import com.google.common.base.Function;
+import com.google.common.base.Functions;
+
+public class JmxAttributePollConfig<T> extends PollConfig<Object, T, JmxAttributePollConfig<T>>{
+
+    private ObjectName objectName;
+    private String attributeName;
+
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public JmxAttributePollConfig(AttributeSensor<T> sensor) {
+        super(sensor);
+        onSuccess((Function)Functions.identity());
+    }
+
+    public JmxAttributePollConfig(JmxAttributePollConfig<T> other) {
+        super(other);
+        this.objectName = other.objectName;
+        this.attributeName = other.attributeName;
+    }
+
+    public ObjectName getObjectName() {
+        return objectName;
+    }
+    
+    public String getAttributeName() {
+        return attributeName;
+    }
+    
+    public JmxAttributePollConfig<T> objectName(ObjectName val) {
+        this.objectName = val; return this;
+    }
+    
+    public JmxAttributePollConfig<T> objectName(String val) {
+        try {
+            return objectName(new ObjectName(val));
+        } catch (MalformedObjectNameException e) {
+            throw new IllegalArgumentException("Invalid object name ("+val+")", e);
+        }
+    }
+    
+    public JmxAttributePollConfig<T> attributeName(String val) {
+        this.attributeName = val; return this;
+    }
+    
+    @Override protected String toStringBaseName() { return "jmx"; }
+    @Override protected String toStringPollSource() { return objectName+":"+attributeName; }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeed.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeed.java b/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeed.java
new file mode 100644
index 0000000..3c1897e
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeed.java
@@ -0,0 +1,436 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.feed.jmx;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.TimeUnit;
+
+import javax.management.Notification;
+import javax.management.NotificationFilter;
+import javax.management.NotificationListener;
+import javax.management.ObjectName;
+
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
+import org.apache.brooklyn.sensor.feed.AbstractFeed;
+import org.apache.brooklyn.sensor.feed.AttributePollHandler;
+import org.apache.brooklyn.sensor.feed.DelegatingPollHandler;
+import org.apache.brooklyn.sensor.feed.PollHandler;
+import org.apache.brooklyn.sensor.feed.Poller;
+import org.apache.brooklyn.util.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.collect.SetMultimap;
+import com.google.common.collect.Sets;
+import com.google.common.reflect.TypeToken;
+
+
+/**
+ * Provides a feed of attribute values, by polling or subscribing over jmx.
+ * 
+ * Example usage (e.g. in an entity that extends {@link SoftwareProcessImpl}):
+ * <pre>
+ * {@code
+ * private JmxFeed feed;
+ * 
+ * //@Override
+ * protected void connectSensors() {
+ *   super.connectSensors();
+ *   
+ *   feed = JmxFeed.builder()
+ *       .entity(this)
+ *       .period(500, TimeUnit.MILLISECONDS)
+ *       .pollAttribute(new JmxAttributePollConfig<Integer>(ERROR_COUNT)
+ *           .objectName(requestProcessorMbeanName)
+ *           .attributeName("errorCount"))
+ *       .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP)
+ *           .objectName(serverMbeanName)
+ *           .attributeName("Started")
+ *           .onError(Functions.constant(false)))
+ *       .build();
+ * }
+ * 
+ * {@literal @}Override
+ * protected void disconnectSensors() {
+ *   super.disconnectSensors();
+ *   if (feed != null) feed.stop();
+ * }
+ * }
+ * </pre>
+ * 
+ * @author aled
+ */
+public class JmxFeed extends AbstractFeed {
+
+    public static final Logger log = LoggerFactory.getLogger(JmxFeed.class);
+
+    public static final long JMX_CONNECTION_TIMEOUT_MS = 120*1000;
+
+    public static final ConfigKey<JmxHelper> HELPER = ConfigKeys.newConfigKey(JmxHelper.class, "helper");
+    public static final ConfigKey<Boolean> OWN_HELPER = ConfigKeys.newBooleanConfigKey("ownHelper");
+    public static final ConfigKey<String> JMX_URI = ConfigKeys.newStringConfigKey("jmxUri");
+    public static final ConfigKey<Long> JMX_CONNECTION_TIMEOUT = ConfigKeys.newLongConfigKey("jmxConnectionTimeout");
+    
+    @SuppressWarnings("serial")
+    public static final ConfigKey<SetMultimap<String, JmxAttributePollConfig<?>>> ATTRIBUTE_POLLS = ConfigKeys.newConfigKey(
+            new TypeToken<SetMultimap<String, JmxAttributePollConfig<?>>>() {},
+            "attributePolls");
+
+    @SuppressWarnings("serial")
+    public static final ConfigKey<SetMultimap<List<?>, JmxOperationPollConfig<?>>> OPERATION_POLLS = ConfigKeys.newConfigKey(
+            new TypeToken<SetMultimap<List<?>, JmxOperationPollConfig<?>>>() {},
+            "operationPolls");
+
+    @SuppressWarnings("serial")
+    public static final ConfigKey<SetMultimap<NotificationFilter, JmxNotificationSubscriptionConfig<?>>> NOTIFICATION_SUBSCRIPTIONS = ConfigKeys.newConfigKey(
+            new TypeToken<SetMultimap<NotificationFilter, JmxNotificationSubscriptionConfig<?>>>() {},
+            "notificationPolls");
+
+    public static Builder builder() {
+        return new Builder();
+    }
+    
+    public static class Builder {
+        private EntityLocal entity;
+        private JmxHelper helper;
+        private long jmxConnectionTimeout = JMX_CONNECTION_TIMEOUT_MS;
+        private long period = 500;
+        private TimeUnit periodUnits = TimeUnit.MILLISECONDS;
+        private List<JmxAttributePollConfig<?>> attributePolls = Lists.newArrayList();
+        private List<JmxOperationPollConfig<?>> operationPolls = Lists.newArrayList();
+        private List<JmxNotificationSubscriptionConfig<?>> notificationSubscriptions = Lists.newArrayList();
+        private String uniqueTag;
+        private volatile boolean built;
+        
+        public Builder entity(EntityLocal val) {
+            this.entity = val;
+            return this;
+        }
+        public Builder helper(JmxHelper val) {
+            this.helper = val;
+            return this;
+        }
+        public Builder period(Duration duration) {
+            return period(duration.toMilliseconds(), TimeUnit.MILLISECONDS);
+        }
+        public Builder period(long millis) {
+            return period(millis, TimeUnit.MILLISECONDS);
+        }
+        public Builder period(long val, TimeUnit units) {
+            this.period = val;
+            this.periodUnits = units;
+            return this;
+        }
+        public Builder pollAttribute(JmxAttributePollConfig<?> config) {
+            attributePolls.add(config);
+            return this;
+        }
+        public Builder pollOperation(JmxOperationPollConfig<?> config) {
+            operationPolls.add(config);
+            return this;
+        }
+        public Builder subscribeToNotification(JmxNotificationSubscriptionConfig<?> config) {
+            notificationSubscriptions.add(config);
+            return this;
+        }
+        public Builder uniqueTag(String uniqueTag) {
+            this.uniqueTag = uniqueTag;
+            return this;
+        }
+        public JmxFeed build() {
+            built = true;
+            JmxFeed result = new JmxFeed(this);
+            result.setEntity(checkNotNull(entity, "entity"));
+            result.start();
+            return result;
+        }
+        @Override
+        protected void finalize() {
+            if (!built) log.warn("JmxFeed.Builder created, but build() never called");
+        }
+    }
+
+    private final SetMultimap<ObjectName, NotificationListener> notificationListeners = HashMultimap.create();
+
+    /**
+     * For rebind; do not call directly; use builder
+     */
+    public JmxFeed() {
+    }
+
+    protected JmxFeed(Builder builder) {
+        super();
+        if (builder.helper != null) {
+            JmxHelper helper = builder.helper;
+            setConfig(HELPER, helper);
+            setConfig(OWN_HELPER, false);
+            setConfig(JMX_URI, helper.getUrl());
+        }
+        setConfig(JMX_CONNECTION_TIMEOUT, builder.jmxConnectionTimeout);
+        
+        SetMultimap<String, JmxAttributePollConfig<?>> attributePolls = HashMultimap.<String,JmxAttributePollConfig<?>>create();
+        for (JmxAttributePollConfig<?> config : builder.attributePolls) {
+            if (!config.isEnabled()) continue;
+            @SuppressWarnings({ "rawtypes", "unchecked" })
+            JmxAttributePollConfig<?> configCopy = new JmxAttributePollConfig(config);
+            if (configCopy.getPeriod() < 0) configCopy.period(builder.period, builder.periodUnits);
+            attributePolls.put(configCopy.getObjectName().getCanonicalName() + configCopy.getAttributeName(), configCopy);
+        }
+        setConfig(ATTRIBUTE_POLLS, attributePolls);
+        
+        SetMultimap<List<?>, JmxOperationPollConfig<?>> operationPolls = HashMultimap.<List<?>,JmxOperationPollConfig<?>>create();
+        for (JmxOperationPollConfig<?> config : builder.operationPolls) {
+            if (!config.isEnabled()) continue;
+            @SuppressWarnings({ "rawtypes", "unchecked" })
+            JmxOperationPollConfig<?> configCopy = new JmxOperationPollConfig(config);
+            if (configCopy.getPeriod() < 0) configCopy.period(builder.period, builder.periodUnits);
+            operationPolls.put(configCopy.buildOperationIdentity(), configCopy);
+        }
+        setConfig(OPERATION_POLLS, operationPolls);
+        
+        SetMultimap<NotificationFilter, JmxNotificationSubscriptionConfig<?>> notificationSubscriptions = HashMultimap.create();
+        for (JmxNotificationSubscriptionConfig<?> config : builder.notificationSubscriptions) {
+            if (!config.isEnabled()) continue;
+            notificationSubscriptions.put(config.getNotificationFilter(), config);
+        }
+        setConfig(NOTIFICATION_SUBSCRIPTIONS, notificationSubscriptions);
+        initUniqueTag(builder.uniqueTag, attributePolls, operationPolls, notificationSubscriptions);
+    }
+
+    @Override
+    public void setEntity(EntityLocal entity) {
+        if (getConfig(HELPER) == null) {
+            JmxHelper helper = new JmxHelper(entity);
+            setConfig(HELPER, helper);
+            setConfig(OWN_HELPER, true);
+            setConfig(JMX_URI, helper.getUrl());
+        }
+        super.setEntity(entity);
+    }
+    
+    public String getJmxUri() {
+        return getConfig(JMX_URI);
+    }
+    
+    protected JmxHelper getHelper() {
+        return getConfig(HELPER);
+    }
+    
+    @SuppressWarnings("unchecked")
+    protected Poller<Object> getPoller() {
+        return (Poller<Object>) super.getPoller();
+    }
+    
+    @Override
+    protected boolean isConnected() {
+        return super.isConnected() && getHelper().isConnected();
+    }
+    
+    @Override
+    protected void preStart() {
+        /*
+         * All actions on the JmxHelper are done async (through the poller's threading) so we don't 
+         * block on start for a long time (e.g. if the entity is not contactable and doing a rebind 
+         * on restart of brooklyn). Without that, one gets a 120 second pause with it stuck in a 
+         * stack trace like:
+         * 
+         *      at brooklyn.event.feed.jmx.JmxHelper.sleep(JmxHelper.java:640)
+         *      at brooklyn.event.feed.jmx.JmxHelper.connect(JmxHelper.java:320)
+         *      at brooklyn.event.feed.jmx.JmxFeed.preStart(JmxFeed.java:172)
+         *      at brooklyn.event.feed.AbstractFeed.start(AbstractFeed.java:68)
+         *      at brooklyn.event.feed.jmx.JmxFeed$Builder.build(JmxFeed.java:119)
+         *      at brooklyn.entity.java.JavaAppUtils.connectMXBeanSensors(JavaAppUtils.java:109)
+         *      at brooklyn.entity.java.VanillaJavaApp.connectSensors(VanillaJavaApp.java:97)
+         *      at brooklyn.entity.basic.SoftwareProcessImpl.callRebindHooks(SoftwareProcessImpl.java:189)
+         *      at brooklyn.entity.basic.SoftwareProcessImpl.rebind(SoftwareProcessImpl.java:235)
+         *      ...
+         *      at brooklyn.entity.rebind.RebindManagerImpl.rebind(RebindManagerImpl.java:184)
+         */
+        final SetMultimap<NotificationFilter, JmxNotificationSubscriptionConfig<?>> notificationSubscriptions = getConfig(NOTIFICATION_SUBSCRIPTIONS);
+        final SetMultimap<List<?>, JmxOperationPollConfig<?>> operationPolls = getConfig(OPERATION_POLLS);
+        final SetMultimap<String, JmxAttributePollConfig<?>> attributePolls = getConfig(ATTRIBUTE_POLLS);
+        
+        getPoller().submit(new Callable<Void>() {
+               public Void call() {
+                   getHelper().connect(getConfig(JMX_CONNECTION_TIMEOUT));
+                   return null;
+               }
+               @Override public String toString() { return "Connect JMX "+getHelper().getUrl(); }
+           });
+        
+        for (final NotificationFilter filter : notificationSubscriptions.keySet()) {
+            getPoller().submit(new Callable<Void>() {
+                public Void call() {
+                    // TODO Could config.getObjectName have wildcards? Is this code safe?
+                    Set<JmxNotificationSubscriptionConfig<?>> configs = notificationSubscriptions.get(filter);
+                    NotificationListener listener = registerNotificationListener(configs);
+                    ObjectName objectName = Iterables.get(configs, 0).getObjectName();
+                    notificationListeners.put(objectName, listener);
+                    return null;
+                }
+                @Override public String toString() { return "Register JMX notifications: "+notificationSubscriptions.get(filter); }
+            });
+        }
+        
+        // Setup polling of sensors
+        for (final String jmxAttributeName : attributePolls.keys()) {
+            registerAttributePoller(attributePolls.get(jmxAttributeName));
+        }
+        
+        // Setup polling of operations
+        for (final List<?> operationIdentifier : operationPolls.keys()) {
+            registerOperationPoller(operationPolls.get(operationIdentifier));
+        }
+    }
+    
+    @Override
+    protected void preStop() {
+        super.preStop();
+
+        for (Map.Entry<ObjectName, NotificationListener> entry : notificationListeners.entries()) {
+            unregisterNotificationListener(entry.getKey(), entry.getValue());
+        }
+        notificationListeners.clear();
+    }
+    
+    @Override
+    protected void postStop() {
+        super.postStop();
+        JmxHelper helper = getHelper();
+        Boolean ownHelper = getConfig(OWN_HELPER);
+        if (helper != null && ownHelper) helper.terminate();
+    }
+    
+    /**
+     * Registers to poll a jmx-operation for an ObjectName, where all the given configs are for the same ObjectName + operation + parameters.
+     */
+    private void registerOperationPoller(Set<JmxOperationPollConfig<?>> configs) {
+        Set<AttributePollHandler<? super Object>> handlers = Sets.newLinkedHashSet();
+        long minPeriod = Integer.MAX_VALUE;
+        
+        final ObjectName objectName = Iterables.get(configs, 0).getObjectName();
+        final String operationName = Iterables.get(configs, 0).getOperationName();
+        final List<String> signature = Iterables.get(configs, 0).getSignature();
+        final List<?> params = Iterables.get(configs, 0).getParams();
+        
+        for (JmxOperationPollConfig<?> config : configs) {
+            handlers.add(new AttributePollHandler<Object>(config, getEntity(), this));
+            if (config.getPeriod() > 0) minPeriod = Math.min(minPeriod, config.getPeriod());
+        }
+        
+        getPoller().scheduleAtFixedRate(
+                new Callable<Object>() {
+                    public Object call() throws Exception {
+                        if (log.isDebugEnabled()) log.debug("jmx operation polling for {} sensors at {} -> {}", new Object[] {getEntity(), getJmxUri(), operationName});
+                        if (signature.size() == params.size()) {
+                            return getHelper().operation(objectName, operationName, signature, params);
+                        } else {
+                            return getHelper().operation(objectName, operationName, params.toArray());
+                        }
+                    }
+                }, 
+                new DelegatingPollHandler<Object>(handlers), minPeriod);
+    }
+
+    /**
+     * Registers to poll a jmx-attribute for an ObjectName, where all the given configs are for that same ObjectName + attribute.
+     */
+    private void registerAttributePoller(Set<JmxAttributePollConfig<?>> configs) {
+        Set<AttributePollHandler<? super Object>> handlers = Sets.newLinkedHashSet();
+        long minPeriod = Integer.MAX_VALUE;
+        
+        final ObjectName objectName = Iterables.get(configs, 0).getObjectName();
+        final String jmxAttributeName = Iterables.get(configs, 0).getAttributeName();
+        
+        for (JmxAttributePollConfig<?> config : configs) {
+            handlers.add(new AttributePollHandler<Object>(config, getEntity(), this));
+            if (config.getPeriod() > 0) minPeriod = Math.min(minPeriod, config.getPeriod());
+        }
+        
+        // TODO Not good calling this holding the synchronization lock
+        getPoller().scheduleAtFixedRate(
+                new Callable<Object>() {
+                    public Object call() throws Exception {
+                        if (log.isTraceEnabled()) log.trace("jmx attribute polling for {} sensors at {} -> {}", new Object[] {getEntity(), getJmxUri(), jmxAttributeName});
+                        return getHelper().getAttribute(objectName, jmxAttributeName);
+                    }
+                }, 
+                new DelegatingPollHandler<Object>(handlers), minPeriod);
+    }
+
+    /**
+     * Registers to subscribe to notifications for an ObjectName, where all the given configs are for that same ObjectName + filter.
+     */
+    private NotificationListener registerNotificationListener(Set<JmxNotificationSubscriptionConfig<?>> configs) {
+        final List<AttributePollHandler<? super javax.management.Notification>> handlers = Lists.newArrayList();
+
+        final ObjectName objectName = Iterables.get(configs, 0).getObjectName();
+        final NotificationFilter filter = Iterables.get(configs, 0).getNotificationFilter();
+
+        for (final JmxNotificationSubscriptionConfig<?> config : configs) {
+            AttributePollHandler<javax.management.Notification> handler = new AttributePollHandler<javax.management.Notification>(config, getEntity(), this) {
+                @Override protected Object transformValueOnSuccess(javax.management.Notification val) {
+                    if (config.getOnNotification() != null) {
+                        return config.getOnNotification().apply(val);
+                    } else {
+                        Object result = super.transformValueOnSuccess(val);
+                        if (result instanceof javax.management.Notification)
+                            return ((javax.management.Notification)result).getUserData();
+                        return result;
+                    }
+                }
+            };
+            handlers.add(handler);
+        }
+        final PollHandler<javax.management.Notification> compoundHandler = new DelegatingPollHandler<javax.management.Notification>(handlers);
+        
+        NotificationListener listener = new NotificationListener() {
+            @Override public void handleNotification(Notification notification, Object handback) {
+                compoundHandler.onSuccess(notification);
+            }
+        };
+        getHelper().addNotificationListener(objectName, listener, filter);
+        
+        return listener;
+    }
+    
+    private void unregisterNotificationListener(ObjectName objectName, NotificationListener listener) {
+        try {
+            getHelper().removeNotificationListener(objectName, listener);
+        } catch (RuntimeException e) {
+            log.warn("Failed to unregister listener: "+objectName+", "+listener+"; continuing...", e);
+        }
+    }
+    
+    @Override
+    public String toString() {
+        return "JmxFeed["+(getManagementContext()!=null&&getManagementContext().isRunning()?getJmxUri():"mgmt-not-running")+"]";
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxHelper.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxHelper.java b/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxHelper.java
new file mode 100644
index 0000000..9599be1
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxHelper.java
@@ -0,0 +1,724 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.feed.jmx;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.apache.brooklyn.util.JavaGroovyEquivalents.groovyTruth;
+import groovy.time.TimeDuration;
+
+import java.io.IOException;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.cert.Certificate;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.WeakHashMap;
+import java.util.concurrent.Callable;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.management.AttributeNotFoundException;
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.InstanceNotFoundException;
+import javax.management.InvalidAttributeValueException;
+import javax.management.JMX;
+import javax.management.ListenerNotFoundException;
+import javax.management.MBeanServerConnection;
+import javax.management.MalformedObjectNameException;
+import javax.management.NotCompliantMBeanException;
+import javax.management.NotificationFilter;
+import javax.management.NotificationListener;
+import javax.management.ObjectInstance;
+import javax.management.ObjectName;
+import javax.management.openmbean.CompositeData;
+import javax.management.openmbean.TabularData;
+import javax.management.remote.JMXConnector;
+import javax.management.remote.JMXConnectorFactory;
+import javax.management.remote.JMXServiceURL;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.entity.java.JmxSupport;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.util.core.crypto.SecureKeys;
+import org.apache.brooklyn.util.crypto.SslTrustUtils;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.exceptions.RuntimeInterruptedException;
+import org.apache.brooklyn.util.jmx.jmxmp.JmxmpAgent;
+import org.apache.brooklyn.util.repeat.Repeater;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+
+public class JmxHelper {
+
+    private static final Logger LOG = LoggerFactory.getLogger(JmxHelper.class);
+
+    public static final String JMX_URL_FORMAT = "service:jmx:rmi:///jndi/rmi://%s:%d/%s";
+    // first host:port may be ignored, so above is sufficient, but not sure
+    public static final String RMI_JMX_URL_FORMAT = "service:jmx:rmi://%s:%d/jndi/rmi://%s:%d/%s";
+    // jmxmp
+    public static final String JMXMP_URL_FORMAT = "service:jmx:jmxmp://%s:%d";
+    
+    // Tracks the MBeans we have failed to find, with a set keyed off the url
+    private static final Map<String, Set<ObjectName>> notFoundMBeansByUrl = Collections.synchronizedMap(new WeakHashMap<String, Set<ObjectName>>());
+
+    public static final Map<String, String> CLASSES = ImmutableMap.<String,String>builder()
+            .put("Integer", Integer.TYPE.getName())
+            .put("Long", Long.TYPE.getName())
+            .put("Boolean", Boolean.TYPE.getName())
+            .put("Byte", Byte.TYPE.getName())
+            .put("Character", Character.TYPE.getName())
+            .put("Double", Double.TYPE.getName())
+            .put("Float", Float.TYPE.getName())
+            .put("GStringImpl", String.class.getName())
+            .put("LinkedHashMap", Map.class.getName())
+            .put("TreeMap", Map.class.getName())
+            .put("HashMap", Map.class.getName())
+            .put("ConcurrentHashMap", Map.class.getName())
+            .put("TabularDataSupport", TabularData.class.getName())
+            .put("CompositeDataSupport", CompositeData.class.getName())
+            .build();
+
+    /** constructs a JMX URL suitable for connecting to the given entity, being smart about JMX/RMI vs JMXMP */
+    public static String toJmxUrl(EntityLocal entity) {
+        String url = entity.getAttribute(UsesJmx.JMX_URL);
+        if (url != null) {
+            return url;
+        } else {
+            new JmxSupport(entity, null).setJmxUrl();
+            url = entity.getAttribute(UsesJmx.JMX_URL);
+            return Preconditions.checkNotNull(url, "Could not find URL for "+entity);
+        }
+    }
+
+    /** constructs an RMI/JMX URL with the given inputs 
+     * (where the RMI Registry Port should be non-null, and at least one must be non-null) */
+    public static String toRmiJmxUrl(String host, Integer jmxRmiServerPort, Integer rmiRegistryPort, String context) {
+        if (rmiRegistryPort != null && rmiRegistryPort > 0) {
+            if (jmxRmiServerPort!=null && jmxRmiServerPort > 0 && jmxRmiServerPort!=rmiRegistryPort) {
+                // we have an explicit known JMX RMI server port (e.g. because we are using the agent),
+                // distinct from the RMI registry port
+                // (if the ports are the same, it is a short-hand, and don't use this syntax!)
+                return String.format(RMI_JMX_URL_FORMAT, host, jmxRmiServerPort, host, rmiRegistryPort, context);
+            }
+            return String.format(JMX_URL_FORMAT, host, rmiRegistryPort, context);
+        } else if (jmxRmiServerPort!=null && jmxRmiServerPort > 0) {
+            LOG.warn("No RMI registry port set for "+host+"; attempting to use JMX port for RMI lookup");
+            return String.format(JMX_URL_FORMAT, host, jmxRmiServerPort, context);
+        } else {
+            LOG.warn("No RMI/JMX details set for "+host+"; returning null");
+            return null;
+        }
+    }
+
+    /** constructs a JMXMP URL for connecting to the given host and port */
+    public static String toJmxmpUrl(String host, Integer jmxmpPort) {
+        return "service:jmx:jmxmp://"+host+(jmxmpPort!=null ? ":"+jmxmpPort : "");
+    }
+    
+    final EntityLocal entity;
+    final String url;
+    final String user;
+    final String password;
+
+    private volatile transient JMXConnector connector;
+    private volatile transient MBeanServerConnection connection;
+    private transient boolean triedConnecting;
+    private transient boolean failedReconnecting;
+    private transient long failedReconnectingTime;
+    private int minTimeBetweenReconnectAttempts = 1000;
+    private final AtomicBoolean terminated = new AtomicBoolean();
+    
+    // Tracks the MBeans we have failed to find for this JmsHelper's connection URL (so can log just once for each)
+    private final Set<ObjectName> notFoundMBeans;
+
+    public JmxHelper(EntityLocal entity) {
+        this(toJmxUrl(entity), entity, entity.getAttribute(UsesJmx.JMX_USER), entity.getAttribute(UsesJmx.JMX_PASSWORD));
+        
+        if (entity.getAttribute(UsesJmx.JMX_URL) == null) {
+            entity.setAttribute(UsesJmx.JMX_URL, url);
+        }
+    }
+    
+    // TODO split this in to two classes, one for entities, and one entity-neutral
+    // (simplifying set of constructors below)
+    
+    public JmxHelper(String url) {
+        this(url, null, null);
+    }
+
+    public JmxHelper(String url, String user, String password) {
+        this(url, null, user, password);
+    }
+    
+    public JmxHelper(String url, EntityLocal entity, String user, String password) {
+        this.url = url;
+        this.entity = entity;
+        this.user = user;
+        this.password = password;
+
+        synchronized (notFoundMBeansByUrl) {
+            Set<ObjectName> set = notFoundMBeansByUrl.get(url);
+            if (set == null) {
+                set = Collections.synchronizedSet(Collections.newSetFromMap(new WeakHashMap<ObjectName, Boolean>()));
+                notFoundMBeansByUrl.put(url, set);
+            }
+            notFoundMBeans = set;
+        }
+    }
+
+    public void setMinTimeBetweenReconnectAttempts(int val) {
+        minTimeBetweenReconnectAttempts = val;
+    }
+    
+    public String getUrl(){
+        return url;
+    }
+
+    // ============== connection related calls =======================
+
+    //for tesing purposes
+    protected MBeanServerConnection getConnection() {
+        return connection;
+    }
+
+    /**
+     * Checks if the JmxHelper is connected. Returned value could be stale as soon
+     * as it is received.
+     *
+     * This method is thread safe.
+     *
+     * @return true if connected, false otherwise.
+     */
+    public boolean isConnected() {
+        return connection!=null;
+    }
+
+    /**
+     * Reconnects. If it already is connected, it disconnects first.
+     *
+     * @throws IOException
+     */
+    public synchronized void reconnectWithRetryDampened() throws IOException {
+        // If we've already tried reconnecting very recently, don't try again immediately
+        if (failedReconnecting) {
+            long timeSince = (System.currentTimeMillis() - failedReconnectingTime);
+            if (timeSince < minTimeBetweenReconnectAttempts) {
+                String msg = "Not reconnecting to JMX at "+url+" because attempt failed "+Time.makeTimeStringRounded(timeSince)+" ago";
+                throw new IllegalStateException(msg);
+            }
+        }
+        
+        reconnect();
+    }
+    
+    public synchronized void reconnect() throws IOException {
+        disconnect();
+
+        try {
+            connect();
+            failedReconnecting = false;
+        } catch (Exception e) {
+            if (failedReconnecting) {
+                if (LOG.isDebugEnabled()) LOG.debug("unable to re-connect to JMX url (repeated failure): {}: {}", url, e);
+            } else {
+                LOG.debug("unable to re-connect to JMX url {} (rethrowing): {}", url, e);
+                failedReconnecting = true;
+            }
+            failedReconnectingTime = System.currentTimeMillis();
+            throw Throwables.propagate(e);
+        }
+    }
+
+    /** attempts to connect immediately */
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    public synchronized void connect() throws IOException {
+        if (terminated.get()) throw new IllegalStateException("JMX Helper "+this+" already terminated");
+        if (connection != null) return;
+
+        triedConnecting = true;
+        if (connector != null) connector.close();
+        JMXServiceURL serviceUrl = new JMXServiceURL(url);
+        Map env = getConnectionEnvVars();
+        try {
+            connector = JMXConnectorFactory.connect(serviceUrl, env);
+        } catch (NullPointerException npe) {
+            //some software -- eg WSO2 -- will throw an NPE exception if the JMX connection can't be created, instead of an IOException.
+            //this is a break of contract with the JMXConnectorFactory.connect method, so this code verifies if the NPE is
+            //thrown by a known offender (wso2) and if so replaces the bad exception by a new IOException.
+            //ideally WSO2 will fix this bug and we can remove this code.
+            boolean thrownByWso2 = npe.getStackTrace()[0].toString().contains("org.wso2.carbon.core.security.CarbonJMXAuthenticator.authenticate");
+            if (thrownByWso2) {
+                throw new IOException("Failed to connect to url "+url+". NullPointerException is thrown, but replaced by an IOException to fix a WSO2 JMX problem", npe);
+            } else {
+                throw npe;
+            }
+        } catch (IOException e) {
+            Exceptions.propagateIfFatal(e);
+            if (terminated.get()) {
+                throw new IllegalStateException("JMX Helper "+this+" already terminated", e);
+            } else {
+                throw e;
+            }
+        }
+        connection = connector.getMBeanServerConnection();
+        
+        if (terminated.get()) {
+            disconnectNow();
+            throw new IllegalStateException("JMX Helper "+this+" already terminated");
+        }
+    }
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    public Map getConnectionEnvVars() {
+        Map env = new LinkedHashMap();
+        
+        if (groovyTruth(user) && groovyTruth(password)) {
+            String[] creds = new String[] {user, password};
+            env.put(JMXConnector.CREDENTIALS, creds);
+        }
+        
+        if (entity!=null && groovyTruth(entity.getConfig(UsesJmx.JMX_SSL_ENABLED))) {
+            env.put("jmx.remote.profiles", JmxmpAgent.TLS_JMX_REMOTE_PROFILES);
+
+            PrivateKey key = entity.getConfig(UsesJmx.JMX_SSL_ACCESS_KEY);
+            Certificate cert = entity.getConfig(UsesJmx.JMX_SSL_ACCESS_CERT);
+            KeyStore ks = SecureKeys.newKeyStore();
+            try {
+                KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+                if (key!=null) {
+                    ks.setKeyEntry("brooklyn-jmx-access", key, "".toCharArray(), new Certificate[] { cert });
+                }
+                kmf.init(ks, "".toCharArray());
+
+                TrustManager tms = 
+                        // TODO use root cert for trusting server
+                        //trustStore!=null ? SecureKeys.getTrustManager(trustStore) : 
+                        SslTrustUtils.TRUST_ALL;
+
+                SSLContext ctx = SSLContext.getInstance("TLSv1");
+                ctx.init(kmf.getKeyManagers(), new TrustManager[] { tms }, null);
+                SSLSocketFactory ssf = ctx.getSocketFactory(); 
+                env.put(JmxmpAgent.TLS_SOCKET_FACTORY_PROPERTY, ssf); 
+                
+            } catch (Exception e) {
+                LOG.warn("Error setting key "+key+" for "+entity+": "+e, e);
+            }
+        }
+        
+        return env;
+    }
+
+    /**
+     * Continuously attempts to connect for at least the indicated amount of time; or indefinitely if -1. This method
+     * is useful when you are not sure if the system you are trying to connect to already is up and running.
+     *
+     * This method doesn't throw an Exception, but returns true on success, false otherwise.
+     *
+     * TODO: What happens if already connected?
+     *
+     * @param timeoutMs
+     * @return
+     */
+    public boolean connect(long timeoutMs) {
+        if (LOG.isDebugEnabled()) LOG.debug("Connecting to JMX URL: {} ({})", url, ((timeoutMs == -1) ? "indefinitely" : timeoutMs+"ms timeout"));
+        long startMs = System.currentTimeMillis();
+        long endMs = (timeoutMs == -1) ? Long.MAX_VALUE : (startMs + timeoutMs);
+        long currentTime = startMs;
+        Throwable lastError = null;
+        int attempt = 0;
+        while (currentTime <= endMs) {
+            currentTime = System.currentTimeMillis();
+            if (attempt != 0) sleep(100); //sleep 100 to prevent thrashing and facilitate interruption
+            if (LOG.isTraceEnabled()) LOG.trace("trying connection to {} at time {}", url, currentTime);
+
+            try {
+                connect();
+                return true;
+            } catch (Exception e) {
+                Exceptions.propagateIfFatal(e);
+                if (!terminated.get() && shouldRetryOn(e)) {
+                    if (LOG.isDebugEnabled()) LOG.debug("Attempt {} failed connecting to {} ({})", new Object[] {attempt + 1, url, e.getMessage()});
+                    lastError = e;
+                } else {
+                    throw Exceptions.propagate(e);
+                }
+            }
+            attempt++;
+        }
+        LOG.warn("unable to connect to JMX url: "+url, lastError);
+        return false;
+    }
+
+    private boolean shouldRetryOn(Exception e) {
+        // Expect SecurityException, IOException, etc.
+        // But can also see things like javax.naming.ServiceUnavailableException with WSO2 app-servers.
+        // So let's not try to second guess strange behaviours that future entities will exhibit.
+        //
+        // However, if it was our request that was invalid then not worth retrying.
+        
+        if (e instanceof AttributeNotFoundException) return false;
+        if (e instanceof InstanceAlreadyExistsException) return false;
+        if (e instanceof InstanceNotFoundException) return false;
+        if (e instanceof InvalidAttributeValueException) return false;
+        if (e instanceof ListenerNotFoundException) return false;
+        if (e instanceof MalformedObjectNameException) return false;
+        if (e instanceof NotCompliantMBeanException) return false;
+        if (e instanceof InterruptedException) return false;
+        if (e instanceof RuntimeInterruptedException) return false;
+
+        return true;
+    }
+
+    /**
+     * A thread-safe version of {@link #disconnectNow()}.
+     *
+     * This method is threadsafe.
+     */
+    public synchronized void disconnect() {
+        disconnectNow();
+    }
+    
+    /**
+     * Disconnects, preventing subsequent connections to be made. Method doesn't throw an exception.
+     *
+     * Can safely be called if already disconnected.
+     *
+     * This method is not threadsafe, but will thus not block if 
+     * another thread is taking a long time for connections to timeout.
+     * 
+     * Any concurrent requests will likely get an IOException - see
+     * {@linkplain http://docs.oracle.com/javase/7/docs/api/javax/management/remote/JMXConnector.html#close()}.
+     * 
+     */
+    public void terminate() {
+        terminated.set(true);
+        disconnectNow();
+    }
+    
+    protected void disconnectNow() {
+        triedConnecting = false;
+        if (connector != null) {
+            if (LOG.isDebugEnabled()) LOG.debug("Disconnecting from JMX URL {}", url);
+            try {
+                connector.close();
+            } catch (Exception e) {
+                // close attempts to connect to close cleanly; and if it can't, it throws;
+                // often we disconnect as part of shutdown, even if the other side has already stopped --
+                // so swallow exceptions (no situations known where we need a clean closure on the remote side)
+                if (LOG.isDebugEnabled()) LOG.debug("Caught exception disconnecting from JMX at {} ({})", url, e.getMessage());
+                if (LOG.isTraceEnabled()) LOG.trace("Details for exception disconnecting JMX", e);
+            } finally {
+                connector = null;
+                connection = null;
+            }
+        }
+    }
+
+    /**
+     * Gets a usable MBeanServerConnection.
+     *
+     * Method is threadsafe.
+     *
+     * @returns the MBeanServerConnection
+     * @throws IllegalStateException if not connected.
+     */
+    private synchronized MBeanServerConnection getConnectionOrFail() {
+        if (isConnected())
+            return getConnection();
+
+        if (triedConnecting) {
+            throw new IllegalStateException("Failed to connect to JMX at "+url);
+        } else {
+            String msg = "Not connected (and not attempted to connect) to JMX at "+url+
+                    (failedReconnecting ? (" (last reconnect failure at "+ Time.makeDateString(failedReconnectingTime) + ")") : "");
+            throw new IllegalStateException(msg);
+        }
+    }
+
+    private <T> T invokeWithReconnect(Callable<T> task) {
+        try {
+            return task.call();
+        } catch (Exception e) {
+            if (shouldRetryOn(e)) {
+                try {
+                    reconnectWithRetryDampened();
+                    return task.call();
+                } catch (Exception e2) {
+                    throw Throwables.propagate(e2);
+                }
+            } else {
+                throw Throwables.propagate(e);
+            }
+        }
+    }
+
+    // ====================== query related calls =======================================
+
+    /**
+     * Converts from an object name pattern to a real object name, by querying with findMBean; 
+     * if no matching MBean can be found (or if more than one match found) then returns null.
+     * If the supplied object name is not a pattern then just returns that. If the 
+     */
+    public ObjectName toLiteralObjectName(ObjectName objectName) {
+        if (checkNotNull(objectName, "objectName").isPattern()) {
+            ObjectInstance bean = findMBean(objectName);    
+            return (bean != null) ? bean.getObjectName() : null;
+        } else {
+            return objectName;
+        }
+    }
+    
+    public Set<ObjectInstance> findMBeans(final ObjectName objectName) {
+        return invokeWithReconnect(new Callable<Set<ObjectInstance>>() {
+                public Set<ObjectInstance> call() throws Exception {
+                    return getConnectionOrFail().queryMBeans(objectName, null);
+                }});
+    }
+
+    public ObjectInstance findMBean(ObjectName objectName) {
+        Set<ObjectInstance> beans = findMBeans(objectName);
+        if (beans.size() == 1) {
+            notFoundMBeans.remove(objectName);
+            return Iterables.getOnlyElement(beans);
+        } else {
+            boolean changed = notFoundMBeans.add(objectName);
+
+            if (beans.size() > 1) {
+                if (changed) {
+                    LOG.warn("JMX object name query returned {} values for {} at {}; ignoring all",
+                            new Object[] {beans.size(), objectName.getCanonicalName(), url});
+                } else {
+                    if (LOG.isDebugEnabled()) LOG.debug("JMX object name query returned {} values for {} at {} (repeating); ignoring all", 
+                            new Object[] {beans.size(), objectName.getCanonicalName(), url});
+                }
+            } else {
+                if (changed) {
+                    LOG.warn("JMX object {} not found at {}", objectName.getCanonicalName(), url);
+                } else {
+                    if (LOG.isDebugEnabled()) LOG.debug("JMX object {} not found at {} (repeating)", objectName.getCanonicalName(), url);
+                }
+            }
+            return null;
+        }
+    }
+
+    public Set<ObjectInstance> doesMBeanExistsEventually(final ObjectName objectName, Duration timeout) {
+        return doesMBeanExistsEventually(objectName, timeout.toMilliseconds(), TimeUnit.MILLISECONDS);
+    }
+    public Set<ObjectInstance> doesMBeanExistsEventually(final ObjectName objectName, TimeDuration timeout) {
+        return doesMBeanExistsEventually(objectName, timeout.toMilliseconds(), TimeUnit.MILLISECONDS);
+    }
+    
+    public Set<ObjectInstance> doesMBeanExistsEventually(final ObjectName objectName, long timeoutMillis) {
+        return doesMBeanExistsEventually(objectName, timeoutMillis, TimeUnit.MILLISECONDS);
+    }
+    
+    public Set<ObjectInstance> doesMBeanExistsEventually(String objectName, Duration timeout) {
+        return doesMBeanExistsEventually(createObjectName(objectName), timeout);
+    }
+    public Set<ObjectInstance> doesMBeanExistsEventually(String objectName, TimeDuration timeout) {
+        return doesMBeanExistsEventually(createObjectName(objectName), timeout);
+    }
+    
+    public Set<ObjectInstance> doesMBeanExistsEventually(String objectName, long timeout, TimeUnit timeUnit) {
+        return doesMBeanExistsEventually(createObjectName(objectName), timeout, timeUnit);
+    }
+
+    /** returns set of beans found, with retry, empty set if none after timeout */
+    public Set<ObjectInstance> doesMBeanExistsEventually(final ObjectName objectName, long timeout, TimeUnit timeUnit) {
+        final long timeoutMillis = timeUnit.toMillis(timeout);
+        final AtomicReference<Set<ObjectInstance>> beans = new AtomicReference<Set<ObjectInstance>>(ImmutableSet.<ObjectInstance>of());
+        try {
+            Repeater.create("Wait for "+objectName)
+                    .limitTimeTo(timeout, timeUnit)
+                    .every(500, TimeUnit.MILLISECONDS)
+                    .until(new Callable<Boolean>() {
+                            public Boolean call() {
+                                connect(timeoutMillis);
+                                beans.set(findMBeans(objectName));
+                                return !beans.get().isEmpty();
+                            }})
+                    .rethrowException()
+                    .run();
+            return beans.get();
+        } catch (Exception e) {
+            throw Exceptions.propagate(e);
+        }
+    }
+
+    public void assertMBeanExistsEventually(ObjectName objectName, Duration timeout) {
+        assertMBeanExistsEventually(objectName, timeout.toMilliseconds(), TimeUnit.MILLISECONDS);
+    }
+    public void assertMBeanExistsEventually(ObjectName objectName, TimeDuration timeout) {
+        assertMBeanExistsEventually(objectName, timeout.toMilliseconds(), TimeUnit.MILLISECONDS);
+    }
+    
+    public void assertMBeanExistsEventually(ObjectName objectName, long timeoutMillis) {
+        assertMBeanExistsEventually(objectName, timeoutMillis, TimeUnit.MILLISECONDS);
+    }
+    
+    public void assertMBeanExistsEventually(ObjectName objectName, long timeout, TimeUnit timeUnit) {
+        Set<ObjectInstance> beans = doesMBeanExistsEventually(objectName, timeout, timeUnit);
+        if (beans.size() != 1) {
+            throw new IllegalStateException("MBean "+objectName+" not found within "+timeout+
+                    (beans.size() > 1 ? "; found multiple matches: "+beans : ""));
+        }
+    }
+
+    /**
+     * Returns a specific attribute for a JMX {@link ObjectName}.
+     */
+    public Object getAttribute(ObjectName objectName, final String attribute) {
+        final ObjectName realObjectName = toLiteralObjectName(objectName);
+        
+        if (realObjectName != null) {
+            Object result = invokeWithReconnect(new Callable<Object>() {
+                    public Object call() throws Exception {
+                        return getConnectionOrFail().getAttribute(realObjectName, attribute);
+                    }});
+
+            if (LOG.isTraceEnabled()) LOG.trace("From {}, for jmx attribute {}.{}, got value {}", new Object[] {url, objectName.getCanonicalName(), attribute, result});
+            return result;
+        } else {
+            return null;
+        }
+    }
+
+    public void setAttribute(String objectName, String attribute, Object val) {
+        setAttribute(createObjectName(objectName), attribute, val);
+    }
+
+    public void setAttribute(ObjectName objectName, final String attribute, final Object val) {
+        final ObjectName realObjectName = toLiteralObjectName(objectName);
+        
+        if (realObjectName != null) {
+            invokeWithReconnect(new Callable<Void>() {
+                    public Void call() throws Exception {
+                        getConnectionOrFail().setAttribute(realObjectName, new javax.management.Attribute(attribute, val));
+                        return null;
+                    }});
+            if (LOG.isTraceEnabled()) LOG.trace("From {}, for jmx attribute {}.{}, set value {}", new Object[] {url, objectName.getCanonicalName(), attribute, val});
+        } else {
+            if (LOG.isDebugEnabled()) LOG.debug("From {}, cannot set attribute {}.{}, because mbean not found", new Object[] {url, objectName.getCanonicalName(), attribute});
+        }
+    }
+
+    /** @see #operation(ObjectName, String, Object ...) */
+    public Object operation(String objectName, String method, Object... arguments) {
+        return operation(createObjectName(objectName), method, arguments);
+    }
+
+    /**
+     * Executes an operation on a JMX {@link ObjectName}.
+     */
+    public Object operation(ObjectName objectName, final String method, final Object... arguments) {
+        final ObjectName realObjectName = toLiteralObjectName(objectName);
+        final String[] signature = new String[arguments.length];
+        for (int i = 0; i < arguments.length; i++) {
+            Class<?> clazz = arguments[i].getClass();
+            signature[i] = (CLASSES.containsKey(clazz.getSimpleName()) ? CLASSES.get(clazz.getSimpleName()) : clazz.getName());
+        }
+        
+        Object result = invokeWithReconnect(new Callable<Object>() {
+                public Object call() throws Exception {
+                    return getConnectionOrFail().invoke(realObjectName, method, arguments, signature);
+                }});
+
+        if (LOG.isTraceEnabled()) LOG.trace("From {}, for jmx operation {}.{}({}), got value {}", new Object[] {url, realObjectName.getCanonicalName(), method, Arrays.asList(arguments), 
+                result});
+        return result;
+    }
+
+    public void addNotificationListener(String objectName, NotificationListener listener) {
+        addNotificationListener(createObjectName(objectName), listener, null);
+    }
+    
+    public void addNotificationListener(String objectName, NotificationListener listener, NotificationFilter filter) {
+        addNotificationListener(createObjectName(objectName), listener, filter);
+    }
+
+    public void addNotificationListener(ObjectName objectName, NotificationListener listener) {
+        addNotificationListener(objectName, listener, null);
+    }
+    
+    public void addNotificationListener(final ObjectName objectName, final NotificationListener listener, final NotificationFilter filter) {
+        invokeWithReconnect(new Callable<Void>() {
+                public Void call() throws Exception {
+                    getConnectionOrFail().addNotificationListener(objectName, listener, filter, null);
+                    return null;
+                }});
+    }
+
+    public void removeNotificationListener(String objectName, NotificationListener listener) {
+        removeNotificationListener(createObjectName(objectName), listener);
+    }
+
+    public void removeNotificationListener(final ObjectName objectName, final NotificationListener listener) {
+        removeNotificationListener(objectName, listener, null);
+    }
+    
+    public void removeNotificationListener(final ObjectName objectName, final NotificationListener listener, final NotificationFilter filter) {
+        if (isConnected()) invokeWithReconnect(new Callable<Void>() {
+                public Void call() throws Exception {
+                    getConnectionOrFail().removeNotificationListener(objectName, listener, filter, null);
+                    return null;
+                }});
+    }
+
+    public <M> M getProxyObject(String objectName, Class<M> mbeanInterface) {
+        return getProxyObject(createObjectName(objectName), mbeanInterface);
+    }
+
+    public <M> M getProxyObject(ObjectName objectName, Class<M> mbeanInterface) {
+        MBeanServerConnection connection = getConnectionOrFail();
+        return JMX.newMBeanProxy(connection, objectName, mbeanInterface, false);
+    }
+
+    public static ObjectName createObjectName(String name) {
+        try {
+            return new ObjectName(name);
+        } catch (MalformedObjectNameException e) {
+            throw Throwables.propagate(e);
+        }
+    }
+    
+    private static void sleep(long sleepTimeMillis) {
+        try {
+            Thread.sleep(sleepTimeMillis);
+        } catch (InterruptedException e) {
+            throw new RuntimeInterruptedException(e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxNotificationFilters.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxNotificationFilters.java b/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxNotificationFilters.java
new file mode 100644
index 0000000..182866a
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxNotificationFilters.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.feed.jmx;
+
+import javax.management.Notification;
+import javax.management.NotificationFilter;
+import javax.management.NotificationFilterSupport;
+
+public class JmxNotificationFilters {
+
+    private JmxNotificationFilters() {} // instead use static utility methods
+    
+    /**
+     * Matches the given notification type.
+     * @see {@link NotificationFilterSupport#enableType(String)}
+     */
+    public static NotificationFilter matchesType(String type) {
+        return matchesTypes(type);
+    }
+
+    /**
+     * Matches any of the given notification types.
+     * @see {@link NotificationFilterSupport#enableType(String)}
+     */
+    public static NotificationFilter matchesTypes(String... types) {
+        NotificationFilterSupport result = new NotificationFilterSupport();
+        for (String type : types) {
+            result.enableType(type);
+        }
+        return result;
+    }
+
+    /**
+     * @deprecated since 0.6.0;
+     *             only works if this brooklyn class is on the classpath of the JVM that your 
+     *             subscribing to notifications on (because it tries to push the filter instance
+     *             to that JVM). So of very limited use in real-world java processes to be managed.
+     *             Therefore this will be deleted to avoid people hitting this surprising behaviour.
+     */
+    @SuppressWarnings("serial")
+    public static NotificationFilter matchesTypeRegex(final String typeRegex) {
+        return new NotificationFilter() {
+            @Override public boolean isNotificationEnabled(Notification notif) {
+                return notif.getType().matches(typeRegex);
+            }
+        };
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxNotificationSubscriptionConfig.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxNotificationSubscriptionConfig.java b/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxNotificationSubscriptionConfig.java
new file mode 100644
index 0000000..2a99c62
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxNotificationSubscriptionConfig.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.feed.jmx;
+
+import javax.management.MalformedObjectNameException;
+import javax.management.Notification;
+import javax.management.NotificationFilter;
+import javax.management.ObjectName;
+
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.sensor.feed.FeedConfig;
+import org.apache.brooklyn.util.collections.MutableList;
+
+import com.google.common.base.Function;
+import com.google.common.base.Functions;
+
+public class JmxNotificationSubscriptionConfig<T> extends FeedConfig<javax.management.Notification, T, JmxNotificationSubscriptionConfig<T>>{
+
+    private ObjectName objectName;
+    private NotificationFilter notificationFilter;
+    private Function<Notification, T> onNotification;
+
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public JmxNotificationSubscriptionConfig(AttributeSensor<T> sensor) {
+        super(sensor);
+        onSuccess((Function)Functions.identity());
+    }
+
+    public JmxNotificationSubscriptionConfig(JmxNotificationSubscriptionConfig<T> other) {
+        super(other);
+        this.objectName = other.objectName;
+        this.notificationFilter = other.notificationFilter;
+        this.onNotification = other.onNotification;
+    }
+
+    public ObjectName getObjectName() {
+        return objectName;
+    }
+
+    public NotificationFilter getNotificationFilter() {
+        return notificationFilter;
+    }
+    
+    public Function<Notification, T> getOnNotification() {
+        return onNotification;
+    }
+    
+    public JmxNotificationSubscriptionConfig<T> objectName(ObjectName val) {
+        this.objectName = val; return this;
+    }
+    
+    public JmxNotificationSubscriptionConfig<T> objectName(String val) {
+        try {
+            return objectName(new ObjectName(val));
+        } catch (MalformedObjectNameException e) {
+            throw new IllegalArgumentException("Invalid object name ("+val+")", e);
+        }
+    }
+    
+    public JmxNotificationSubscriptionConfig<T> notificationFilter(NotificationFilter val) {
+        this.notificationFilter = val; return this;
+    }
+
+    public JmxNotificationSubscriptionConfig<T> onNotification(Function<Notification,T> val) {
+        this.onNotification = val; return this;
+    }
+
+    @Override
+    protected Object toStringPollSource() {
+        return objectName;
+    }
+
+    @Override
+    protected MutableList<Object> equalsFields() {
+        return super.equalsFields()
+            .appendIfNotNull(notificationFilter).appendIfNotNull(onNotification);
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxOperationPollConfig.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxOperationPollConfig.java b/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxOperationPollConfig.java
new file mode 100644
index 0000000..b72a4ee
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxOperationPollConfig.java
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.feed.jmx;
+
+import java.util.Collections;
+import java.util.List;
+
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.sensor.feed.PollConfig;
+
+import com.google.common.base.Function;
+import com.google.common.base.Functions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+public class JmxOperationPollConfig<T> extends PollConfig<Object, T, JmxOperationPollConfig<T>>{
+
+    private ObjectName objectName;
+    private String operationName;
+    private List<String> signature = Collections.emptyList();
+    private List<?> params = Collections.emptyList();
+
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public JmxOperationPollConfig(AttributeSensor<T> sensor) {
+        super(sensor);
+        onSuccess((Function)Functions.identity());
+    }
+
+    public JmxOperationPollConfig(JmxOperationPollConfig<T> other) {
+        super(other);
+        this.objectName = other.objectName;
+        this.operationName = other.operationName;
+        this.signature = other.signature != null ? ImmutableList.copyOf(other.signature) : null;
+        this.params = other.params != null ? ImmutableList.copyOf(other.params) : null;
+    }
+
+    public ObjectName getObjectName() {
+        return objectName;
+    }
+    
+    public String getOperationName() {
+        return operationName;
+    }
+    
+    public List<String> getSignature() {
+        return signature;
+    }
+    
+    public List<?> getParams() {
+        return params;
+    }
+    
+    public JmxOperationPollConfig<T> objectName(ObjectName val) {
+        this.objectName = val; return this;
+    }
+    
+    public JmxOperationPollConfig<T> objectName(String val) {
+        try {
+            return objectName(new ObjectName(val));
+        } catch (MalformedObjectNameException e) {
+            throw new IllegalArgumentException("Invalid object name ("+val+")", e);
+        }
+    }
+
+    public JmxOperationPollConfig<T> operationName(String val) {
+        this.operationName = val; return this;
+    }
+    
+    public JmxOperationPollConfig<T> operationSignature(List<String> val) {
+        this.signature = val; return this;
+    }
+    
+    public JmxOperationPollConfig<T> operationParams(List<?> val) {
+        this.params = val; return this;
+    }
+
+    public List<?> buildOperationIdentity() {
+        // FIXME Have a build() method for ensuring signature is set, and making class subsequently immutable?
+        return ImmutableList.of(operationName, buildSignature(), params);
+    }
+    
+    private List<String> buildSignature() {
+        if (signature != null && signature.size() == params.size()) {
+            return signature;
+        } else {
+            List<String> derivedSignature = Lists.newLinkedList();
+            for (Object param : params) {
+                Class<?> clazz = (param != null) ? param.getClass() : null;
+                String clazzName = (clazz != null) ? 
+                         (JmxHelper.CLASSES.containsKey(clazz.getSimpleName()) ? 
+                                 JmxHelper.CLASSES.get(clazz.getSimpleName()) : clazz.getName()) : 
+                         Object.class.getName();
+                derivedSignature.add(clazzName);
+            }
+            return derivedSignature;
+        }
+    }
+
+    @Override protected String toStringBaseName() { return "jmx"; }
+    @Override protected String toStringPollSource() { return objectName+":"+operationName+(params!=null ? params : "[]"); }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxValueFunctions.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxValueFunctions.java b/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxValueFunctions.java
new file mode 100644
index 0000000..d0b5e21
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/sensor/feed/jmx/JmxValueFunctions.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.feed.jmx;
+
+import java.util.List;
+import java.util.Map;
+
+import javax.management.openmbean.CompositeData;
+import javax.management.openmbean.TabularData;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Function;
+import com.google.common.collect.Maps;
+
+public class JmxValueFunctions {
+
+    private static final Logger log = LoggerFactory.getLogger(JmxValueFunctions.class);
+    
+    /**
+     * @return a closure that converts a TabularDataSupport to a map.
+     */
+    public static Function<TabularData, Map> tabularDataToMap() {
+        return new Function<TabularData, Map>() {
+            @Override public Map apply(TabularData input) {
+                return tabularDataToMap(input);
+            }};
+    }
+
+    public static Function<TabularData, Map> tabularDataToMapOfMaps() {
+        return new Function<TabularData, Map>() {
+            @Override public Map apply(TabularData input) {
+                return tabularDataToMapOfMaps(input);
+            }};
+    }
+
+    public static Function<CompositeData,Map> compositeDataToMap() {
+        return new Function<CompositeData, Map>() {
+            @Override public Map apply(CompositeData input) {
+                return compositeDataToMap(input);
+            }};
+    }
+    
+    public static Map tabularDataToMap(TabularData table) {
+        Map<String, Object> result = Maps.newLinkedHashMap();
+        for (Object entry : table.values()) {
+            CompositeData data = (CompositeData) entry; //.getValue()
+            for (String key : data.getCompositeType().keySet()) {
+                Object old = result.put(key, data.get(key));
+                if (old != null) {
+                    log.warn("tablularDataToMap has overwritten key {}", key);
+                }
+            }
+        }
+        return result;
+    }
+    
+    public static Map<List<?>, Map<String, Object>> tabularDataToMapOfMaps(TabularData table) {
+        Map<List<?>, Map<String, Object>> result = Maps.newLinkedHashMap();
+        for (Object k : table.keySet()) {
+            final Object[] kValues = ((List<?>)k).toArray();
+            CompositeData v = (CompositeData) table.get(kValues);
+            result.put((List<?>)k, compositeDataToMap(v));
+        }
+        return result;
+    }
+    
+    public static Map<String, Object> compositeDataToMap(CompositeData data) {
+        Map<String, Object> result = Maps.newLinkedHashMap();
+        for (String key : data.getCompositeType().keySet()) {
+            Object old = result.put(key, data.get(key));
+            if (old != null) {
+                log.warn("compositeDataToMap has overwritten key {}", key);
+            }
+        }
+        return result;
+    }
+}


[41/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/MachineLifecycleEffectorTasksTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/MachineLifecycleEffectorTasksTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/MachineLifecycleEffectorTasksTest.java
deleted file mode 100644
index 3d87dbb..0000000
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/MachineLifecycleEffectorTasksTest.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.entity.software.base;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
-import java.util.List;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
-import org.apache.brooklyn.entity.software.base.SoftwareProcess;
-import org.apache.brooklyn.entity.software.base.SoftwareProcess.StopSoftwareParameters.StopMode;
-import org.apache.brooklyn.entity.software.base.lifecycle.MachineLifecycleEffectorTasks;
-import org.apache.brooklyn.entity.stock.BasicEntity;
-import org.apache.brooklyn.entity.stock.BasicEntityImpl;
-import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.sensor.core.DependentConfiguration;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.core.task.TaskInternal;
-import org.apache.brooklyn.util.time.Duration;
-import org.testng.annotations.DataProvider;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
-import org.apache.brooklyn.location.jclouds.BailOutJcloudsLocation;
-
-public class MachineLifecycleEffectorTasksTest {
-    public static boolean canStop(StopMode stopMode, boolean isEntityStopped) {
-        BasicEntityImpl entity = new BasicEntityImpl();
-        Lifecycle state = isEntityStopped ? Lifecycle.STOPPED : Lifecycle.RUNNING;
-        entity.setAttribute(SoftwareProcess.SERVICE_STATE_ACTUAL, state);
-        return MachineLifecycleEffectorTasks.canStop(stopMode, entity);
-    }
-    
-    @DataProvider(name = "canStopStates")
-    public Object[][] canStopStates() {
-        return new Object[][] {
-            { StopMode.ALWAYS, true, true },
-            { StopMode.ALWAYS, false, true },
-            { StopMode.IF_NOT_STOPPED, true, false },
-            { StopMode.IF_NOT_STOPPED, false, true },
-            { StopMode.NEVER, true, false },
-            { StopMode.NEVER, false, false },
-        };
-    }
-
-    @Test(dataProvider = "canStopStates")
-    public void testBasicSonftwareProcessCanStop(StopMode mode, boolean isEntityStopped, boolean expected) {
-        boolean canStop = canStop(mode, isEntityStopped);
-        assertEquals(canStop, expected);
-    }
-
-    @Test
-    public void testProvisionLatchObeyed() throws Exception {
-
-        AttributeSensor<Boolean> ready = Sensors.newBooleanSensor("readiness");
-
-        TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
-        BasicEntity triggerEntity = app.createAndManageChild(EntitySpec.create(BasicEntity.class));
-
-        EmptySoftwareProcess entity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class)
-                .configure(BrooklynConfigKeys.PROVISION_LATCH, DependentConfiguration.attributeWhenReady(triggerEntity, ready)));
-
-        final Task<Void> task = Entities.invokeEffector(app, app, Startable.START, ImmutableMap.of(
-                "locations", ImmutableList.of(BailOutJcloudsLocation.newBailOutJcloudsLocation(app.getManagementContext()))));
-
-        assertEffectorBlockingDetailsEventually(entity, "Waiting for config " + BrooklynConfigKeys.PROVISION_LATCH.getName());
-
-        Asserts.succeedsContinually(new Runnable() {
-            @Override
-            public void run() {
-                assertFalse(task.isDone());
-            }
-        });
-        try {
-            ((EntityLocal) triggerEntity).setAttribute(ready, true);
-            task.get(Duration.THIRTY_SECONDS);
-        } catch (Throwable t) {
-            // BailOut location throws but we don't care.
-        } finally {
-            Entities.destroyAll(app.getManagementContext());
-        }
-    }
-
-    private void assertEffectorBlockingDetailsEventually(final Entity entity, final String blockingDetailsSnippet) {
-        Asserts.succeedsEventually(new Runnable() {
-            @Override public void run() {
-                Task<?> entityTask = Iterables.getOnlyElement(entity.getApplication().getManagementContext().getExecutionManager().getTasksWithAllTags(
-                        ImmutableList.of(BrooklynTaskTags.EFFECTOR_TAG, BrooklynTaskTags.tagForContextEntity(entity))));
-                String blockingDetails = getBlockingDetails(entityTask);
-                assertTrue(blockingDetails.contains(blockingDetailsSnippet));
-            }});
-    }
-
-    private String getBlockingDetails(Task<?> task) {
-        List<TaskInternal<?>> taskChain = Lists.newArrayList();
-        TaskInternal<?> taskI = (TaskInternal<?>) task;
-        while (taskI != null) {
-            taskChain.add(taskI);
-            if (taskI.getBlockingDetails() != null) {
-                return taskI.getBlockingDetails();
-            }
-            taskI = (TaskInternal<?>) taskI.getBlockingTask();
-        }
-        throw new IllegalStateException("No blocking details for "+task+" (walked task chain "+taskChain+")");
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SameServerEntityTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SameServerEntityTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SameServerEntityTest.java
index 937c87d..bed5d48 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SameServerEntityTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SameServerEntityTest.java
@@ -33,8 +33,8 @@ import org.apache.brooklyn.entity.software.base.SameServerEntity;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation.LocalhostMachine;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareEffectorTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareEffectorTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareEffectorTest.java
index b341b6e..a369772 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareEffectorTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareEffectorTest.java
@@ -37,8 +37,8 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Throwables;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityLatchTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityLatchTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityLatchTest.java
index e743b24..b9731cf 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityLatchTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityLatchTest.java
@@ -42,8 +42,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.util.core.task.TaskInternal;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityRebindTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityRebindTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityRebindTest.java
index 475cb09..6c5718e 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityRebindTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityRebindTest.java
@@ -48,8 +48,8 @@ import org.apache.brooklyn.util.core.flags.SetFromFlag;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.AbstractLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityTest.java
index 0a6bd26..d9d18c1 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityTest.java
@@ -64,6 +64,7 @@ import org.apache.brooklyn.entity.software.base.SoftwareProcess.RestartSoftwareP
 import org.apache.brooklyn.entity.software.base.SoftwareProcess.StopSoftwareParameters;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess.RestartSoftwareParameters.RestartMachineMode;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess.StopSoftwareParameters.StopMode;
+import org.apache.brooklyn.entity.software.base.lifecycle.MachineLifecycleEffectorTasksTest;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.test.Asserts;
@@ -90,10 +91,10 @@ import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
 
-import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.core.Locations;
+import org.apache.brooklyn.location.core.SimulatedLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 
 public class SoftwareProcessEntityTest extends BrooklynAppUnitTestSupport {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessSshDriverIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessSshDriverIntegrationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessSshDriverIntegrationTest.java
index 1b270b9..5b25087 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessSshDriverIntegrationTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessSshDriverIntegrationTest.java
@@ -53,8 +53,8 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Charsets;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasksTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasksTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasksTest.java
new file mode 100644
index 0000000..24838c6
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasksTest.java
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.lifecycle;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.util.List;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.StopSoftwareParameters.StopMode;
+import org.apache.brooklyn.entity.stock.BasicEntity;
+import org.apache.brooklyn.entity.stock.BasicEntityImpl;
+import org.apache.brooklyn.entity.trait.Startable;
+import org.apache.brooklyn.location.jclouds.BailOutJcloudsLocation;
+import org.apache.brooklyn.sensor.core.DependentConfiguration;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.core.task.TaskInternal;
+import org.apache.brooklyn.util.core.task.ValueResolver;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+
+public class MachineLifecycleEffectorTasksTest {
+    public static boolean canStop(StopMode stopMode, boolean isEntityStopped) {
+        BasicEntityImpl entity = new BasicEntityImpl();
+        Lifecycle state = isEntityStopped ? Lifecycle.STOPPED : Lifecycle.RUNNING;
+        entity.setAttribute(SoftwareProcess.SERVICE_STATE_ACTUAL, state);
+        return MachineLifecycleEffectorTasks.canStop(stopMode, entity);
+    }
+    
+    @DataProvider(name = "canStopStates")
+    public Object[][] canStopStates() {
+        return new Object[][] {
+            { StopMode.ALWAYS, true, true },
+            { StopMode.ALWAYS, false, true },
+            { StopMode.IF_NOT_STOPPED, true, false },
+            { StopMode.IF_NOT_STOPPED, false, true },
+            { StopMode.NEVER, true, false },
+            { StopMode.NEVER, false, false },
+        };
+    }
+
+    @Test(dataProvider = "canStopStates")
+    public void testBasicSonftwareProcessCanStop(StopMode mode, boolean isEntityStopped, boolean expected) {
+        boolean canStop = canStop(mode, isEntityStopped);
+        assertEquals(canStop, expected);
+    }
+
+    @Test(groups="Integration")
+    public void testProvisionLatchObeyed() throws Exception {
+
+        AttributeSensor<Boolean> ready = Sensors.newBooleanSensor("readiness");
+
+        TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
+        BasicEntity triggerEntity = app.createAndManageChild(EntitySpec.create(BasicEntity.class));
+
+        EmptySoftwareProcess entity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class)
+                .configure(BrooklynConfigKeys.PROVISION_LATCH, DependentConfiguration.attributeWhenReady(triggerEntity, ready)));
+
+        final Task<Void> task = Entities.invokeEffector(app, app, Startable.START, ImmutableMap.of(
+                "locations", ImmutableList.of(BailOutJcloudsLocation.newBailOutJcloudsLocation(app.getManagementContext()))));
+        
+        Time.sleep(ValueResolver.PRETTY_QUICK_WAIT);
+        if (task.isDone()) throw new IllegalStateException("Task finished early with: "+task.get());
+        assertEffectorBlockingDetailsEventually(entity, "Waiting for config " + BrooklynConfigKeys.PROVISION_LATCH.getName());
+
+        Asserts.succeedsContinually(new Runnable() {
+            @Override
+            public void run() {
+                if (task.isDone()) throw new IllegalStateException("Task finished early with: "+task.getUnchecked());
+            }
+        });
+        try {
+            ((EntityLocal) triggerEntity).setAttribute(ready, true);
+            task.get(Duration.THIRTY_SECONDS);
+        } catch (Throwable t) {
+            Exceptions.propagateIfFatal(t);
+            if ((t.toString().contains(BailOutJcloudsLocation.ERROR_MESSAGE))) {
+                // expected - BailOut location throws - just swallow
+            } else {
+                Exceptions.propagate(t);
+            }
+        } finally {
+            Entities.destroyAll(app.getManagementContext());
+        }
+    }
+
+    private void assertEffectorBlockingDetailsEventually(final Entity entity, final String blockingDetailsSnippet) {
+        Asserts.succeedsEventually(new Runnable() {
+            @Override public void run() {
+                Task<?> entityTask = Iterables.getOnlyElement(entity.getApplication().getManagementContext().getExecutionManager().getTasksWithAllTags(
+                        ImmutableList.of(BrooklynTaskTags.EFFECTOR_TAG, BrooklynTaskTags.tagForContextEntity(entity))));
+                String blockingDetails = getBlockingDetails(entityTask);
+                assertTrue(blockingDetails.contains(blockingDetailsSnippet));
+            }});
+    }
+
+    private String getBlockingDetails(Task<?> task) {
+        List<TaskInternal<?>> taskChain = Lists.newArrayList();
+        TaskInternal<?> taskI = (TaskInternal<?>) task;
+        while (taskI != null) {
+            taskChain.add(taskI);
+            if (taskI.getBlockingDetails() != null) {
+                return taskI.getBlockingDetails();
+            }
+            taskI = (TaskInternal<?>) taskI.getBlockingTask();
+        }
+        throw new IllegalStateException("No blocking details for "+task+" (walked task chain "+taskChain+")");
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntityImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntityImpl.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntityImpl.java
index 15dd95b..45e887e 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntityImpl.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntityImpl.java
@@ -26,7 +26,7 @@ import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.ResourceUtils;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/NaiveScriptRunnerTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/NaiveScriptRunnerTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/NaiveScriptRunnerTest.java
index 59103f1..e1f801b 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/NaiveScriptRunnerTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/NaiveScriptRunnerTest.java
@@ -35,7 +35,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.task.BasicExecutionContext;
 import org.apache.brooklyn.util.core.task.BasicExecutionManager;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelperTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelperTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelperTest.java
index 479c24f..09af630 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelperTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelperTest.java
@@ -41,8 +41,8 @@ import org.testng.Assert;
 import org.testng.TestException;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Functions;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/StartStopSshDriverTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/StartStopSshDriverTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/StartStopSshDriverTest.java
index 1bf3bbe..103f916 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/StartStopSshDriverTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/StartStopSshDriverTest.java
@@ -47,7 +47,7 @@ import org.apache.brooklyn.util.core.internal.ssh.sshj.SshjTool;
 import org.apache.brooklyn.util.stream.StreamGobbler;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Function;
 import com.google.common.collect.FluentIterable;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/LocationUsageTrackingTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/LocationUsageTrackingTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/LocationUsageTrackingTest.java
index 44760ac..8302f86 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/LocationUsageTrackingTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/LocationUsageTrackingTest.java
@@ -39,8 +39,8 @@ import org.apache.brooklyn.entity.lifecycle.Lifecycle;
 import org.apache.brooklyn.entity.software.base.SoftwareProcessEntityTest;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.util.time.Time;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/driver/MockSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/driver/MockSshDriver.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/driver/MockSshDriver.java
index 9c92b5b..e15d2f5 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/driver/MockSshDriver.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/driver/MockSshDriver.java
@@ -21,7 +21,7 @@ package org.apache.brooklyn.entity.software.base.test.driver;
 import org.apache.brooklyn.api.internal.EntityLocal;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 public class MockSshDriver implements SoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/group/DynamicClusterWithAvailabilityZonesMultiLocationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/group/DynamicClusterWithAvailabilityZonesMultiLocationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/group/DynamicClusterWithAvailabilityZonesMultiLocationTest.java
index 474ce0f..d93f008 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/group/DynamicClusterWithAvailabilityZonesMultiLocationTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/group/DynamicClusterWithAvailabilityZonesMultiLocationTest.java
@@ -38,8 +38,8 @@ import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.MultiLocation;
+import org.apache.brooklyn.location.core.MultiLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.test.Asserts;
 
 import com.google.common.base.Predicate;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsEc2LiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsEc2LiveTest.java
index b9e3d68..c257b6b 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsEc2LiveTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsEc2LiveTest.java
@@ -29,9 +29,9 @@ import org.apache.brooklyn.api.location.OsDetails;
 import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
 import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.location.basic.BasicMachineDetails;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.BasicMachineDetails;
+import org.apache.brooklyn.location.core.Locations;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.slf4j.Logger;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsGoogleComputeLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsGoogleComputeLiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsGoogleComputeLiveTest.java
index 1234f41..bb4df77 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsGoogleComputeLiveTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsGoogleComputeLiveTest.java
@@ -29,9 +29,9 @@ import org.apache.brooklyn.api.location.OsDetails;
 import org.apache.brooklyn.entity.AbstractGoogleComputeLiveTest;
 import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
 import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.location.basic.BasicMachineDetails;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.BasicMachineDetails;
+import org.apache.brooklyn.location.core.Locations;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/WinRmMachineLocationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/WinRmMachineLocationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/WinRmMachineLocationTest.java
deleted file mode 100644
index 8880d88..0000000
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/WinRmMachineLocationTest.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.entity.software.base.test.location;
-
-import static org.testng.Assert.assertEquals;
-
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.location.basic.WinRmMachineLocation;
-import org.apache.brooklyn.util.net.Networking;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
-
-public class WinRmMachineLocationTest extends BrooklynAppUnitTestSupport {
-
-    @Test
-    public void testConfigurePrivateAddresses() throws Exception {
-        WinRmMachineLocation host = mgmt.getLocationManager().createLocation(LocationSpec.create(WinRmMachineLocation.class)
-                .configure("address", Networking.getLocalHost())
-                .configure(WinRmMachineLocation.PRIVATE_ADDRESSES, ImmutableList.of("1.2.3.4"))
-                .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, true));
-
-        assertEquals(host.getPrivateAddresses(), ImmutableSet.of("1.2.3.4"));
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/AbstractToyMySqlEntityTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/AbstractToyMySqlEntityTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/AbstractToyMySqlEntityTest.java
index e7bc7d8..2446e65 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/AbstractToyMySqlEntityTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/AbstractToyMySqlEntityTest.java
@@ -36,8 +36,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.BeforeMethod;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.Iterables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityBuilder.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityBuilder.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityBuilder.java
index 650c28c..3b0b100 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityBuilder.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityBuilder.java
@@ -32,9 +32,9 @@ import org.apache.brooklyn.entity.software.base.lifecycle.MachineLifecycleEffect
 import org.apache.brooklyn.entity.stock.BasicStartable;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.BasicOsDetails.OsVersions;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.BasicOsDetails.OsVersions;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation.LocalhostMachine;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.core.task.DynamicTasks;
 import org.apache.brooklyn.util.core.task.Tasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityTest.java
index d676c00..46fd126 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityTest.java
@@ -24,7 +24,7 @@ import org.apache.brooklyn.api.entity.Entity;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/sensor/core/PortAttributeSensorAndConfigKeyTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/sensor/core/PortAttributeSensorAndConfigKeyTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/sensor/core/PortAttributeSensorAndConfigKeyTest.java
index 66049b5..92c1953 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/sensor/core/PortAttributeSensorAndConfigKeyTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/sensor/core/PortAttributeSensorAndConfigKeyTest.java
@@ -28,8 +28,8 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
 import org.apache.brooklyn.entity.software.base.EmptySoftwareProcessImpl;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/ssh/SshCommandIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/ssh/SshCommandIntegrationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/ssh/SshCommandIntegrationTest.java
index c51725c..fad701c 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/ssh/SshCommandIntegrationTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/ssh/SshCommandIntegrationTest.java
@@ -43,7 +43,7 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricherTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricherTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricherTest.java
index 87ad639..934e88f 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricherTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricherTest.java
@@ -34,8 +34,8 @@ import org.apache.brooklyn.entity.software.base.VanillaSoftwareProcessSshDriver;
 import org.apache.brooklyn.entity.system_service.SystemServiceEnricher;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.location.jclouds.JcloudsLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.util.ssh.BashCommands;
 import org.apache.brooklyn.util.time.Duration;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeedTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeedTest.java b/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeedTest.java
index 124e00a..8a19afd 100644
--- a/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeedTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeedTest.java
@@ -77,9 +77,9 @@ import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 import org.testng.collections.Lists;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.PortRanges;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.location.core.SimulatedLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/RebindJmxFeedTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/RebindJmxFeedTest.java b/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/RebindJmxFeedTest.java
index f4a72cd..d39e7cd 100644
--- a/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/RebindJmxFeedTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/RebindJmxFeedTest.java
@@ -48,8 +48,8 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/base/src/test/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasksTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasksTest.java b/software/base/src/test/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasksTest.java
index 073a8df..f786d23 100644
--- a/software/base/src/test/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasksTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasksTest.java
@@ -41,8 +41,8 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.io.Files;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNode.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNode.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNode.java
index 94b03bf..30f5800 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNode.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNode.java
@@ -28,7 +28,7 @@ import org.apache.brooklyn.entity.java.UsesJava;
 import org.apache.brooklyn.entity.java.UsesJavaMXBeans;
 import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.sensor.core.AttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeSshDriver.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeSshDriver.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeSshDriver.java
index fbfe9dd..fda1c65 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeSshDriver.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeSshDriver.java
@@ -28,7 +28,7 @@ import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
 
 import com.google.common.collect.ImmutableList;
 
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Urls;
 import org.apache.brooklyn.util.os.Os;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNode.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNode.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNode.java
index a5a91f6..1755802 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNode.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNode.java
@@ -29,7 +29,7 @@ import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.database.DatabaseNode;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.Sensors;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNodeImpl.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNodeImpl.java
index 0b5becf..f613046 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNodeImpl.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNodeImpl.java
@@ -22,8 +22,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.effector.core.EffectorBody;
 import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.Locations;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.ssh.SshFeed;
 import org.apache.brooklyn.sensor.feed.ssh.SshPollConfig;
 import org.apache.brooklyn.sensor.feed.ssh.SshPollValue;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbSshDriver.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbSshDriver.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbSshDriver.java
index 300cc35..0827c96 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbSshDriver.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbSshDriver.java
@@ -38,7 +38,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.database.DatastoreMixins;
 import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.apache.brooklyn.api.location.OsDetails;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.task.DynamicTasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNode.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNode.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNode.java
index be837c4..038c0f6 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNode.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNode.java
@@ -31,7 +31,7 @@ import org.apache.brooklyn.entity.annotation.EffectorParam;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.Sensors;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNodeImpl.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNodeImpl.java
index 4f0ae7d..1fd8b6d 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNodeImpl.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNodeImpl.java
@@ -25,8 +25,8 @@ import org.apache.brooklyn.effector.core.EffectorBody;
 import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.Locations;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.ssh.SshFeed;
 import org.apache.brooklyn.sensor.feed.ssh.SshPollConfig;
 import org.apache.brooklyn.sensor.feed.ssh.SshPollValue;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlSshDriver.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlSshDriver.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlSshDriver.java
index b73b6c1..978ce83 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlSshDriver.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlSshDriver.java
@@ -40,8 +40,8 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.database.DatastoreMixins;
 import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.apache.brooklyn.api.location.OsDetails;
-import org.apache.brooklyn.location.basic.BasicOsDetails.OsVersions;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.BasicOsDetails.OsVersions;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.task.DynamicTasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNode.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNode.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNode.java
index 168179c..08d46c1 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNode.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNode.java
@@ -29,7 +29,7 @@ import org.apache.brooklyn.entity.database.DatabaseNode;
 import org.apache.brooklyn.entity.database.DatastoreMixins;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNodeChefImplFromScratch.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNodeChefImplFromScratch.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNodeChefImplFromScratch.java
index f839a91..c291be6 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNodeChefImplFromScratch.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNodeChefImplFromScratch.java
@@ -30,8 +30,8 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.stock.EffectorStartableImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.Locations;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.ssh.SshFeed;
 import org.apache.brooklyn.sensor.feed.ssh.SshPollConfig;
 import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlSshDriver.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlSshDriver.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlSshDriver.java
index ec70005..749031c 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlSshDriver.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlSshDriver.java
@@ -39,7 +39,7 @@ import java.io.InputStream;
 import javax.annotation.Nullable;
 
 import org.apache.brooklyn.api.location.OsDetails;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.MutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepSshDriver.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepSshDriver.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepSshDriver.java
index 4a11b63..4925770 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepSshDriver.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepSshDriver.java
@@ -31,7 +31,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.os.Os;
 import org.apache.brooklyn.util.ssh.BashCommands;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/test/java/org/apache/brooklyn/entity/database/crate/CrateNodeIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/crate/CrateNodeIntegrationTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/crate/CrateNodeIntegrationTest.java
index 126fb08..f4c28d5 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/crate/CrateNodeIntegrationTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/crate/CrateNodeIntegrationTest.java
@@ -32,7 +32,7 @@ import org.testng.annotations.Test;
 
 import com.google.common.collect.ImmutableList;
 
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 public class CrateNodeIntegrationTest {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/test/java/org/apache/brooklyn/entity/database/mariadb/MariaDbIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/mariadb/MariaDbIntegrationTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/mariadb/MariaDbIntegrationTest.java
index 86fb752..04d6f78 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/mariadb/MariaDbIntegrationTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/mariadb/MariaDbIntegrationTest.java
@@ -38,7 +38,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.VogellaExampleAccess;
 import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/test/java/org/apache/brooklyn/entity/database/mariadb/MariaDbLiveRackspaceTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/mariadb/MariaDbLiveRackspaceTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/mariadb/MariaDbLiveRackspaceTest.java
index 3476163..b5474f8 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/mariadb/MariaDbLiveRackspaceTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/mariadb/MariaDbLiveRackspaceTest.java
@@ -24,8 +24,8 @@ import org.apache.brooklyn.api.entity.EntitySpec;
 import org.testng.annotations.Test;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.VogellaExampleAccess;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.location.jclouds.JcloudsLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.net.Protocol;
 import org.apache.brooklyn.util.ssh.IptablesCommands;
 import org.apache.brooklyn.util.ssh.IptablesCommands.Chain;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlIntegrationTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlIntegrationTest.java
index 0ea106f..139a1e7 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlIntegrationTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlIntegrationTest.java
@@ -27,7 +27,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.Test;
 import org.apache.brooklyn.entity.database.VogellaExampleAccess;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;
 import org.apache.brooklyn.util.os.Os;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlLiveRackspaceTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlLiveRackspaceTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlLiveRackspaceTest.java
index 31fbd78..46396fd 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlLiveRackspaceTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlLiveRackspaceTest.java
@@ -25,8 +25,8 @@ import org.apache.brooklyn.core.internal.BrooklynProperties;
 import org.testng.annotations.Test;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.VogellaExampleAccess;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.location.jclouds.JcloudsLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.net.Protocol;
 import org.apache.brooklyn.util.ssh.IptablesCommands;
 import org.apache.brooklyn.util.ssh.IptablesCommands.Chain;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlChefTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlChefTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlChefTest.java
index 7ae04f7..cf6d62d 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlChefTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlChefTest.java
@@ -30,8 +30,8 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.VogellaExampleAccess;
 import org.apache.brooklyn.api.location.PortRange;
-import org.apache.brooklyn.location.basic.PortRanges;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
 import org.apache.brooklyn.util.time.Duration;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlIntegrationTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlIntegrationTest.java
index 1d10e9b..0f2392e 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlIntegrationTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlIntegrationTest.java
@@ -32,7 +32,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.VogellaExampleAccess;
 import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlRackspaceLiveTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlRackspaceLiveTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlRackspaceLiveTest.java
index 264ff70..e07d693 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlRackspaceLiveTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlRackspaceLiveTest.java
@@ -24,9 +24,9 @@ import org.apache.brooklyn.api.entity.EntitySpec;
 import org.testng.annotations.Test;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.VogellaExampleAccess;
-import org.apache.brooklyn.location.basic.PortRanges;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.location.jclouds.JcloudsLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.net.Protocol;
 import org.apache.brooklyn.util.ssh.IptablesCommands;
 import org.apache.brooklyn.util.ssh.IptablesCommands.Chain;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlRebindIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlRebindIntegrationTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlRebindIntegrationTest.java
index 7f0d632..320c14b 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlRebindIntegrationTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlRebindIntegrationTest.java
@@ -23,7 +23,7 @@ import org.apache.brooklyn.core.mgmt.rebind.RebindTestFixtureWithApp;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepEc2LiveTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepEc2LiveTest.java
index db7dcbd..1e3a418 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepEc2LiveTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepEc2LiveTest.java
@@ -25,7 +25,7 @@ import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.postgresql.PostgreSqlIntegrationTest;
 import org.apache.brooklyn.entity.database.postgresql.PostgreSqlNode;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 
 public class RubyRepEc2LiveTest extends AbstractEc2LiveTest {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepIntegrationTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepIntegrationTest.java
index 69f5c9e..4740772 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepIntegrationTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepIntegrationTest.java
@@ -42,8 +42,8 @@ import org.apache.brooklyn.entity.database.mysql.MySqlNode;
 import org.apache.brooklyn.entity.database.postgresql.PostgreSqlIntegrationTest;
 import org.apache.brooklyn.entity.database.postgresql.PostgreSqlNode;
 import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 public class RubyRepIntegrationTest {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepRackspaceLiveTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepRackspaceLiveTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepRackspaceLiveTest.java
index d8946c7..361b8d6 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepRackspaceLiveTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepRackspaceLiveTest.java
@@ -26,8 +26,8 @@ import org.testng.annotations.Test;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.postgresql.PostgreSqlIntegrationTest;
 import org.apache.brooklyn.entity.database.postgresql.PostgreSqlNode;
-import org.apache.brooklyn.location.basic.PortRanges;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.net.Protocol;
 import org.apache.brooklyn.util.ssh.IptablesCommands;
 import org.apache.brooklyn.util.ssh.IptablesCommands.Chain;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQSshDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQSshDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQSshDriver.java
index 56cbbd5..b73cf1a 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQSshDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQSshDriver.java
@@ -26,7 +26,7 @@ import java.util.Map;
 
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;
 import org.apache.brooklyn.util.os.Os;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/AbstractfKafkaSshDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/AbstractfKafkaSshDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/AbstractfKafkaSshDriver.java
index efcb5a8..72ffef7 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/AbstractfKafkaSshDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/AbstractfKafkaSshDriver.java
@@ -30,7 +30,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;
 import org.apache.brooklyn.util.os.Os;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBroker.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBroker.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBroker.java
index 65576f3..0e71a83 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBroker.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBroker.java
@@ -27,7 +27,7 @@ import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.entity.messaging.MessageBroker;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.zookeeper.ZooKeeperNode;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.Sensors;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerSshDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerSshDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerSshDriver.java
index b1eeb43..3b6ffd3 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerSshDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerSshDriver.java
@@ -25,7 +25,7 @@ import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.entity.java.UsesJmx.JmxAgentModes;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 
 public class KafkaBrokerSshDriver extends AbstractfKafkaSshDriver implements KafkaBrokerDriver {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaZooKeeperSshDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaZooKeeperSshDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaZooKeeperSshDriver.java
index a392d71..29fa8fa 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaZooKeeperSshDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaZooKeeperSshDriver.java
@@ -22,7 +22,7 @@ import java.util.Map;
 
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 
 import static org.apache.brooklyn.util.text.StringEscapes.BashStringEscapes.escapeLiteralForDoubleQuotedBash;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidSshDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidSshDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidSshDriver.java
index 318c24a..a628d42 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidSshDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidSshDriver.java
@@ -28,7 +28,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;
 import org.apache.brooklyn.util.os.Os;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitDestination.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitDestination.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitDestination.java
index 67f8975..484defd 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitDestination.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitDestination.java
@@ -24,7 +24,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.entity.core.AbstractEntity;
 import org.apache.brooklyn.entity.messaging.amqp.AmqpExchange;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Objects.ToStringHelper;
 import com.google.common.base.Predicates;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitSshDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitSshDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitSshDriver.java
index 98f87ec..c9d9872 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitSshDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitSshDriver.java
@@ -35,7 +35,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.messaging.amqp.AmqpServer;
 import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelper;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;
 import org.apache.brooklyn.util.os.Os;



[51/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/group/zoneaware/ProportionalZoneFailureDetectorTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/group/zoneaware/ProportionalZoneFailureDetectorTest.java b/core/src/test/java/org/apache/brooklyn/entity/group/zoneaware/ProportionalZoneFailureDetectorTest.java
index 3bc5b9d..451ec1b 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/group/zoneaware/ProportionalZoneFailureDetectorTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/group/zoneaware/ProportionalZoneFailureDetectorTest.java
@@ -32,7 +32,7 @@ import org.apache.brooklyn.entity.group.zoneaware.ProportionalZoneFailureDetecto
 import org.apache.brooklyn.util.time.Duration;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Ticker;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/hello/LocalEntitiesTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/hello/LocalEntitiesTest.java b/core/src/test/java/org/apache/brooklyn/entity/hello/LocalEntitiesTest.java
index 01b4992..3dd71e7 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/hello/LocalEntitiesTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/hello/LocalEntitiesTest.java
@@ -47,7 +47,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 import org.testng.collections.Lists;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.time.Time;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/stock/BasicStartableTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/stock/BasicStartableTest.java b/core/src/test/java/org/apache/brooklyn/entity/stock/BasicStartableTest.java
index 19ef05e..0f64426 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/stock/BasicStartableTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/stock/BasicStartableTest.java
@@ -50,8 +50,8 @@ import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 
-import org.apache.brooklyn.location.basic.Locations.LocationsFilter;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
+import org.apache.brooklyn.location.core.Locations.LocationsFilter;
 
 public class BasicStartableTest {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/stock/DataEntityTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/stock/DataEntityTest.java b/core/src/test/java/org/apache/brooklyn/entity/stock/DataEntityTest.java
index 49ae17e..a177a1b 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/stock/DataEntityTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/stock/DataEntityTest.java
@@ -39,7 +39,7 @@ import org.apache.brooklyn.util.collections.MutableMap;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.base.Supplier;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/entity/trait/StartableMethodsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/trait/StartableMethodsTest.java b/core/src/test/java/org/apache/brooklyn/entity/trait/StartableMethodsTest.java
index 49c4456..8a099c6 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/trait/StartableMethodsTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/trait/StartableMethodsTest.java
@@ -31,7 +31,7 @@ import org.apache.brooklyn.entity.trait.FailingEntity.RecordingEventListener;
 import org.apache.brooklyn.util.core.task.Tasks;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/access/BrooklynAccessUtilsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/access/BrooklynAccessUtilsTest.java b/core/src/test/java/org/apache/brooklyn/location/access/BrooklynAccessUtilsTest.java
index c43ca5a..91e06f8 100644
--- a/core/src/test/java/org/apache/brooklyn/location/access/BrooklynAccessUtilsTest.java
+++ b/core/src/test/java/org/apache/brooklyn/location/access/BrooklynAccessUtilsTest.java
@@ -30,8 +30,8 @@ import org.apache.brooklyn.api.location.LocationSpec;
 import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
 import org.apache.brooklyn.core.test.entity.TestEntity;
 import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.location.basic.SupportsPortForwarding;
+import org.apache.brooklyn.location.core.SupportsPortForwarding;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.net.Cidr;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/access/PortForwardManagerRebindTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/access/PortForwardManagerRebindTest.java b/core/src/test/java/org/apache/brooklyn/location/access/PortForwardManagerRebindTest.java
index 45b6991..58308f4 100644
--- a/core/src/test/java/org/apache/brooklyn/location/access/PortForwardManagerRebindTest.java
+++ b/core/src/test/java/org/apache/brooklyn/location/access/PortForwardManagerRebindTest.java
@@ -30,12 +30,12 @@ import org.apache.brooklyn.api.mgmt.ha.MementoCopyMode;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynPersistenceUtils;
+import org.apache.brooklyn.core.mgmt.persist.FileBasedObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
 import org.apache.brooklyn.core.mgmt.rebind.RebindOptions;
 import org.apache.brooklyn.core.mgmt.rebind.RebindTestFixtureWithApp;
 import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynPersistenceUtils;
-import org.apache.brooklyn.core.mgmt.rebind.persister.FileBasedObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
 import org.apache.brooklyn.core.test.entity.TestEntity;
 import org.apache.brooklyn.core.test.entity.TestEntityImpl;
 import org.apache.brooklyn.sensor.core.Sensors;
@@ -47,7 +47,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.Iterables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/access/PortForwardManagerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/access/PortForwardManagerTest.java b/core/src/test/java/org/apache/brooklyn/location/access/PortForwardManagerTest.java
index 9246694..1017828 100644
--- a/core/src/test/java/org/apache/brooklyn/location/access/PortForwardManagerTest.java
+++ b/core/src/test/java/org/apache/brooklyn/location/access/PortForwardManagerTest.java
@@ -35,7 +35,7 @@ import org.apache.brooklyn.core.internal.BrooklynProperties;
 import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
 import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Predicate;
 import com.google.common.net.HostAndPort;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/AbstractLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/AbstractLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/AbstractLocationTest.java
deleted file mode 100644
index af9191d..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/AbstractLocationTest.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNotEquals;
-import static org.testng.Assert.assertTrue;
-
-import java.util.Collections;
-import java.util.Map;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.collections.MutableSet;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-public class AbstractLocationTest {
-
-    public static class ConcreteLocation extends AbstractLocation {
-        private static final long serialVersionUID = 3954199300889119970L;
-        @SetFromFlag(defaultVal="mydefault")
-        String myfield;
-
-        public ConcreteLocation() {
-            super();
-        }
-
-        public ConcreteLocation(Map<?,?> properties) {
-            super(properties);
-        }
-    }
-
-    private ManagementContext mgmt;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        mgmt = LocalManagementContextForTests.newInstance();
-    }
-    
-    @AfterMethod(alwaysRun = true)
-    public void tearDown(){
-        if (mgmt!=null) Entities.destroyAll(mgmt);
-    }
-
-    private ConcreteLocation createConcrete() {
-        return createConcrete(MutableMap.<String,Object>of());
-    }
-    private ConcreteLocation createConcrete(Map<String,?> flags) {
-        return createConcrete(null, flags);
-    }
-    @SuppressWarnings("deprecation")
-    private ConcreteLocation createConcrete(String id, Map<String,?> flags) {
-        return mgmt.getLocationManager().createLocation( LocationSpec.create(ConcreteLocation.class).id(id).configure(flags) );
-    }
-    
-    @Test
-    public void testEqualsUsesId() {
-        Location l1 = createConcrete("1", MutableMap.of("name", "bob"));
-        Location l1b = new ConcreteLocation(ImmutableMap.of("id", 1));
-        Location l2 = createConcrete("2", MutableMap.of("name", "frank"));
-        assertEquals(l1, l1b);
-        assertNotEquals(l1, l2);
-    }
-
-    @Test
-    public void nullNameAndParentLocationIsAcceptable() {
-        Location location = createConcrete(MutableMap.of("name", null, "parentLocation", null));
-        assertEquals(location.getDisplayName(), null);
-        assertEquals(location.getParent(), null);
-    }
-
-    @Test
-    public void testSettingParentLocation() {
-        Location location = createConcrete();
-        Location locationSub = createConcrete();
-        locationSub.setParent(location);
-        
-        assertEquals(ImmutableList.copyOf(location.getChildren()), ImmutableList.of(locationSub));
-        assertEquals(locationSub.getParent(), location);
-    }
-
-    @Test
-    public void testClearingParentLocation() {
-        Location location = createConcrete();
-        Location locationSub = createConcrete();
-        locationSub.setParent(location);
-        
-        locationSub.setParent(null);
-        assertEquals(ImmutableList.copyOf(location.getChildren()), Collections.emptyList());
-        assertEquals(locationSub.getParent(), null);
-    }
-    
-    @Test
-    public void testContainsLocation() {
-        Location location = createConcrete();
-        Location locationSub = createConcrete();
-        locationSub.setParent(location);
-        
-        assertTrue(location.containsLocation(location));
-        assertTrue(location.containsLocation(locationSub));
-        assertFalse(locationSub.containsLocation(location));
-    }
-
-
-    @Test
-    public void queryingNameReturnsNameGivenInConstructor() {
-        String name = "Outer Mongolia";
-        Location location = createConcrete(MutableMap.of("name", "Outer Mongolia"));
-        assertEquals(location.getDisplayName(), name);;
-    }
-
-    @Test
-    public void constructorParentLocationReturnsExpectedLocation() {
-        Location parent = createConcrete(MutableMap.of("name", "Middle Earth"));
-        Location child = createConcrete(MutableMap.of("name", "The Shire", "parentLocation", parent));
-        assertEquals(child.getParent(), parent);
-        assertEquals(ImmutableList.copyOf(parent.getChildren()), ImmutableList.of(child));
-    }
-
-    @Test
-    public void setParentLocationReturnsExpectedLocation() {
-        Location parent = createConcrete(MutableMap.of("name", "Middle Earth"));
-        Location child = createConcrete(MutableMap.of("name", "The Shire"));
-        child.setParent(parent);
-        assertEquals(child.getParent(), parent);
-        assertEquals(ImmutableList.copyOf(parent.getChildren()), ImmutableList.of(child));
-    }
-    
-    @Test
-    public void testAddChildToParentLocationReturnsExpectedLocation() {
-        ConcreteLocation parent = createConcrete();
-        Location child = createConcrete();
-        parent.addChild(child);
-        assertEquals(child.getParent(), parent);
-        assertEquals(ImmutableList.copyOf(parent.getChildren()), ImmutableList.of(child));
-    }
-
-    @Test
-    public void testFieldSetFromFlag() {
-        ConcreteLocation loc = createConcrete(MutableMap.of("myfield", "myval"));
-        assertEquals(loc.myfield, "myval");
-    }
-    
-    @Test
-    public void testFieldSetFromFlagUsesDefault() {
-        ConcreteLocation loc = createConcrete();
-        assertEquals(loc.myfield, "mydefault");
-    }
-
-    @Test
-    public void testLocationTags() throws Exception {
-        LocationInternal loc = mgmt.getLocationManager().createLocation(LocationSpec.create(ConcreteLocation.class).tag("x"));
-        assertEquals(loc.tags().getTags(), MutableSet.of("x"));
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/AggregatingMachineProvisioningLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/AggregatingMachineProvisioningLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/AggregatingMachineProvisioningLocationTest.java
deleted file mode 100644
index 75996a1..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/AggregatingMachineProvisioningLocationTest.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.fail;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-public class AggregatingMachineProvisioningLocationTest {
-
-    
-    private LocalManagementContext managementContext;
-    private AggregatingMachineProvisioningLocation<LocalhostMachine> aggregator;
-    private LocalhostMachine machine1a;
-    private LocalhostMachine machine1b;
-    private LocalhostMachine machine2a;
-    private LocalhostMachine machine2b;
-    private MachineProvisioningLocation<LocalhostMachine> provisioner1;
-    private MachineProvisioningLocation<LocalhostMachine> provisioner2;
-    
-    @BeforeMethod(alwaysRun=true)
-    @SuppressWarnings("unchecked")
-    public void setUp() {
-        managementContext = new LocalManagementContextForTests();
-        machine1a = newLocation(LocalhostMachine.class, "1a");
-        machine1b = newLocation(LocalhostMachine.class, "1b");
-        machine2a = newLocation(LocalhostMachine.class, "2a");
-        machine2b = newLocation(LocalhostMachine.class, "2b");
-        provisioner1 = newLocation(FixedListMachineProvisioningLocation.class, ImmutableMap.of("machines", ImmutableList.of(machine1a, machine1b)));
-        provisioner2 = newLocation(FixedListMachineProvisioningLocation.class, ImmutableMap.of("machines", ImmutableList.of(machine2a, machine2b)));
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() {
-        if (managementContext != null) Entities.destroyAll(managementContext);
-    }
-
-    @Test
-    @SuppressWarnings("unchecked")
-    public void testObtainAndRelease() throws Exception {
-        aggregator = newLocation(AggregatingMachineProvisioningLocation.class, ImmutableMap.of("provisioners", ImmutableList.of(provisioner1, provisioner2)));
-        assertEquals(aggregator.obtain(), machine1a);
-        assertEquals(aggregator.obtain(), machine2a);
-        assertEquals(aggregator.obtain(), machine1b);
-        assertEquals(aggregator.obtain(), machine2b);
-        
-        try {
-            aggregator.obtain();
-            fail();
-        } catch (NoMachinesAvailableException e) {
-            // success
-        }
-        
-        aggregator.release(machine2b);
-        assertEquals(aggregator.obtain(), machine2b);
-    }
-
-    @Test
-    @SuppressWarnings("unchecked")
-    public void testReleaseWhenNotHeldThrows() throws Exception {
-        aggregator = newLocation(AggregatingMachineProvisioningLocation.class, ImmutableMap.of("provisioners", ImmutableList.of(provisioner1, provisioner2)));
-        try {
-            aggregator.release(machine1a);
-            fail();
-        } catch (IllegalStateException e) {
-            if (!e.toString().contains("machine is not currently allocated")) throw e;
-        }
-    }
-
-    private <T extends Location> T newLocation(Class<T> clazz, String displayName) {
-        return newLocation(clazz, displayName, ImmutableMap.of());
-    }
-
-    private <T extends Location> T newLocation(Class<T> clazz, Map<?,?> config) {
-        return newLocation(clazz, "mydisplayname", config);
-    }
-    
-    private <T extends Location> T newLocation(Class<T> clazz, String displayName, Map<?,?> config) {
-        return managementContext.getLocationManager().createLocation(LocationSpec.create(clazz)
-                .displayName(displayName)
-                .configure(config));
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/ByonLocationResolverTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/ByonLocationResolverTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/ByonLocationResolverTest.java
deleted file mode 100644
index bd799b0..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/ByonLocationResolverTest.java
+++ /dev/null
@@ -1,422 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
-
-import java.net.InetAddress;
-import java.util.List;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Set;
-
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.net.Networking;
-import org.apache.brooklyn.util.net.UserAndHostAndPort;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.text.StringPredicates;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Function;
-import com.google.common.base.Joiner;
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-
-public class ByonLocationResolverTest {
-
-    private static final Logger log = LoggerFactory.getLogger(ByonLocationResolverTest.class);
-    
-    private BrooklynProperties brooklynProperties;
-    private LocalManagementContext managementContext;
-    private Predicate<CharSequence> defaultNamePredicate;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        managementContext = LocalManagementContextForTests.newInstance();
-        brooklynProperties = managementContext.getBrooklynProperties();
-        defaultNamePredicate = StringPredicates.startsWith(FixedListMachineProvisioningLocation.class.getSimpleName());
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (managementContext != null) Entities.destroyAll(managementContext);
-    }
-    
-    @Test
-    public void testTakesByonScopedProperties() {
-        brooklynProperties.put("brooklyn.location.byon.privateKeyFile", "myprivatekeyfile");
-        brooklynProperties.put("brooklyn.location.byon.publicKeyFile", "mypublickeyfile");
-        brooklynProperties.put("brooklyn.location.byon.privateKeyData", "myprivateKeyData");
-        brooklynProperties.put("brooklyn.location.byon.publicKeyData", "myPublicKeyData");
-        brooklynProperties.put("brooklyn.location.byon.privateKeyPassphrase", "myprivateKeyPassphrase");
-
-        Map<String, Object> conf = resolve("byon(hosts=\"1.1.1.1\")").config().getBag().getAllConfig();
-        
-        assertEquals(conf.get("privateKeyFile"), "myprivatekeyfile");
-        assertEquals(conf.get("publicKeyFile"), "mypublickeyfile");
-        assertEquals(conf.get("privateKeyData"), "myprivateKeyData");
-        assertEquals(conf.get("publicKeyData"), "myPublicKeyData");
-        assertEquals(conf.get("privateKeyPassphrase"), "myprivateKeyPassphrase");
-    }
-
-    @Test
-    public void testNamedByonLocation() throws Exception {
-        brooklynProperties.put("brooklyn.location.named.mynamed", "byon(hosts=\"1.1.1.1\")");
-        
-        FixedListMachineProvisioningLocation<MachineLocation> loc = resolve("named:mynamed");
-        assertEquals(loc.obtain().getAddress(), InetAddress.getByName("1.1.1.1"));
-    }
-
-    @Test
-    public void testPropertiesInSpec() throws Exception {
-        FixedListMachineProvisioningLocation<MachineLocation> loc = resolve("byon(privateKeyFile=myprivatekeyfile,hosts=\"1.1.1.1\")");
-        SshMachineLocation machine = (SshMachineLocation)loc.obtain();
-        
-        assertEquals(machine.config().getBag().getStringKey("privateKeyFile"), "myprivatekeyfile");
-        assertEquals(machine.getAddress(), Networking.getInetAddressWithFixedName("1.1.1.1"));
-    }
-
-    @Test
-    public void testPropertyScopePrecedence() throws Exception {
-        brooklynProperties.put("brooklyn.location.named.mynamed", "byon(hosts=\"1.1.1.1\")");
-        
-        // prefer those in "named" over everything else
-        brooklynProperties.put("brooklyn.location.named.mynamed.privateKeyFile", "privateKeyFile-inNamed");
-        brooklynProperties.put("brooklyn.location.byon.privateKeyFile", "privateKeyFile-inProviderSpecific");
-        brooklynProperties.put("brooklyn.localhost.privateKeyFile", "privateKeyFile-inGeneric");
-
-        // prefer those in provider-specific over generic
-        brooklynProperties.put("brooklyn.location.byon.publicKeyFile", "publicKeyFile-inProviderSpecific");
-        brooklynProperties.put("brooklyn.location.publicKeyFile", "publicKeyFile-inGeneric");
-
-        // prefer location-generic if nothing else
-        brooklynProperties.put("brooklyn.location.privateKeyData", "privateKeyData-inGeneric");
-
-        Map<String, Object> conf = resolve("named:mynamed").config().getBag().getAllConfig();
-        
-        assertEquals(conf.get("privateKeyFile"), "privateKeyFile-inNamed");
-        assertEquals(conf.get("publicKeyFile"), "publicKeyFile-inProviderSpecific");
-        assertEquals(conf.get("privateKeyData"), "privateKeyData-inGeneric");
-    }
-
-    @Test
-    public void testThrowsOnInvalid() throws Exception {
-        assertThrowsNoSuchElement("wrongprefix:(hosts=\"1.1.1.1\")");
-        assertThrowsIllegalArgument("byon"); // no hosts
-        assertThrowsIllegalArgument("byon()"); // no hosts
-        assertThrowsIllegalArgument("byon(hosts=\"\")"); // empty hosts
-        assertThrowsIllegalArgument("byon(hosts=\"1.1.1.1\""); // no closing bracket
-        assertThrowsIllegalArgument("byon(hosts=\"1.1.1.1\", name)"); // no value for name
-        assertThrowsIllegalArgument("byon(hosts=\"1.1.1.1\", name=)"); // no value for name
-    }
-    
-    @Test(expectedExceptions={IllegalArgumentException.class})
-    public void testRegistryCommaResolutionInListNotAllowed() throws NoMachinesAvailableException {
-        // disallowed since 0.7.0
-        // fails because it interprets the entire string as a single byon spec, which does not parse
-        managementContext.getLocationRegistry().resolve(ImmutableList.of("byon(hosts=\"192.168.0.1\",user=bob),byon(hosts=\"192.168.0.2\",user=bob2)"));
-    }
-
-    @Test
-    public void testResolvesHosts() throws Exception {
-        assertByonClusterEquals(resolve("byon(hosts=\"1.1.1.1\")"), ImmutableSet.of("1.1.1.1"));
-        assertByonClusterEquals(resolve("byon(hosts=\"1.1.1.1\")"), ImmutableSet.of("1.1.1.1"));
-        assertByonClusterEquals(resolve("byon(hosts=\"1.1.1.1,1.1.1.2\")"), ImmutableSet.of("1.1.1.1","1.1.1.2"));
-        assertByonClusterEquals(resolve("byon(hosts=\"1.1.1.1, 1.1.1.2\")"), ImmutableSet.of("1.1.1.1","1.1.1.2"));
-    }
-
-    @Test
-    public void testWithOldStyleColon() throws Exception {
-        assertByonClusterEquals(resolve("byon:(hosts=\"1.1.1.1\")"), ImmutableSet.of("1.1.1.1"));
-        assertByonClusterEquals(resolve("byon:(hosts=\"1.1.1.1\", name=myname)"), ImmutableSet.of("1.1.1.1"), "myname");
-    }
-
-    @Test
-    public void testUsesDisplayName() throws Exception {
-        assertByonClusterEquals(resolve("byon(hosts=\"1.1.1.1\", name=myname)"), ImmutableSet.of("1.1.1.1"), "myname");
-        assertByonClusterEquals(resolve("byon(hosts=\"1.1.1.1\", name=\"myname\")"), ImmutableSet.of("1.1.1.1"), "myname");
-    }
-
-    @Test
-    public void testResolvesHostsGlobExpansion() throws Exception {
-        assertByonClusterEquals(resolve("byon(hosts=\"1.1.1.{1,2}\")"), ImmutableSet.of("1.1.1.1","1.1.1.2"));
-        assertByonClusterEquals(resolve("byon(hosts=\"1.1.{1.1,2.{1,2}}\")"), 
-                ImmutableSet.of("1.1.1.1","1.1.2.1","1.1.2.2"));
-        assertByonClusterEquals(resolve("byon(hosts=\"1.1.{1,2}.{1,2}\")"), 
-                ImmutableSet.of("1.1.1.1","1.1.1.2","1.1.2.1","1.1.2.2"));
-    }
-
-    @Test(groups="Integration")
-    public void testNiceError() throws Exception {
-        Asserts.assertFailsWith(new Runnable() {
-            @Override public void run() {
-                FixedListMachineProvisioningLocation<MachineLocation> x =
-                        resolve("byon(hosts=\"1.1.1.{1,2}}\")");
-                log.error("got "+x+" but should have failed (your DNS is giving an IP for hostname '1.1.1.1}' (with the extra '}')");
-            }
-        }, new Predicate<Throwable>() {
-            @Override
-            public boolean apply(@Nullable Throwable input) {
-                String s = input.toString();
-                // words
-                if (!s.contains("Invalid host")) return false;
-                // problematic entry
-                if (!s.contains("1.1.1.1}")) return false;
-                // original spec
-                if (!s.contains("1.1.1.{1,2}}")) return false;
-                return true;
-            }
-        });
-    }
-
-    @Test
-    public void testResolvesUsernameAtHost() throws Exception {
-        assertByonClusterWithUsersEquals(resolve("byon(hosts=\"myuser@1.1.1.1\")"), 
-                ImmutableSet.of(UserAndHostAndPort.fromParts("myuser", "1.1.1.1", 22)));
-        assertByonClusterWithUsersEquals(resolve("byon(hosts=\"myuser@1.1.1.1,myuser2@1.1.1.1\")"), ImmutableSet.of(
-                UserAndHostAndPort.fromParts("myuser", "1.1.1.1", 22), UserAndHostAndPort.fromParts("myuser2", "1.1.1.1", 22)));
-        assertByonClusterWithUsersEquals(resolve("byon(hosts=\"myuser@1.1.1.1,myuser2@1.1.1.2\")"), ImmutableSet.of(
-                UserAndHostAndPort.fromParts("myuser", "1.1.1.1", 22), UserAndHostAndPort.fromParts("myuser2", "1.1.1.2", 22)));
-    }
-
-    @Test
-    public void testResolvesUserArg() throws Exception {
-        assertByonClusterWithUsersEquals(resolve("byon(hosts=\"1.1.1.1\",user=bob)"), 
-                ImmutableSet.of(UserAndHostAndPort.fromParts("bob", "1.1.1.1", 22)));
-        assertByonClusterWithUsersEquals(resolve("byon(user=\"bob\",hosts=\"myuser@1.1.1.1,1.1.1.1\")"), 
-                ImmutableSet.of(UserAndHostAndPort.fromParts("myuser", "1.1.1.1", 22), UserAndHostAndPort.fromParts("bob", "1.1.1.1", 22)));
-    }
-
-    @Test
-    public void testResolvesUserArg2() throws Exception {
-        String spec = "byon(hosts=\"1.1.1.1\",user=bob)";
-        FixedListMachineProvisioningLocation<MachineLocation> ll = resolve(spec);
-        SshMachineLocation l = (SshMachineLocation)ll.obtain();
-        Assert.assertEquals("bob", l.getUser());
-    }
-
-    @SuppressWarnings("unchecked")
-    @Test
-    public void testResolvesUserArg3() throws Exception {
-        String spec = "byon(hosts=\"1.1.1.1\")";
-        managementContext.getLocationRegistry().getProperties().putAll(MutableMap.of(
-                "brooklyn.location.named.foo", spec,
-                "brooklyn.location.named.foo.user", "bob"));
-        ((BasicLocationRegistry)managementContext.getLocationRegistry()).updateDefinedLocations();
-        
-        MachineProvisioningLocation<SshMachineLocation> ll = (MachineProvisioningLocation<SshMachineLocation>)
-                new NamedLocationResolver().newLocationFromString(MutableMap.of(), "named:foo", managementContext.getLocationRegistry());
-        SshMachineLocation l = ll.obtain(MutableMap.of());
-        Assert.assertEquals("bob", l.getUser());
-    }
-
-    @Test
-    public void testResolvesPortArg() throws Exception {
-        assertByonClusterWithUsersEquals(resolve("byon(user=bob,port=8022,hosts=\"1.1.1.1\")"), 
-                ImmutableSet.of(UserAndHostAndPort.fromParts("bob", "1.1.1.1", 8022)));
-        assertByonClusterWithUsersEquals(resolve("byon(user=bob,port=8022,hosts=\"myuser@1.1.1.1,1.1.1.2:8901\")"), 
-                ImmutableSet.of(UserAndHostAndPort.fromParts("myuser", "1.1.1.1", 8022), UserAndHostAndPort.fromParts("bob", "1.1.1.2", 8901)));
-    }
-
-    @SuppressWarnings("unchecked")
-    @Test
-    /** private key should be inherited, so confirm that happens correctly */
-    public void testResolvesPrivateKeyArgInheritance() throws Exception {
-        String spec = "byon(hosts=\"1.1.1.1\")";
-        managementContext.getLocationRegistry().getProperties().putAll(MutableMap.of(
-                "brooklyn.location.named.foo", spec,
-                "brooklyn.location.named.foo.user", "bob",
-                "brooklyn.location.named.foo.privateKeyFile", "/tmp/x"));
-        ((BasicLocationRegistry)managementContext.getLocationRegistry()).updateDefinedLocations();
-        
-        MachineProvisioningLocation<SshMachineLocation> ll = (MachineProvisioningLocation<SshMachineLocation>) 
-                new NamedLocationResolver().newLocationFromString(MutableMap.of(), "named:foo", managementContext.getLocationRegistry());
-        
-        Assert.assertEquals("/tmp/x", ll.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE));
-        Assert.assertTrue(((LocationInternal)ll).config().getLocalRaw(LocationConfigKeys.PRIVATE_KEY_FILE).isPresent());
-        Assert.assertEquals("/tmp/x", ((LocationInternal)ll).config().getLocalBag().getStringKey(LocationConfigKeys.PRIVATE_KEY_FILE.getName()));
-        Assert.assertEquals("/tmp/x", ((LocationInternal)ll).config().getBag().get(LocationConfigKeys.PRIVATE_KEY_FILE));
-
-        SshMachineLocation l = ll.obtain(MutableMap.of());
-        
-        Assert.assertEquals("/tmp/x", l.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE));
-        
-        Assert.assertTrue(l.config().getRaw(LocationConfigKeys.PRIVATE_KEY_FILE).isPresent());
-        Assert.assertTrue(l.config().getLocalRaw(LocationConfigKeys.PRIVATE_KEY_FILE).isAbsent());
-
-        Assert.assertEquals("/tmp/x", l.config().getBag().getStringKey(LocationConfigKeys.PRIVATE_KEY_FILE.getName()));
-        Assert.assertEquals("/tmp/x", l.config().getBag().getStringKey(LocationConfigKeys.PRIVATE_KEY_FILE.getName()));
-
-        Assert.assertEquals("/tmp/x", l.config().getBag().get(LocationConfigKeys.PRIVATE_KEY_FILE));
-    }
-
-    @Test
-    public void testResolvesLocalTempDir() throws Exception {
-        String localTempDir = Os.mergePaths(Os.tmp(), "testResolvesUsernameAtHost");
-        brooklynProperties.put("brooklyn.location.byon.localTempDir", localTempDir);
-
-        FixedListMachineProvisioningLocation<MachineLocation> byon = resolve("byon(hosts=\"1.1.1.1\",osFamily=\"windows\")");
-        MachineLocation machine = byon.obtain();
-        assertEquals(machine.getConfig(SshMachineLocation.LOCAL_TEMP_DIR), localTempDir);
-    }
-
-    @Test
-    public void testMachinesObtainedInOrder() throws Exception {
-        List<String> ips = ImmutableList.of("1.1.1.1", "1.1.1.6", "1.1.1.3", "1.1.1.4", "1.1.1.5");
-        String spec = "byon(hosts=\""+Joiner.on(",").join(ips)+"\")";
-        
-        MachineProvisioningLocation<MachineLocation> ll = resolve(spec);
-
-        for (String expected : ips) {
-            MachineLocation obtained = ll.obtain(ImmutableMap.of());
-            assertEquals(obtained.getAddress().getHostAddress(), expected);
-        }
-    }
-    
-    @Test
-    public void testEmptySpec() throws Exception {
-        String spec = "byon";
-        Map<String, ?> flags = ImmutableMap.of(
-                "hosts", ImmutableList.of("1.1.1.1", "2.2.2.22"),
-                "name", "foo",
-                "user", "myuser"
-        );
-        MachineProvisioningLocation<MachineLocation> provisioner = resolve(spec, flags);
-        SshMachineLocation location1 = (SshMachineLocation)provisioner.obtain(ImmutableMap.of());
-        Assert.assertEquals("myuser", location1.getUser());
-        Assert.assertEquals("1.1.1.1", location1.getAddress().getHostAddress());
-    }
-
-    @Test
-    public void testWindowsMachines() throws Exception {
-        brooklynProperties.put("brooklyn.location.byon.user", "myuser");
-        brooklynProperties.put("brooklyn.location.byon.password", "mypassword");
-        String spec = "byon";
-        Map<String, ?> flags = ImmutableMap.of(
-                "hosts", ImmutableList.of("1.1.1.1", "2.2.2.2"),
-                "osfamily", "windows"
-        );
-        MachineProvisioningLocation<MachineLocation> provisioner = resolve(spec, flags);
-        WinRmMachineLocation location = (WinRmMachineLocation) provisioner.obtain(ImmutableMap.of());
-
-        assertEquals(location.config().get(WinRmMachineLocation.USER), "myuser");
-        assertEquals(location.config().get(WinRmMachineLocation.PASSWORD), "mypassword");
-        assertEquals(location.config().get(WinRmMachineLocation.ADDRESS).getHostAddress(), "1.1.1.1");
-    }
-
-    @Test
-    public void testNoneWindowsMachines() throws Exception {
-        String spec = "byon";
-        Map<String, ?> flags = ImmutableMap.of(
-                "hosts", ImmutableList.of("1.1.1.1", "2.2.2.2"),
-                "osfamily", "linux"
-        );
-        MachineProvisioningLocation<MachineLocation> provisioner = resolve(spec, flags);
-        MachineLocation location = provisioner.obtain(ImmutableMap.of());
-        assertTrue(location instanceof SshMachineLocation, "Expected location to be SshMachineLocation, found " + location);
-    }
-
-    @Test
-    public void testAdditionalConfig() throws Exception {
-        FixedListMachineProvisioningLocation<MachineLocation> loc = resolve("byon(mykey=myval,hosts=\"1.1.1.1\")");
-        MachineLocation machine = loc.obtain(ImmutableMap.of());
-        assertEquals(machine.getConfig(ConfigKeys.newConfigKey(String.class, "mykey")), "myval");
-    }
-
-    private void assertByonClusterEquals(FixedListMachineProvisioningLocation<? extends MachineLocation> cluster, Set<String> expectedHosts) {
-        assertByonClusterEquals(cluster, expectedHosts, defaultNamePredicate);
-    }
-    
-    private void assertByonClusterEquals(FixedListMachineProvisioningLocation<? extends MachineLocation> cluster, Set<String> expectedHosts, String expectedName) {
-        assertByonClusterEquals(cluster, expectedHosts, Predicates.equalTo(expectedName));
-    }
-    
-    private void assertByonClusterEquals(FixedListMachineProvisioningLocation<? extends MachineLocation> cluster, Set<String> expectedHosts, Predicate<? super String> expectedName) {
-        Set<String> actualHosts = ImmutableSet.copyOf(Iterables.transform(cluster.getMachines(), new Function<MachineLocation, String>() {
-            @Override public String apply(MachineLocation input) {
-                return input.getAddress().getHostName();
-            }}));
-        assertEquals(actualHosts, expectedHosts);
-        assertTrue(expectedName.apply(cluster.getDisplayName()), "name="+cluster.getDisplayName());
-    }
-
-    private void assertByonClusterWithUsersEquals(FixedListMachineProvisioningLocation<? extends MachineLocation> cluster, Set<UserAndHostAndPort> expectedHosts) {
-        assertByonClusterWithUsersEquals(cluster, expectedHosts, defaultNamePredicate);
-    }
-    
-    private void assertByonClusterWithUsersEquals(FixedListMachineProvisioningLocation<? extends MachineLocation> cluster, Set<UserAndHostAndPort> expectedHosts, Predicate<? super String> expectedName) {
-        Set<UserAndHostAndPort> actualHosts = ImmutableSet.copyOf(Iterables.transform(cluster.getMachines(), new Function<MachineLocation, UserAndHostAndPort>() {
-            @Override public UserAndHostAndPort apply(MachineLocation input) {
-                SshMachineLocation machine = (SshMachineLocation) input;
-                return UserAndHostAndPort.fromParts(machine.getUser(), machine.getAddress().getHostName(), machine.getPort());
-            }}));
-        assertEquals(actualHosts, expectedHosts);
-        assertTrue(expectedName.apply(cluster.getDisplayName()), "name="+cluster.getDisplayName());
-    }
-
-    private void assertThrowsNoSuchElement(String val) {
-        try {
-            resolve(val);
-            fail();
-        } catch (NoSuchElementException e) {
-            // success
-        }
-    }
-    
-    private void assertThrowsIllegalArgument(String val) {
-        try {
-            resolve(val);
-            fail();
-        } catch (IllegalArgumentException e) {
-            // success
-        }
-    }
-    
-    @SuppressWarnings("unchecked")
-    private FixedListMachineProvisioningLocation<MachineLocation> resolve(String val) {
-        return (FixedListMachineProvisioningLocation<MachineLocation>) managementContext.getLocationRegistry().resolve(val);
-    }
-    
-    @SuppressWarnings("unchecked")
-    private FixedListMachineProvisioningLocation<MachineLocation> resolve(String val, Map<?, ?> locationFlags) {
-        return (FixedListMachineProvisioningLocation<MachineLocation>) managementContext.getLocationRegistry().resolve(val, locationFlags);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/FixedListMachineProvisioningLocationRebindTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/FixedListMachineProvisioningLocationRebindTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/FixedListMachineProvisioningLocationRebindTest.java
deleted file mode 100644
index 6d21014..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/FixedListMachineProvisioningLocationRebindTest.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-
-import java.io.File;
-import java.util.Set;
-
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.util.collections.MutableSet;
-import org.apache.brooklyn.util.os.Os;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Function;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-
-public class FixedListMachineProvisioningLocationRebindTest {
-
-    private FixedListMachineProvisioningLocation<SshMachineLocation> origLoc;
-    private ClassLoader classLoader = getClass().getClassLoader();
-    private ManagementContext origManagementContext;
-    private TestApplication origApp;
-    private TestApplication newApp;
-    private File mementoDir;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        mementoDir = Os.newTempDir(getClass());
-        origManagementContext = RebindTestUtils.newPersistingManagementContext(mementoDir, classLoader, 1);
-        
-        origLoc = new FixedListMachineProvisioningLocation.Builder(origManagementContext.getLocationManager())
-                .addAddresses("localhost", "127.0.0.1")
-                .user("myuser")
-                .keyFile("/path/to/myPrivateKeyFile")
-                .keyData("myKeyData")
-                .keyPassphrase("myKeyPassphrase")
-                .build();
-        origApp = ApplicationBuilder.newManagedApp(TestApplication.class, origManagementContext);
-        origApp.start(ImmutableList.of(origLoc));
-    }
-
-    @AfterMethod(alwaysRun = true)
-    public void tearDown() throws Exception {
-        if (origManagementContext != null) Entities.destroyAll(origManagementContext);
-        if (newApp != null) Entities.destroyAll(newApp.getManagementContext());
-        if (mementoDir != null) RebindTestUtils.deleteMementoDir(mementoDir);
-    }
-    
-    @Test
-    public void testRebindPreservesConfig() throws Exception {
-        newApp = rebind();
-        FixedListMachineProvisioningLocation<SshMachineLocation> newLoc = (FixedListMachineProvisioningLocation<SshMachineLocation>) Iterables.get(newApp.getLocations(), 0);
-        
-        assertEquals(newLoc.getId(), origLoc.getId());
-        assertEquals(newLoc.getDisplayName(), origLoc.getDisplayName());
-        assertEquals(newLoc.getHostGeoInfo(), origLoc.getHostGeoInfo());
-        assertEquals(newLoc.getConfig(LocationConfigKeys.USER), origLoc.getConfig(LocationConfigKeys.USER));
-        assertEquals(newLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_PASSPHRASE), origLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_PASSPHRASE));
-        assertEquals(newLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE), origLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE));
-        assertEquals(newLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_DATA), origLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_DATA));
-    }
-
-    @Test
-    public void testRebindParentRelationship() throws Exception {
-        newApp = rebind();
-        FixedListMachineProvisioningLocation<SshMachineLocation> newLoc = (FixedListMachineProvisioningLocation<SshMachineLocation>) Iterables.get(newApp.getLocations(), 0);
-        
-        assertLocationIdsEqual(newLoc.getChildren(), origLoc.getChildren());
-        assertEquals(Iterables.get(newLoc.getChildren(), 0).getParent(), newLoc);
-        assertEquals(Iterables.get(newLoc.getChildren(), 1).getParent(), newLoc);
-    }
-
-    @Test
-    public void testRebindPreservesInUseMachines() throws Exception {
-        SshMachineLocation inuseMachine = origLoc.obtain();
-        origApp.setAttribute(TestApplication.SERVICE_UP, true); // to force persist, and thus avoid race
-        
-        newApp = rebind();
-        FixedListMachineProvisioningLocation<SshMachineLocation> newLoc = (FixedListMachineProvisioningLocation<SshMachineLocation>) Iterables.get(newApp.getLocations(), 0);
-        
-        assertLocationIdsEqual(newLoc.getInUse(), origLoc.getInUse());
-        assertLocationIdsEqual(newLoc.getAvailable(), origLoc.getAvailable());
-    }
-
-    private TestApplication rebind() throws Exception {
-        RebindTestUtils.waitForPersisted(origApp);
-        return (TestApplication) RebindTestUtils.rebind(mementoDir, getClass().getClassLoader());
-    }
-    
-    private void assertLocationIdsEqual(Iterable<? extends Location> actual, Iterable<? extends Location> expected) {
-        Function<Location, String> locationIdFunction = new Function<Location, String>() {
-            @Override public String apply(@Nullable Location input) {
-                return (input != null) ? input.getId() : null;
-            }
-        };
-        Set<String> actualIds = MutableSet.copyOf(Iterables.transform(actual, locationIdFunction));
-        Set<String> expectedIds = MutableSet.copyOf(Iterables.transform(expected, locationIdFunction));
-        
-        assertEquals(actualIds, expectedIds);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/FixedListMachineProvisioningLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/FixedListMachineProvisioningLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/FixedListMachineProvisioningLocationTest.java
deleted file mode 100644
index dffc759..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/FixedListMachineProvisioningLocationTest.java
+++ /dev/null
@@ -1,574 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.fail;
-
-import java.net.Inet4Address;
-import java.net.UnknownHostException;
-import java.util.List;
-import java.util.Random;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.net.Networking;
-import org.apache.brooklyn.util.stream.Streams;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Function;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
-/**
- * Provisions {@link SshMachineLocation}s in a specific location from a list of known machines
- */
-public class FixedListMachineProvisioningLocationTest {
-    
-    private static final Logger LOG = LoggerFactory.getLogger(FixedListMachineProvisioningLocationTest.class);
-
-    SshMachineLocation machine;
-    LocalManagementContext mgmt;
-    FixedListMachineProvisioningLocation<SshMachineLocation> provisioner;
-    FixedListMachineProvisioningLocation<SshMachineLocation> provisioner2;
-    
-    @SuppressWarnings("unchecked")
-    @BeforeMethod(alwaysRun=true)
-    public void createProvisioner() throws UnknownHostException {
-        mgmt = LocalManagementContextForTests.newInstance();
-        
-        machine = mgmt.getLocationManager().createLocation(MutableMap.of("address", Inet4Address.getByName("192.168.144.200")), SshMachineLocation.class);
-        provisioner = mgmt.getLocationManager().createLocation(
-                MutableMap.of("machines", MutableList.of(machine)),
-                FixedListMachineProvisioningLocation.class);
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (provisioner != null) Streams.closeQuietly(provisioner);
-        if (provisioner2 != null) Streams.closeQuietly(provisioner2);
-        Entities.destroyAll(mgmt);
-    }
-    
-    @Test
-    public void testSetsChildLocations() throws NoMachinesAvailableException {
-        // Available machines should be listed as children
-        assertEquals(ImmutableList.copyOf(provisioner.getChildren()), ImmutableList.of(machine));
-        
-        // In-use machines should also be listed as children
-        provisioner.obtain();
-        assertEquals(ImmutableList.copyOf(provisioner.getChildren()), ImmutableList.of(machine));
-    }
-
-    @Test
-    public void canObtainMachine() throws NoMachinesAvailableException {
-        SshMachineLocation obtained = provisioner.obtain();
-        assertEquals(obtained, machine);
-    }
-
-    @SuppressWarnings("unused")
-    @Test(expectedExceptions = { NoMachinesAvailableException.class })
-    public void throwsExceptionIfNoMachinesAvailable() throws NoMachinesAvailableException {
-        SshMachineLocation machine1 = provisioner.obtain();
-        SshMachineLocation machine2 = provisioner.obtain();
-        fail("Did not throw NoMachinesAvailableException as expected");
-    }
-
-    @Test
-    public void canGetAMachineReturnItAndObtainItAgain() throws NoMachinesAvailableException {
-        SshMachineLocation obtained = provisioner.obtain();
-        provisioner.release(obtained);
-        SshMachineLocation obtained2 = provisioner.obtain();
-        assertEquals(obtained2, machine);
-    }
-
-    @Test
-    public void theBuilder() throws NoMachinesAvailableException {
-        provisioner2 =
-            new FixedListMachineProvisioningLocation.Builder(mgmt.getLocationManager()).
-                user("u1").
-                addAddress("192.168.0.1").
-                addAddress("u2@192.168.0.2").
-                addAddress("192.168.0.{3,4}").
-                addAddresses("192.168.0.{6-8}").
-                addAddressMultipleTimes("192.168.0.{8,7}", 2).
-                addAddress("u3@192.168.0.{11-20}").
-                build();
-        assertUserAndHost(provisioner2.obtain(), "u1", "192.168.0.1");
-        assertUserAndHost(provisioner2.obtain(), "u2", "192.168.0.2");
-        for (int i=3; i<=4; i++) assertUserAndHost(provisioner2.obtain(), "u1", "192.168.0."+i);
-        for (int i=6; i<=8; i++) assertUserAndHost(provisioner2.obtain(), "u1", "192.168.0."+i);
-        for (int j=0; j<2; j++)
-            for (int i=8; i>=7; i--) assertUserAndHost(provisioner2.obtain(), "u1", "192.168.0."+i);
-        for (int i=11; i<=20; i++) assertUserAndHost(provisioner2.obtain(), "u3", "192.168.0."+i);
-        try { 
-            provisioner2.obtain();
-            fail("Should not have obtained");  //throws error so not caught below
-        } catch (Exception e) {
-            /** expected */
-        }
-    }
-    
-    @Test
-    public void theBuilderLegacy() throws NoMachinesAvailableException {
-        provisioner2 =
-            new FixedListMachineProvisioningLocation.Builder(mgmt.getLocationManager()).
-                user("u1").
-                addAddress("192.168.0.1").
-                addAddress("u2@192.168.0.2").
-                addAddress("192.168.0.{3,4}").
-                addAddresses("192.168.0.{6-8}").
-                addAddressMultipleTimes("192.168.0.{8,7}", 2).
-                addAddress("u3@192.168.0.{11-20}").
-                build();
-        assertUserAndHost(provisioner2.obtain(), "u1", "192.168.0.1");
-        assertUserAndHost(provisioner2.obtain(), "u2", "192.168.0.2");
-        for (int i=3; i<=4; i++) assertUserAndHost(provisioner2.obtain(), "u1", "192.168.0."+i);
-        for (int i=6; i<=8; i++) assertUserAndHost(provisioner2.obtain(), "u1", "192.168.0."+i);
-        for (int j=0; j<2; j++)
-            for (int i=8; i>=7; i--) assertUserAndHost(provisioner2.obtain(), "u1", "192.168.0."+i);
-        for (int i=11; i<=20; i++) assertUserAndHost(provisioner2.obtain(), "u3", "192.168.0."+i);
-        try { 
-            provisioner2.obtain();
-            fail("Should not have obtained");  //throws error so not caught below
-        } catch (Exception e) {
-            /** expected */
-        }
-    }
-    
-    @Test(expectedExceptions = { IllegalStateException.class })
-    public void throwsExceptionIfTryingToReleaseUnallocationMachine() throws NoMachinesAvailableException, UnknownHostException {
-        @SuppressWarnings("unused")
-        SshMachineLocation obtained = provisioner.obtain();
-        provisioner.release(new SshMachineLocation(MutableMap.of("address", Inet4Address.getByName("192.168.144.201"))));
-        fail("Did not throw IllegalStateException as expected");
-    }
-    
-    @Test
-    public void testCanAddMachineToPool() throws UnknownHostException, NoMachinesAvailableException {
-        SshMachineLocation machine2 = new SshMachineLocation(
-                MutableMap.of("address", Inet4Address.getByName("192.168.144.200")));
-        provisioner2 = new FixedListMachineProvisioningLocation<SshMachineLocation>(
-                MutableMap.of("machines", MutableList.of()));
-        provisioner2.addMachine(machine2);
-        
-        assertEquals(ImmutableList.copyOf(provisioner2.getChildren()), ImmutableList.of(machine2));
-        assertEquals(ImmutableSet.copyOf(provisioner2.getAvailable()), ImmutableSet.of(machine2));
-        
-        SshMachineLocation obtained = provisioner2.obtain();
-        assertEquals(obtained, machine2);
-        
-        // Can only obtain the added machien once though (i.e. not added multiple times somehow)
-        try {
-            SshMachineLocation obtained2 = provisioner2.obtain();
-            fail("obtained="+obtained2);
-        } catch (NoMachinesAvailableException e) {
-            // success
-        }
-    }
-
-    @Test
-    public void testCanRemoveAvailableMachineFromPool() {
-        provisioner.removeMachine(machine);
-        
-        Assert.assertTrue(provisioner.getChildren().isEmpty());
-        Assert.assertTrue(provisioner.getAvailable().isEmpty());
-        
-        try {
-            SshMachineLocation obtained = provisioner.obtain();
-            fail("obtained="+obtained);
-        } catch (NoMachinesAvailableException e) {
-            // success
-        }
-    }
-
-    @Test
-    public void testCanRemoveObtainedMachineFromPoolSoNotReallocated() throws NoMachinesAvailableException {
-        SshMachineLocation obtained = provisioner.obtain();
-        provisioner.removeMachine(obtained);
-        
-        // Continue to know about the machine until it is returned
-        assertEquals(ImmutableList.copyOf(provisioner.getChildren()), ImmutableList.of(machine));
-        Assert.assertTrue(provisioner.getAvailable().isEmpty());
-
-        // When released, the machine is then removed entirely
-        provisioner.release(obtained);
-
-        Assert.assertTrue(provisioner.getChildren().isEmpty());
-        Assert.assertTrue(provisioner.getAvailable().isEmpty());
-
-        // So no machines left; cannot re-obtain
-        try {
-            SshMachineLocation obtained2 = provisioner.obtain();
-            fail("obtained="+obtained2);
-        } catch (NoMachinesAvailableException e) {
-            // success
-        }
-    }
-
-    @Test
-    public void testObtainDesiredMachineThrowsIfNotKnown() throws Exception {
-        SshMachineLocation machine2 = new SshMachineLocation(
-                MutableMap.of("address", Inet4Address.getByName("192.168.144.201")));
-        try {
-            SshMachineLocation obtained = provisioner.obtain(MutableMap.of("desiredMachine", machine2));
-            fail("obtained="+obtained);
-        } catch (IllegalStateException e) {
-            if (!e.toString().contains("machine unknown")) throw e;
-        }
-    }
-
-    @Test
-    public void testObtainDesiredMachineThrowsIfInUse() throws Exception {
-        provisioner.addMachine(new SshMachineLocation(
-                MutableMap.of("address", Inet4Address.getByName("192.168.144.201"))));
-        SshMachineLocation obtained = provisioner.obtain();
-        try {
-            SshMachineLocation obtained2 = provisioner.obtain(MutableMap.of("desiredMachine", obtained));
-            fail("obtained2="+obtained2);
-        } catch (IllegalStateException e) {
-            if (!e.toString().contains("machine in use")) throw e;
-        }
-    }
-
-    @Test
-    public void testObtainDesiredMachineReturnsDesired() throws Exception {
-        int desiredMachineIndex = 10;
-        SshMachineLocation desiredMachine = null;
-        for (int i = 0; i < 20; i++) {
-            SshMachineLocation newMachine = new SshMachineLocation(
-                    MutableMap.of("address", Inet4Address.getByName("192.168.144."+(201+i))));
-            if (i == desiredMachineIndex) desiredMachine = newMachine;
-            provisioner.addMachine(newMachine);
-        }
-        SshMachineLocation obtained = provisioner.obtain(MutableMap.of("desiredMachine", desiredMachine));
-        assertEquals(obtained, desiredMachine);
-    }
-
-    @Test
-    public void testAddAndRemoveChildUpdatesMachinesSet() throws Exception {
-        SshMachineLocation anotherMachine = new SshMachineLocation(
-                MutableMap.of("address", Inet4Address.getByName("192.168.144.201")));
-        provisioner.addChild(anotherMachine);
-        assertEquals(provisioner.getAllMachines(), ImmutableSet.of(machine, anotherMachine));
-        
-        provisioner.removeChild(anotherMachine);
-        assertEquals(provisioner.getAllMachines(), ImmutableSet.of(machine));
-    }
-    
-    @Test
-    public void testCanAddAlreadyParentedMachine() throws UnknownHostException, NoMachinesAvailableException {
-        provisioner.obtain(); // so no machines left
-        
-        FixedListMachineProvisioningLocation<SshMachineLocation> provisioner2 = new FixedListMachineProvisioningLocation.Builder(mgmt.getLocationManager())
-            .addAddress("1.2.3.4")
-            .build();
-        SshMachineLocation machine = provisioner2.obtain();
-        
-        provisioner.addMachine(machine);
-        assertEquals(provisioner.obtain(), machine);
-    }
-
-    @Test
-    public void testCanCreateWithAlreadyParentedMachine() throws UnknownHostException, NoMachinesAvailableException {
-        machine = provisioner.obtain();
-        
-        FixedListMachineProvisioningLocation<SshMachineLocation> provisioner2 = new FixedListMachineProvisioningLocation.Builder(mgmt.getLocationManager())
-            .add(machine)
-            .build();
-        assertEquals(provisioner2.obtain(), machine);
-    }
-
-    @Test
-    @SuppressWarnings("unchecked")
-    public void testMachinesObtainedInOrder() throws Exception {
-        List<SshMachineLocation> machines = ImmutableList.of(
-                mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.1"))),
-                mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.6"))),
-                mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.3"))),
-                mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.4"))),
-                mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.5"))));
-        
-        provisioner2 = mgmt.getLocationManager().createLocation(
-                MutableMap.of("machines", machines),
-                FixedListMachineProvisioningLocation.class);
-
-        for (SshMachineLocation expected : machines) {
-            assertEquals(provisioner2.obtain(), expected);
-        }
-    }
-    
-    @Test
-    @SuppressWarnings("unchecked")
-    public void testMachineChooser() throws Exception {
-        List<SshMachineLocation> machines = Lists.newArrayList();
-        for (int i = 0; i < 10; i++) {
-            machines.add(mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1."+i))));
-        }
-        final List<SshMachineLocation> desiredOrder = randomized(machines);
-        
-        Function<Iterable<? extends MachineLocation>, MachineLocation> chooser = new Function<Iterable<? extends MachineLocation>, MachineLocation>() {
-            @Override public MachineLocation apply(Iterable<? extends MachineLocation> input) {
-                for (SshMachineLocation contender : desiredOrder) {
-                    if (Iterables.contains(input, contender)) {
-                        return contender;
-                    }
-                }
-                Assert.fail("No intersection of input="+input+" and desiredOrder="+desiredOrder);
-                return null; // unreachable code
-            }
-        };
-        provisioner2 = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
-                .configure("machines", machines)
-                .configure(FixedListMachineProvisioningLocation.MACHINE_CHOOSER, chooser));
-
-        List<SshMachineLocation> result = Lists.newArrayList();
-        for (int i = 0; i < machines.size(); i++) {
-            result.add(provisioner2.obtain());
-        }
-        assertEquals(result, desiredOrder, "result="+result+"; desired="+desiredOrder);
-        LOG.debug("chooser's desiredOrder="+desiredOrder);
-    }
-    
-    @Test
-    @SuppressWarnings("unchecked")
-    public void testMachineChooserPassedToObtain() throws Exception {
-        List<SshMachineLocation> machines = Lists.newArrayList();
-        for (int i = 0; i < 10; i++) {
-            machines.add(mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1."+i))));
-        }
-        final List<SshMachineLocation> desiredOrder = randomized(machines);
-        
-        Function<Iterable<? extends MachineLocation>, MachineLocation> chooser = new Function<Iterable<? extends MachineLocation>, MachineLocation>() {
-            @Override public MachineLocation apply(Iterable<? extends MachineLocation> input) {
-                for (SshMachineLocation contender : desiredOrder) {
-                    if (Iterables.contains(input, contender)) {
-                        return contender;
-                    }
-                }
-                Assert.fail("No intersection of input="+input+" and desiredOrder="+desiredOrder);
-                return null; // unreachable code
-            }
-        };
-        provisioner2 = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
-                .configure("machines", machines));
-
-        List<SshMachineLocation> result = Lists.newArrayList();
-        for (int i = 0; i < machines.size(); i++) {
-            result.add(provisioner2.obtain(ImmutableMap.of(FixedListMachineProvisioningLocation.MACHINE_CHOOSER, chooser)));
-        }
-        assertEquals(result, desiredOrder, "result="+result+"; desired="+desiredOrder);
-        LOG.debug("chooser's desiredOrder="+desiredOrder);
-    }
-    
-    @Test
-    @SuppressWarnings("unchecked")
-    public void testMachineChooserNotCalledWhenNoMachines() throws Exception {
-        List<SshMachineLocation> machines = ImmutableList.of(
-                mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.1"))));
-        final AtomicInteger callCount = new AtomicInteger();
-        
-        Function<Iterable<? extends MachineLocation>, MachineLocation> chooser = new Function<Iterable<? extends MachineLocation>, MachineLocation>() {
-            @Override public MachineLocation apply(Iterable<? extends MachineLocation> input) {
-                callCount.incrementAndGet();
-                return Iterables.get(input, 0);
-            }
-        };
-        provisioner2 = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
-                .configure("machines", machines)
-                .configure(FixedListMachineProvisioningLocation.MACHINE_CHOOSER, chooser));
-        provisioner2.obtain();
-
-        // When no machines available should fail gracefully, without asking the "chooser"
-        try {
-            provisioner2.obtain();
-            fail("Expected "+NoMachinesAvailableException.class.getSimpleName());
-        } catch (NoMachinesAvailableException e) {
-            // Pass; sensible exception
-        }
-        assertEquals(callCount.get(), 1);
-    }
-    
-    @Test
-    @SuppressWarnings("unchecked")
-    public void testFailsWhenMachineChooserReturnsAlreadyAllocatedMachine() throws Exception {
-        final SshMachineLocation machine1 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.1")));
-        final SshMachineLocation machine2 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.2")));
-        List<SshMachineLocation> machines = ImmutableList.of(machine1, machine2);
-        
-        Function<Iterable<? extends MachineLocation>, MachineLocation> chooser = new Function<Iterable<? extends MachineLocation>, MachineLocation>() {
-            @Override public MachineLocation apply(Iterable<? extends MachineLocation> input) {
-                return machine1;
-            }
-        };
-        provisioner2 = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
-                .configure("machines", machines)
-                .configure(FixedListMachineProvisioningLocation.MACHINE_CHOOSER, chooser));
-        provisioner2.obtain();
-
-        // Should fail when tries to return same machine for a second time
-        try {
-            provisioner2.obtain();
-            fail("Expected "+IllegalStateException.class.getSimpleName());
-        } catch (IllegalStateException e) {
-            if (!e.toString().contains("Machine chooser attempted to choose ")) throw e;
-        }
-    }
-
-    @Test
-    @SuppressWarnings("unchecked")
-    public void testFailsWhenMachineChooserReturnsInvalidMachine() throws Exception {
-        final SshMachineLocation machine1 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.1")));
-        final SshMachineLocation machineOther = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("2.2.2.1")));
-        List<SshMachineLocation> machines = ImmutableList.of(machine1);
-        
-        Function<Iterable<? extends MachineLocation>, MachineLocation> chooser = new Function<Iterable<? extends MachineLocation>, MachineLocation>() {
-            @Override public MachineLocation apply(Iterable<? extends MachineLocation> input) {
-                return machineOther;
-            }
-        };
-        provisioner2 = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
-                .configure("machines", machines)
-                .configure(FixedListMachineProvisioningLocation.MACHINE_CHOOSER, chooser));
-
-        // Call when no machines available should fail gracefully, without asking the "chooser"
-        try {
-            provisioner2.obtain();
-            fail("Expected "+IllegalStateException.class.getSimpleName());
-        } catch (IllegalStateException e) {
-            if (!e.toString().contains("Machine chooser attempted to choose ")) throw e;
-        }
-    }
-
-    @Test
-    @SuppressWarnings("unchecked")
-    public void testMachineCustomizerSetOnByon() throws Exception {
-        machine = mgmt.getLocationManager().createLocation(MutableMap.of("address", Inet4Address.getByName("192.168.144.200")), SshMachineLocation.class);
-        RecordingMachineLocationCustomizer customizer = new RecordingMachineLocationCustomizer();
-        
-        provisioner2 = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
-                .configure("machines", ImmutableList.of(machine))
-                .configure(FixedListMachineProvisioningLocation.MACHINE_LOCATION_CUSTOMIZERS.getName(), ImmutableList.of(customizer)));
-                
-        SshMachineLocation obtained = provisioner2.obtain();
-        Assert.assertEquals(Iterables.getOnlyElement(customizer.calls), new RecordingMachineLocationCustomizer.Call("customize", ImmutableList.of(obtained)));
-        
-        provisioner2.release(obtained);
-        assertEquals(customizer.calls.size(), 2);
-        Assert.assertEquals(Iterables.get(customizer.calls, 1), new RecordingMachineLocationCustomizer.Call("preRelease", ImmutableList.of(obtained)));
-    }
-
-    @Test
-    public void testMachineCustomizerSetOnObtainCall() throws Exception {
-        RecordingMachineLocationCustomizer customizer = new RecordingMachineLocationCustomizer();
-        
-        SshMachineLocation obtained = provisioner.obtain(ImmutableMap.of(FixedListMachineProvisioningLocation.MACHINE_LOCATION_CUSTOMIZERS, ImmutableList.of(customizer)));
-        Assert.assertEquals(Iterables.getOnlyElement(customizer.calls), new RecordingMachineLocationCustomizer.Call("customize", ImmutableList.of(obtained)));
-        
-        provisioner.release(obtained);
-        assertEquals(customizer.calls.size(), 2);
-        Assert.assertEquals(customizer.calls.get(1), new RecordingMachineLocationCustomizer.Call("preRelease", ImmutableList.of(obtained)));
-    }
-
-    @Test
-    public void testMachineGivenCustomFlagForDurationOfUsage() throws Exception {
-        boolean origContains = machine.config().getBag().getAllConfig().containsKey("mykey");
-        SshMachineLocation obtained = provisioner.obtain(ImmutableMap.of("mykey", "myNewVal"));
-        Object obtainedVal = obtained.config().getBag().getAllConfig().get("mykey");
-        provisioner.release(obtained);
-        boolean releasedContains = obtained.config().getBag().getAllConfig().containsKey("mykey");
-        
-        assertEquals(obtained, machine);
-        assertFalse(origContains);
-        assertEquals(obtainedVal, "myNewVal");
-        assertFalse(releasedContains);
-    }
-    
-    @Test
-    public void testMachineConfigRestoredToDefaultsOnRelease() throws Exception {
-        ConfigKey<String> mykey = ConfigKeys.newStringConfigKey("mykey");
-        
-        boolean origContains = machine.config().getBag().getAllConfig().containsKey("mykey");
-        SshMachineLocation obtained = provisioner.obtain();
-        obtained.config().set(mykey, "myNewVal");
-        Object obtainedVal = obtained.config().getBag().getAllConfig().get("mykey");
-        
-        provisioner.release(obtained);
-        boolean releasedContains = machine.config().getBag().getAllConfig().containsKey("mykey");
-        releasedContains |= (machine.config().get(mykey) != null);
-        
-        assertEquals(obtained, machine);
-        assertFalse(origContains);
-        assertEquals(obtainedVal, "myNewVal");
-        assertFalse(releasedContains);
-    }
-    
-    @Test
-    public void testMachineGivenOverriddenFlagForDurationOfUsage() throws Exception {
-        SshMachineLocation machine2 = new SshMachineLocation(
-                MutableMap.of("address", Inet4Address.getByName("192.168.144.200"), "mykey", "myval"));
-        provisioner2 = new FixedListMachineProvisioningLocation<SshMachineLocation>(
-                MutableMap.of("machines", MutableList.of(machine2)));
-
-        Object origVal = machine2.config().getBag().getAllConfig().get("mykey");
-        SshMachineLocation obtained = provisioner2.obtain(ImmutableMap.of("mykey", "myNewVal"));
-        Object obtainedVal = obtained.config().getBag().getAllConfig().get("mykey");
-        provisioner2.release(obtained);
-        Object releasedVal = obtained.config().getBag().getAllConfig().get("mykey");
-        
-        assertEquals(obtained, machine2);
-        assertEquals(origVal, "myval");
-        assertEquals(obtainedVal, "myNewVal");
-        assertEquals(releasedVal, "myval");
-    }
-
-    private static <T> List<T> randomized(Iterable<T> list) {
-        // TODO inefficient implementation, but don't care for small tests
-        Random random = new Random();
-        List<T> result = Lists.newLinkedList();
-        for (T element : list) {
-            int index = (result.isEmpty() ? 0 : random.nextInt(result.size()));
-            result.add(index, element);
-        }
-        return result;
-    }
-    
-    private static void assertUserAndHost(SshMachineLocation l, String user, String host) {
-        assertEquals(l.getUser(), user);
-        assertEquals(l.getAddress().getHostAddress(), host);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/HostLocationResolverTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/HostLocationResolverTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/HostLocationResolverTest.java
deleted file mode 100644
index 92d4d63..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/HostLocationResolverTest.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.fail;
-
-import java.net.InetAddress;
-import java.util.Map;
-import java.util.NoSuchElementException;
-
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableMap;
-
-public class HostLocationResolverTest {
-    
-    private BrooklynProperties brooklynProperties;
-    private LocalManagementContext managementContext;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        managementContext = LocalManagementContextForTests.newInstance();
-        brooklynProperties = managementContext.getBrooklynProperties();
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (managementContext != null) Entities.destroyAll(managementContext);
-    }
-    
-    @Test
-    public void testThrowsOnInvalid() throws Exception {
-        assertThrowsNoSuchElement("wrongprefix:(hosts=\"1.1.1.1\")");
-        assertThrowsIllegalArgument("host");
-    }
-    
-    @Test
-    public void testThrowsOnInvalidTarget() throws Exception {
-        assertThrowsIllegalArgument("host:()");
-    }
-    
-    @Test
-    public void resolveHosts() {
-        resolve("host:(\"1.1.1.1\")");
-        resolve("host:(\"localhost\")");
-    }
-    
-    @Test(groups="Integration")
-    public void resolveRealHosts() {
-        // must be online to resolve this
-        resolve("host:(\"www.foo.com\")");
-    }
-    
-    @Test
-    public void testNamedByonLocation() throws Exception {
-        brooklynProperties.put("brooklyn.location.named.mynamed", "host:(\"1.1.1.1\")");
-        
-        MachineProvisioningLocation<SshMachineLocation> loc = resolve("named:mynamed");
-        assertEquals(loc.obtain(ImmutableMap.of()).getAddress(), InetAddress.getByName("1.1.1.1"));
-    }
-
-    @Test
-    public void testPropertyScopePrescedence() throws Exception {
-        brooklynProperties.put("brooklyn.location.named.mynamed", "host:(\"1.1.1.1\")");
-        
-        // prefer those in "named" over everything else
-        brooklynProperties.put("brooklyn.location.named.mynamed.privateKeyFile", "privateKeyFile-inNamed");
-        brooklynProperties.put("brooklyn.localhost.privateKeyFile", "privateKeyFile-inGeneric");
-
-        // prefer location-generic if nothing else
-        brooklynProperties.put("brooklyn.location.privateKeyData", "privateKeyData-inGeneric");
-
-        Map<String, Object> conf = resolve("named:mynamed").obtain(ImmutableMap.of()).config().getBag().getAllConfig();
-        
-        assertEquals(conf.get("privateKeyFile"), "privateKeyFile-inNamed");
-        assertEquals(conf.get("privateKeyData"), "privateKeyData-inGeneric");
-    }
-
-    private void assertThrowsNoSuchElement(String val) {
-        try {
-            resolve(val);
-            fail();
-        } catch (NoSuchElementException e) {
-            // success
-        }
-    }
-    
-    private void assertThrowsIllegalArgument(String val) {
-        try {
-            resolve(val);
-            fail();
-        } catch (IllegalArgumentException e) {
-            // success
-        }
-    }
-    
-    @SuppressWarnings("unchecked")
-    private MachineProvisioningLocation<SshMachineLocation> resolve(String val) {
-        return (MachineProvisioningLocation<SshMachineLocation>) managementContext.getLocationRegistry().resolve(val);
-    }
-}


[15/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/brooklynnode/SelectMasterEffectorTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/brooklynnode/SelectMasterEffectorTest.java b/software/base/src/test/java/brooklyn/entity/brooklynnode/SelectMasterEffectorTest.java
deleted file mode 100644
index efef932..0000000
--- a/software/base/src/test/java/brooklyn/entity/brooklynnode/SelectMasterEffectorTest.java
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.Callable;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.entity.Group;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.group.DynamicCluster;
-import org.apache.brooklyn.sensor.feed.AttributePollHandler;
-import org.apache.brooklyn.sensor.feed.DelegatingPollHandler;
-import org.apache.brooklyn.sensor.feed.Poller;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.http.client.methods.HttpPost;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.brooklynnode.BrooklynCluster.SelectMasterEffector;
-import brooklyn.entity.brooklynnode.CallbackEntityHttpClient.Request;
-
-import com.google.common.base.Function;
-import com.google.common.base.Objects;
-import com.google.common.collect.ImmutableMap;
-
-public class SelectMasterEffectorTest extends BrooklynAppUnitTestSupport {
-    private static final Logger LOG = LoggerFactory.getLogger(BrooklynClusterImpl.class);
-
-    protected BrooklynCluster cluster;
-    protected HttpCallback http; 
-    protected Poller<Void> poller;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        super.setUp();
-
-        // because the effector calls wait for a state change, use a separate thread to drive that 
-        poller = new Poller<Void>((EntityLocal)app, false);
-        poller.scheduleAtFixedRate(
-            new Callable<Void>() {
-                @Override
-                public Void call() throws Exception {
-                    masterFailoverIfNeeded();
-                    return null;
-                }
-            },
-            new DelegatingPollHandler<Void>(Collections.<AttributePollHandler<? super Void>>emptyList()),
-            Duration.millis(20));
-        poller.start();
-    }
-
-    @Override
-    protected void setUpApp() {
-        super.setUpApp();
-        http = new HttpCallback();
-        cluster = app.createAndManageChild(EntitySpec.create(BrooklynCluster.class)
-            .location(app.newLocalhostProvisioningLocation())
-            .configure(BrooklynCluster.MEMBER_SPEC, EntitySpec.create(BrooklynNode.class)
-                .impl(MockBrooklynNode.class)
-                .configure(MockBrooklynNode.HTTP_CLIENT_CALLBACK, http)));
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        poller.stop();
-        super.tearDown();
-    }
-
-    @Test
-    public void testInvalidNewMasterIdFails() {
-        try {
-            selectMaster(cluster, "1234");
-            fail("Non-existend entity ID provided.");
-        } catch (Exception e) {
-            assertTrue(e.toString().contains("1234 is not an ID of brooklyn node in this cluster"));
-        }
-    }
-
-    @Test(groups="Integration") // because slow, due to sensor feeds
-    public void testSelectMasterAfterChange() {
-        List<Entity> nodes = makeTwoNodes();
-        EntityTestUtils.assertAttributeEqualsEventually(cluster, BrooklynCluster.MASTER_NODE, (BrooklynNode)nodes.get(0));
-
-        selectMaster(cluster, nodes.get(1).getId());
-        checkMaster(cluster, nodes.get(1));
-    }
-
-    @Test
-    public void testFindMaster() {
-        List<Entity> nodes = makeTwoNodes();
-        Assert.assertEquals(((BrooklynClusterImpl)Entities.deproxy(cluster)).findMasterChild(), nodes.get(0));
-    }
-    
-    @Test(groups="Integration") // because slow, due to sensor feeds
-    public void testSelectMasterFailsAtChangeState() {
-        http.setFailAtStateChange(true);
-
-        List<Entity> nodes = makeTwoNodes();
-        
-        EntityTestUtils.assertAttributeEqualsEventually(cluster, BrooklynCluster.MASTER_NODE, (BrooklynNode)nodes.get(0));
-
-        try {
-            selectMaster(cluster, nodes.get(1).getId());
-            fail("selectMaster should have failed");
-        } catch (Exception e) {
-            // expected
-        }
-        checkMaster(cluster, nodes.get(0));
-    }
-
-    private List<Entity> makeTwoNodes() {
-        List<Entity> nodes = MutableList.copyOf(cluster.resizeByDelta(2));
-        setManagementState(nodes.get(0), ManagementNodeState.MASTER);
-        setManagementState(nodes.get(1), ManagementNodeState.HOT_STANDBY);
-        return nodes;
-    }
-
-    private void checkMaster(Group cluster, Entity node) {
-        assertEquals(node.getAttribute(BrooklynNode.MANAGEMENT_NODE_STATE), ManagementNodeState.MASTER);
-        assertEquals(cluster.getAttribute(BrooklynCluster.MASTER_NODE), node);
-        for (Entity member : cluster.getMembers()) {
-            if (member != node) {
-                assertEquals(member.getAttribute(BrooklynNode.MANAGEMENT_NODE_STATE), ManagementNodeState.HOT_STANDBY);
-            }
-            assertEquals((int)member.getAttribute(MockBrooklynNode.HA_PRIORITY), 0);
-        }
-    }
-
-    private static class HttpCallback implements Function<CallbackEntityHttpClient.Request, String> {
-        private enum State {
-            INITIAL,
-            PROMOTED
-        }
-        private State state = State.INITIAL;
-        private boolean failAtStateChange;
-
-        @Override
-        public String apply(Request input) {
-            if ("/v1/server/ha/state".equals(input.getPath())) {
-                if (failAtStateChange) {
-                    throw new RuntimeException("Testing failure at changing node state");
-                }
-
-                checkRequest(input, HttpPost.METHOD_NAME, "/v1/server/ha/state", "mode", "HOT_STANDBY");
-                Entity entity = input.getEntity();
-                EntityTestUtils.assertAttributeEquals(entity, BrooklynNode.MANAGEMENT_NODE_STATE, ManagementNodeState.MASTER);
-                EntityTestUtils.assertAttributeEquals(entity, MockBrooklynNode.HA_PRIORITY, 0);
-
-                setManagementState(entity, ManagementNodeState.HOT_STANDBY);
-
-                return "MASTER";
-            } else {
-                switch(state) {
-                case INITIAL:
-                    checkRequest(input, HttpPost.METHOD_NAME, "/v1/server/ha/priority", "priority", "1");
-                    state = State.PROMOTED;
-                    setPriority(input.getEntity(), Integer.parseInt(input.getParams().get("priority")));
-                    return "0";
-                case PROMOTED:
-                    checkRequest(input, HttpPost.METHOD_NAME, "/v1/server/ha/priority", "priority", "0");
-                    state = State.INITIAL;
-                    setPriority(input.getEntity(), Integer.parseInt(input.getParams().get("priority")));
-                    return "1";
-                default: throw new IllegalStateException("Illegal call at state " + state + ". Request = " + input.getMethod() + " " + input.getPath());
-                }
-            }
-        }
-
-        public void checkRequest(Request input, String methodName, String path, String key, String value) {
-            if (!input.getMethod().equals(methodName) || !input.getPath().equals(path)) {
-                throw new IllegalStateException("Request doesn't match expected state. Expected = " + input.getMethod() + " " + input.getPath() + ". " +
-                        "Actual = " + methodName + " " + path);
-            }
-
-            String inputValue = input.getParams().get(key);
-            if(!Objects.equal(value, inputValue)) {
-                throw new IllegalStateException("Request doesn't match expected parameter " + methodName + " " + path + ". Parameter " + key + 
-                    " expected = " + value + ", actual = " + inputValue);
-            }
-        }
-
-        public void setFailAtStateChange(boolean failAtStateChange) {
-            this.failAtStateChange = failAtStateChange;
-        }
-
-    }
-
-    private void masterFailoverIfNeeded() {
-        if (!Entities.isManaged(cluster)) return;
-        if (cluster.getAttribute(BrooklynCluster.MASTER_NODE) == null) {
-            Collection<Entity> members = cluster.getMembers();
-            if (members.size() > 0) {
-                for (Entity member : members) {
-                    if (member.getAttribute(MockBrooklynNode.HA_PRIORITY) == 1) {
-                        masterFailover(member);
-                        return;
-                    }
-                }
-                masterFailover(members.iterator().next());
-            }
-        }
-    }
-
-    private void masterFailover(Entity member) {
-        LOG.debug("Master failover to " + member);
-        setManagementState(member, ManagementNodeState.MASTER);
-        EntityTestUtils.assertAttributeEqualsEventually(cluster, BrooklynCluster.MASTER_NODE, (BrooklynNode)member);
-        return;
-    }
-
-    public static void setManagementState(Entity entity, ManagementNodeState state) {
-        ((EntityLocal)entity).setAttribute(BrooklynNode.MANAGEMENT_NODE_STATE, state);
-    }
-
-    public static void setPriority(Entity entity, int priority) {
-        ((EntityLocal)entity).setAttribute(MockBrooklynNode.HA_PRIORITY, priority);
-    }
-
-    private void selectMaster(DynamicCluster cluster, String id) {
-        app.getExecutionContext().submit(Effectors.invocation(cluster, BrooklynCluster.SELECT_MASTER, ImmutableMap.of(SelectMasterEffector.NEW_MASTER_ID.getName(), id))).asTask().getUnchecked();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/chef/ChefConfigsTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/chef/ChefConfigsTest.java b/software/base/src/test/java/brooklyn/entity/chef/ChefConfigsTest.java
deleted file mode 100644
index f2e25ad..0000000
--- a/software/base/src/test/java/brooklyn/entity/chef/ChefConfigsTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-import java.util.Set;
-
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.Test;
-
-public class ChefConfigsTest {
-
-    private TestApplication app = null;
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() {
-        if (app!=null) Entities.destroyAll(app.getManagementContext());
-        app = null;
-    }
-    
-    @Test
-    public void testAddToRunList() {
-        app = ApplicationBuilder.newManagedApp(TestApplication.class);
-        ChefConfigs.addToLaunchRunList(app, "a", "b");
-        Set<? extends String> runs = app.getConfig(ChefConfig.CHEF_LAUNCH_RUN_LIST);
-        Assert.assertEquals(runs.size(), 2, "runs="+runs);
-        Assert.assertTrue(runs.contains("a"));
-        Assert.assertTrue(runs.contains("b"));
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/chef/ChefLiveTestSupport.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/chef/ChefLiveTestSupport.java b/software/base/src/test/java/brooklyn/entity/chef/ChefLiveTestSupport.java
deleted file mode 100644
index 038657b..0000000
--- a/software/base/src/test/java/brooklyn/entity/chef/ChefLiveTestSupport.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-import java.io.File;
-import java.io.IOException;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.BeforeMethod;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.util.core.ResourceUtils;
-import org.apache.brooklyn.util.io.FileUtil;
-import org.apache.brooklyn.util.stream.InputStreamSupplier;
-
-import com.google.common.base.Throwables;
-import com.google.common.io.Files;
-
-public class ChefLiveTestSupport extends BrooklynAppLiveTestSupport {
-
-    private static final Logger log = LoggerFactory.getLogger(ChefLiveTestSupport.class);
-    
-    protected MachineProvisioningLocation<? extends SshMachineLocation> targetLocation;
-
-    @BeforeMethod(alwaysRun=true)
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-        
-        targetLocation = createLocation();
-    }
-
-    protected MachineProvisioningLocation<? extends SshMachineLocation> createLocation() {
-        return createLocation(mgmt);
-    }
-    
-    /** convenience for setting up a pre-built / fixed IP machine
-     * (because you might not want to set up Chef on localhost) 
-     * and ensuring tests against Chef use the same configured location 
-     **/
-    @SuppressWarnings("unchecked")
-    public static MachineProvisioningLocation<? extends SshMachineLocation> createLocation(ManagementContext mgmt) {
-        Location bestLocation = mgmt.getLocationRegistry().resolve("named:ChefTests", true, null).orNull();
-        if (bestLocation==null) {
-            log.info("using AWS for chef tests because named:ChefTests does not exist");
-            bestLocation = mgmt.getLocationRegistry().resolve("jclouds:aws-ec2:us-east-1");
-        }
-        if (bestLocation==null) {
-            throw new IllegalStateException("Need a location called named:ChefTests or AWS configured for these tests");
-        }
-        return (MachineProvisioningLocation<? extends SshMachineLocation>)bestLocation; 
-    }
-    
-    private static String defaultConfigFile = null; 
-    public synchronized static String installBrooklynChefHostedConfig() {
-        if (defaultConfigFile!=null) return defaultConfigFile;
-        File tempDir = Files.createTempDir();
-        ResourceUtils r = ResourceUtils.create(ChefServerTasksIntegrationTest.class);
-        try {
-            for (String f: new String[] { "knife.rb", "brooklyn-tests.pem", "brooklyn-validator.pem" }) {
-                String contents = r.getResourceAsString("classpath:///brooklyn/entity/chef/hosted-chef-brooklyn-credentials/"+f);
-                FileUtil.copyTo(InputStreamSupplier.fromString(contents).getInput(), new File(tempDir, f));
-            }
-        } catch (IOException e) {
-            throw Throwables.propagate(e);
-        }
-        File knifeConfig = new File(tempDir, "knife.rb");
-        defaultConfigFile = knifeConfig.getPath();
-        return defaultConfigFile;
-    }
-
-    public static void installBrooklynChefHostedConfig(Entity entity) {
-        ((EntityInternal)entity).setConfig(ChefConfig.KNIFE_CONFIG_FILE, ChefLiveTestSupport.installBrooklynChefHostedConfig());
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/chef/ChefServerTasksIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/chef/ChefServerTasksIntegrationTest.java b/software/base/src/test/java/brooklyn/entity/chef/ChefServerTasksIntegrationTest.java
deleted file mode 100644
index 1df48e5..0000000
--- a/software/base/src/test/java/brooklyn/entity/chef/ChefServerTasksIntegrationTest.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.apache.brooklyn.util.stream.StreamGobbler;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-/** Many tests expect knife on the path, but none require any configuration beyond that.
- * They will use the Brooklyn registered account (which has been set up with mysql cookbooks and more).
- * <p>
- * Note this is a free account so cannot manage many nodes. 
- * You can use the credentials in src/test/resources/hosted-chef-brooklyn-credentials/
- * to log in and configure the settings for our tests using knife. You can also log in at:
- * <p>
- * https://manage.opscode.com/
- * <p>
- * with credentials for those with need to know (which is a lot of people, but not everyone
- * with access to this github repo!).
- * <p>
- * You can easily set up your own new account, for free; download the starter kit and
- * point {@link ChefConfig#KNIFE_CONFIG_FILE} at the knife.rb.
- * <p>
- * Note that if you are porting an existing machine to be managed by a new chef account, you may need to do the following:
- * <p>
- * ON management machine:
- * <li>knife client delete HOST   # or bulk delete, but don't delete your validator! it is a PITA recreating and adding back all the permissions! 
- * <li>knife node delete HOST
- * <p>
- * ON machine being managed:
- * <li>rm -rf /{etc,var}/chef
- * <p>
- * Note also that some tests require a location  named:ChefLive  to be set up in your brooklyn.properties.
- * This can be a cloud (but will require frequent chef-node pruning) or a permanently set-up machine.
- **/
-public class ChefServerTasksIntegrationTest {
-
-    private static final Logger log = LoggerFactory.getLogger(ChefServerTasksIntegrationTest.class);
-    
-    protected TestApplication app;
-    protected ManagementContext mgmt;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setup() throws Exception {
-        app = ApplicationBuilder.newManagedApp(TestApplication.class);
-        mgmt = app.getManagementContext();
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (mgmt != null) Entities.destroyAll(mgmt);
-        mgmt = null;
-    }
-
-    /** @deprecated use {@link ChefLiveTestSupport} */
-    @Deprecated
-    public synchronized static String installBrooklynChefHostedConfig() {
-        return ChefLiveTestSupport.installBrooklynChefHostedConfig();
-    }
-    
-    @Test(groups="Integration")
-    @SuppressWarnings("resource")
-    public void testWhichKnife() throws IOException, InterruptedException {
-        // requires that knife is installed on the path of login shells
-        Process p = Runtime.getRuntime().exec(new String[] { "bash", "-l", "-c", "which knife" });
-        ByteArrayOutputStream out = new ByteArrayOutputStream();
-        new StreamGobbler(p.getInputStream(), out, log).start();
-        new StreamGobbler(p.getErrorStream(), out, log).start();
-        log.info("bash -l -c 'which knife' gives exit code: "+p.waitFor());
-        Time.sleep(Duration.millis(1000));
-        log.info("output:\n"+out);
-        Assert.assertEquals(p.exitValue(), 0);
-    }
-
-    @Test(groups="Integration")
-    public void testKnifeWithoutConfig() {
-        // without config it shouldn't pass
-        // (assumes that knife global config is *not* installed on your machine)
-        ProcessTaskWrapper<Boolean> t = Entities.submit(app, ChefServerTasks.isKnifeInstalled());
-        log.info("isKnifeInstalled without config returned: "+t.get()+" ("+t.getExitCode()+")\n"+t.getStdout()+"\nERR:\n"+t.getStderr());
-        Assert.assertFalse(t.get());
-    }
-
-    @Test(groups="Integration")
-    public void testKnifeWithConfig() {
-        // requires that knife is installed on the path of login shells
-        // (creates the config in a temp space)
-        ChefLiveTestSupport.installBrooklynChefHostedConfig(app);
-        ProcessTaskWrapper<Boolean> t = Entities.submit(app, ChefServerTasks.isKnifeInstalled());
-        log.info("isKnifeInstalled *with* config returned: "+t.get()+" ("+t.getExitCode()+")\n"+t.getStdout()+"\nERR:\n"+t.getStderr());
-        Assert.assertTrue(t.get());
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/chef/mysql/AbstractChefToyMySqlEntityLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/chef/mysql/AbstractChefToyMySqlEntityLiveTest.java b/software/base/src/test/java/brooklyn/entity/chef/mysql/AbstractChefToyMySqlEntityLiveTest.java
deleted file mode 100644
index 92bb587..0000000
--- a/software/base/src/test/java/brooklyn/entity/chef/mysql/AbstractChefToyMySqlEntityLiveTest.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef.mysql;
-
-import org.testng.annotations.Test;
-
-import brooklyn.entity.chef.ChefLiveTestSupport;
-import brooklyn.entity.software.mysql.AbstractToyMySqlEntityTest;
-
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-public abstract class AbstractChefToyMySqlEntityLiveTest extends AbstractToyMySqlEntityTest {
-
-    @Override
-    // mark as live here
-    @Test(groups = "Live")
-    public void testMySqlOnProvisioningLocation() throws Exception {
-        super.testMySqlOnProvisioningLocation();
-    }
-    
-    protected MachineProvisioningLocation<? extends SshMachineLocation> createLocation() {
-        return ChefLiveTestSupport.createLocation(mgmt);
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/chef/mysql/ChefSoloDriverMySqlEntityLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/chef/mysql/ChefSoloDriverMySqlEntityLiveTest.java b/software/base/src/test/java/brooklyn/entity/chef/mysql/ChefSoloDriverMySqlEntityLiveTest.java
deleted file mode 100644
index 77e9590..0000000
--- a/software/base/src/test/java/brooklyn/entity/chef/mysql/ChefSoloDriverMySqlEntityLiveTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef.mysql;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.software.SshEffectorTasks;
-
-public class ChefSoloDriverMySqlEntityLiveTest extends AbstractChefToyMySqlEntityLiveTest {
-
-    // test here just so Eclipse IDE picks it up
-    @Override @Test(groups="Live")
-    public void testMySqlOnProvisioningLocation() throws Exception {
-        super.testMySqlOnProvisioningLocation();
-    }
-
-    @Override
-    protected Integer getPid(Entity mysql) {
-        ProcessTaskWrapper<Integer> t = Entities.submit(mysql, SshEffectorTasks.ssh("sudo cat "+ChefSoloDriverToyMySqlEntity.PID_FILE));
-        return Integer.parseInt(t.block().getStdout().trim());
-    }
-    
-    @Override
-    protected Entity createMysql() {
-        return app.createAndManageChild(EntitySpec.create(Entity.class, ChefSoloDriverToyMySqlEntity.class).
-                additionalInterfaces(SoftwareProcess.class));
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/chef/mysql/ChefSoloDriverToyMySqlEntity.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/chef/mysql/ChefSoloDriverToyMySqlEntity.java b/software/base/src/test/java/brooklyn/entity/chef/mysql/ChefSoloDriverToyMySqlEntity.java
deleted file mode 100644
index 68ad137..0000000
--- a/software/base/src/test/java/brooklyn/entity/chef/mysql/ChefSoloDriverToyMySqlEntity.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef.mysql;
-
-import org.apache.brooklyn.api.mgmt.TaskAdaptable;
-import org.apache.brooklyn.api.mgmt.TaskFactory;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.sensor.feed.ssh.SshFeed;
-import org.apache.brooklyn.sensor.feed.ssh.SshPollConfig;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.time.Duration;
-
-import brooklyn.entity.basic.SoftwareProcessImpl;
-import brooklyn.entity.chef.ChefConfig;
-import brooklyn.entity.chef.ChefConfigs;
-import brooklyn.entity.chef.ChefSoloDriver;
-import brooklyn.entity.software.SshEffectorTasks;
-
-@Deprecated /** @deprecated since 0.7.0 use see examples {Dynamic,Typed}ToyMySqlEntityChef */
-public class ChefSoloDriverToyMySqlEntity extends SoftwareProcessImpl implements ChefConfig {
-
-    public static final String PID_FILE = "/var/run/mysqld/mysqld.pid";
-    public static final ConfigKey<TaskFactory<? extends TaskAdaptable<Boolean>>> IS_RUNNING_TASK =
-            ConfigKeys.newConfigKeyWithDefault(ChefSoloDriver.IS_RUNNING_TASK, 
-            SshEffectorTasks.isPidFromFileRunning(PID_FILE).runAsRoot());
-
-    public static final ConfigKey<TaskFactory<?>> STOP_TASK =
-            ConfigKeys.newConfigKeyWithDefault(ChefSoloDriver.STOP_TASK, 
-            SshEffectorTasks.ssh("/etc/init.d/mysql stop").allowingNonZeroExitCode().runAsRoot());
-
-    private SshFeed upFeed;
-    
-    @Override
-    public Class<?> getDriverInterface() {
-        return ChefSoloDriver.class;
-    }
-
-    @Override
-    protected void connectSensors() {
-        super.connectSensors();
-        
-        // TODO have a TaskFactoryFeed which reuses the IS_RUNNING_TASK
-        upFeed = SshFeed.builder().entity(this).period(Duration.FIVE_SECONDS.toMilliseconds())
-            .poll(new SshPollConfig<Boolean>(SERVICE_UP)
-                    .command("ps -p `sudo cat /var/run/mysqld/mysqld.pid`")
-                    .setOnSuccess(true).setOnFailureOrException(false))
-            .build();
-    }
-    
-    @Override
-    protected void disconnectSensors() {
-        // TODO nicer way to disconnect
-        if (upFeed != null) upFeed.stop();
-        super.disconnectSensors();
-    }
-    
-    @Override
-    public void init() {
-        super.init();
-        ChefConfigs.addToLaunchRunList(this, "mysql::server");
-        ChefConfigs.addToCookbooksFromGithub(this, "mysql", "build-essential", "openssl");
-        ChefConfigs.setLaunchAttribute(this, "mysql",  
-                MutableMap.of()
-                    .add("server_root_password", "MyPassword")
-                    .add("server_debian_password", "MyPassword")
-                    .add("server_repl_password", "MyPassword")
-                );
-        
-        // TODO other attributes, eg:
-        // node['mysql']['port']
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/chef/mysql/DynamicChefAutodetectToyMySqlEntityLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/chef/mysql/DynamicChefAutodetectToyMySqlEntityLiveTest.java b/software/base/src/test/java/brooklyn/entity/chef/mysql/DynamicChefAutodetectToyMySqlEntityLiveTest.java
deleted file mode 100644
index d275a54..0000000
--- a/software/base/src/test/java/brooklyn/entity/chef/mysql/DynamicChefAutodetectToyMySqlEntityLiveTest.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef.mysql;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.Test;
-
-public class DynamicChefAutodetectToyMySqlEntityLiveTest extends AbstractChefToyMySqlEntityLiveTest {
-
-    private static final Logger log = LoggerFactory.getLogger(DynamicChefAutodetectToyMySqlEntityLiveTest.class);
-    
-    // test here just so Eclipse IDE picks it up
-    @Override @Test(groups="Live")
-    public void testMySqlOnProvisioningLocation() throws Exception {
-        super.testMySqlOnProvisioningLocation();
-    }
-    
-    @Override
-    protected Entity createMysql() {
-        Entity mysql = app.createAndManageChild(DynamicToyMySqlEntityChef.spec());
-        log.debug("created "+mysql);
-        return mysql;
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/chef/mysql/DynamicChefServerToyMySqlEntityLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/chef/mysql/DynamicChefServerToyMySqlEntityLiveTest.java b/software/base/src/test/java/brooklyn/entity/chef/mysql/DynamicChefServerToyMySqlEntityLiveTest.java
deleted file mode 100644
index 7a47b05..0000000
--- a/software/base/src/test/java/brooklyn/entity/chef/mysql/DynamicChefServerToyMySqlEntityLiveTest.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef.mysql;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.chef.ChefLiveTestSupport;
-import brooklyn.entity.chef.ChefServerTasksIntegrationTest;
-
-/** Expects knife on the path, but will use Brooklyn registered account,
- * and that account has the mysql recipe installed.
- * <p>
- * See {@link ChefServerTasksIntegrationTest} for more info. */
-public class DynamicChefServerToyMySqlEntityLiveTest extends AbstractChefToyMySqlEntityLiveTest {
-
-    private static final Logger log = LoggerFactory.getLogger(DynamicChefServerToyMySqlEntityLiveTest.class);
-    
-    // test here just so Eclipse IDE picks it up
-    @Override @Test(groups="Live")
-    public void testMySqlOnProvisioningLocation() throws Exception {
-        super.testMySqlOnProvisioningLocation();
-    }
-    
-    @Override
-    protected Entity createMysql() {
-        ChefLiveTestSupport.installBrooklynChefHostedConfig(app);
-        Entity mysql = app.createAndManageChild(DynamicToyMySqlEntityChef.specKnife());
-        log.debug("created "+mysql);
-        return mysql;
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/chef/mysql/DynamicChefSoloToyMySqlEntityLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/chef/mysql/DynamicChefSoloToyMySqlEntityLiveTest.java b/software/base/src/test/java/brooklyn/entity/chef/mysql/DynamicChefSoloToyMySqlEntityLiveTest.java
deleted file mode 100644
index 8503069..0000000
--- a/software/base/src/test/java/brooklyn/entity/chef/mysql/DynamicChefSoloToyMySqlEntityLiveTest.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef.mysql;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.Test;
-
-public class DynamicChefSoloToyMySqlEntityLiveTest extends AbstractChefToyMySqlEntityLiveTest {
-
-    private static final Logger log = LoggerFactory.getLogger(DynamicChefSoloToyMySqlEntityLiveTest.class);
-    
-    // test here just so Eclipse IDE picks it up
-    @Override @Test(groups="Live")
-    public void testMySqlOnProvisioningLocation() throws Exception {
-        super.testMySqlOnProvisioningLocation();
-    }
-    
-    @Override
-    protected Entity createMysql() {
-        Entity mysql = app.createAndManageChild(DynamicToyMySqlEntityChef.specSolo());
-        log.debug("created "+mysql);
-        return mysql;
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/chef/mysql/DynamicToyMySqlEntityChef.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/chef/mysql/DynamicToyMySqlEntityChef.java b/software/base/src/test/java/brooklyn/entity/chef/mysql/DynamicToyMySqlEntityChef.java
deleted file mode 100644
index b9069be..0000000
--- a/software/base/src/test/java/brooklyn/entity/chef/mysql/DynamicToyMySqlEntityChef.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef.mysql;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.chef.ChefConfig;
-import brooklyn.entity.chef.ChefConfigs;
-import brooklyn.entity.chef.ChefEntity;
-
-/** Builds up a MySql entity via chef using specs only */
-public class DynamicToyMySqlEntityChef implements ChefConfig {
-
-    private static final Logger log = LoggerFactory.getLogger(DynamicToyMySqlEntityChef.class);
-
-    protected static EntitySpec<? extends Entity> specBase() {
-        EntitySpec<ChefEntity> spec = EntitySpec.create(ChefEntity.class);
-        
-        ChefConfigs.addToLaunchRunList(spec, "mysql::server");
-        spec.configure(PID_FILE, "/var/run/mysqld/mysql*.pid");
-        // init.d service name is sometimes mysql, sometimes mysqld, depending ubuntu/centos
-        // we use pid file above instead, but this (with the right name) could be used:
-//        spec.configure(SERVICE_NAME, "mysql");
-        
-        // chef mysql fails on first run but works on second if switching between server and solo modes
-        spec.configure(ChefConfig.CHEF_RUN_CONVERGE_TWICE, true);
-
-        // only used for solo, but safely ignored for knife
-        ChefConfigs.addToCookbooksFromGithub(spec, "mysql", "build-essential", "openssl");
-        // we always need dependent cookbooks set, and mysql requires password set
-        // (TODO for knife we might wish to prefer things from the server)
-        ChefConfigs.addLaunchAttributes(spec, MutableMap.of("mysql",  
-                MutableMap.of()
-                .add("server_root_password", "MyPassword")
-                .add("server_debian_password", "MyPassword")
-                .add("server_repl_password", "MyPassword")
-            ));
-        
-        return spec;
-    }
-
-    public static EntitySpec<? extends Entity> spec() {
-        EntitySpec<? extends Entity> spec = specBase();
-        log.debug("Created entity spec for MySql: "+spec);
-        return spec;
-    }
-
-    public static EntitySpec<? extends Entity> specSolo() {
-        EntitySpec<? extends Entity> spec = specBase();
-        spec.configure(ChefConfig.CHEF_MODE, ChefConfig.ChefModes.SOLO);
-        log.debug("Created entity spec for MySql: "+spec);
-        return spec;
-    }
-
-    public static EntitySpec<? extends Entity> specKnife() {
-        EntitySpec<? extends Entity> spec = specBase();
-        spec.configure(ChefConfig.CHEF_MODE, ChefConfig.ChefModes.KNIFE);
-        log.debug("Created entity spec for MySql: "+spec);
-        return spec;
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/chef/mysql/TypedToyMySqlEntityChef.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/chef/mysql/TypedToyMySqlEntityChef.java b/software/base/src/test/java/brooklyn/entity/chef/mysql/TypedToyMySqlEntityChef.java
deleted file mode 100644
index ba428d2..0000000
--- a/software/base/src/test/java/brooklyn/entity/chef/mysql/TypedToyMySqlEntityChef.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef.mysql;
-
-import org.apache.brooklyn.util.git.GithubUrls;
-
-import brooklyn.entity.chef.ChefConfig;
-import brooklyn.entity.chef.ChefEntityImpl;
-
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-
-/** Illustrates how to define an entity using Java as a Java class, extending ChefEntityImpl */
-public class TypedToyMySqlEntityChef extends ChefEntityImpl {
-
-    @Override
-    public void init() {
-        super.init();
-
-        String password = "p4ssw0rd";
-        
-        setConfig(CHEF_COOKBOOK_PRIMARY_NAME, "mysql");
-        setConfig(CHEF_COOKBOOK_URLS, ImmutableMap.of(
-            "mysql", GithubUrls.tgz("opscode-cookbooks", "mysql", "v4.0.12"),
-            "openssl", GithubUrls.tgz("opscode-cookbooks", "openssl", "v1.1.0"),
-            "mysql", GithubUrls.tgz("opscode-cookbooks", "build-essential", "v1.4.4")));
-        
-        setConfig(CHEF_LAUNCH_RUN_LIST, ImmutableSet.of("mysql::server"));
-        setConfig(CHEF_LAUNCH_ATTRIBUTES, ImmutableMap.<String,Object>of(
-            "mysql", ImmutableMap.of(
-                "server_root_password", password,
-                "server_repl_password", password,
-                "server_debian_password", password)));
-        
-        setConfig(ChefConfig.PID_FILE, "/var/run/mysqld/mysqld.pid");
-        
-        setConfig(CHEF_MODE, ChefModes.SOLO);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/driver/MockSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/driver/MockSshDriver.java b/software/base/src/test/java/brooklyn/entity/driver/MockSshDriver.java
deleted file mode 100644
index 15c0aec..0000000
--- a/software/base/src/test/java/brooklyn/entity/driver/MockSshDriver.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.driver;
-
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.location.Location;
-
-import brooklyn.entity.basic.SoftwareProcessDriver;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-public class MockSshDriver implements SoftwareProcessDriver {
-
-    public int numCallsToRunApp = 0;
-    private final EntityLocal entity;
-    private final SshMachineLocation machine;
-
-    public MockSshDriver(EntityLocal entity, SshMachineLocation machine) {
-        this.entity = entity;
-        this.machine = machine;
-    }
-    
-    @Override
-    public void start() {
-        numCallsToRunApp++;
-    }
-
-    @Override
-    public boolean isRunning() {
-        return numCallsToRunApp>0;
-    }
-
-    @Override
-    public EntityLocal getEntity() {
-        return entity;
-    }
-
-    @Override
-    public Location getLocation() {
-        return machine;
-    }
-
-    @Override
-    public void rebind() {
-    }
-
-    @Override
-    public void stop() {
-    }
-
-    @Override
-    public void restart() {
-    }
-    
-    @Override
-    public void kill() {
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/group/DynamicClusterWithAvailabilityZonesMultiLocationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/group/DynamicClusterWithAvailabilityZonesMultiLocationTest.java b/software/base/src/test/java/brooklyn/entity/group/DynamicClusterWithAvailabilityZonesMultiLocationTest.java
deleted file mode 100644
index 9361cf7..0000000
--- a/software/base/src/test/java/brooklyn/entity/group/DynamicClusterWithAvailabilityZonesMultiLocationTest.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.group;
-
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertNull;
-
-import java.util.List;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.entity.core.EntityPredicates;
-import org.apache.brooklyn.entity.group.DynamicCluster;
-import org.apache.brooklyn.entity.group.DynamicClusterWithAvailabilityZonesTest;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.EmptySoftwareProcess;
-import brooklyn.entity.basic.SoftwareProcess;
-
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.MultiLocation;
-import org.apache.brooklyn.test.Asserts;
-
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
-/**
- * Uses {@link SoftwareProcess}, so test can't be in core project.
- * 
- * Different from {@link DynamicClusterWithAvailabilityZonesTest} in the use of {@link MultiLocation}.
- * However, the difference is important: the {@link SoftwareProcess} entity has two locations
- * (the {@link MachineProvisioningLocation} and the {@link MachineLocation}, which was previously
- * causing a failure - now fixed and tested here.
- */
-public class DynamicClusterWithAvailabilityZonesMultiLocationTest extends BrooklynAppUnitTestSupport {
-    
-    private DynamicCluster cluster;
-    
-    private LocalhostMachineProvisioningLocation subLoc1;
-    private LocalhostMachineProvisioningLocation subLoc2;
-    private MultiLocation<?> multiLoc;
-    
-    @BeforeMethod(alwaysRun=true)
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-        cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure(DynamicCluster.ENABLE_AVAILABILITY_ZONES, true)
-                .configure(DynamicCluster.INITIAL_SIZE, 0)
-                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(EmptySoftwareProcess.class)));
-        
-        subLoc1 = app.newLocalhostProvisioningLocation(ImmutableMap.of("displayName", "loc1"));
-        subLoc2 = app.newLocalhostProvisioningLocation(ImmutableMap.of("displayName", "loc2"));
-        multiLoc = mgmt.getLocationManager().createLocation(LocationSpec.create(MultiLocation.class)
-                .configure(MultiLocation.SUB_LOCATIONS, ImmutableList.<MachineProvisioningLocation<?>>of(subLoc1, subLoc2)));
-    }
-
-    @Test
-    public void testReplacesEntityInSameZone() throws Exception {
-        ((EntityLocal)cluster).config().set(DynamicCluster.ENABLE_AVAILABILITY_ZONES, true);
-        cluster.start(ImmutableList.of(multiLoc));
-        
-        cluster.resize(4);
-        List<String> locsUsed = getLocationNames(getLocationsOf(cluster.getMembers(), Predicates.instanceOf(MachineProvisioningLocation.class)));
-        Asserts.assertEqualsIgnoringOrder(locsUsed, ImmutableList.of("loc1", "loc1", "loc2", "loc2"));
-
-        String idToRemove = Iterables.getFirst(cluster.getMembers(), null).getId();
-        String idAdded = cluster.replaceMember(idToRemove);
-        locsUsed = getLocationNames(getLocationsOf(cluster.getMembers(), Predicates.instanceOf(MachineProvisioningLocation.class)));
-        Asserts.assertEqualsIgnoringOrder(locsUsed, ImmutableList.of("loc1", "loc1", "loc2", "loc2"));
-        assertNull(Iterables.find(cluster.getMembers(), EntityPredicates.idEqualTo(idToRemove), null));
-        assertNotNull(Iterables.find(cluster.getMembers(), EntityPredicates.idEqualTo(idAdded), null));
-    }
-    
-    protected List<Location> getLocationsOf(Iterable<? extends Entity> entities, Predicate<? super Location> filter) {
-        List<Location> result = Lists.newArrayList();
-        for (Entity entity : entities) {
-            Iterables.addAll(result, Iterables.filter(entity.getLocations(), filter));
-        }
-        return result;
-    }
-
-    protected List<String> getLocationNames(Iterable<? extends Location> locs) {
-        List<String> result = Lists.newArrayList();
-        for (Location subLoc : locs) {
-            result.add(subLoc.getDisplayName());
-        }
-        return result;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/java/EntityPollingTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/java/EntityPollingTest.java b/software/base/src/test/java/brooklyn/entity/java/EntityPollingTest.java
deleted file mode 100644
index 0168a0f..0000000
--- a/software/base/src/test/java/brooklyn/entity/java/EntityPollingTest.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.java.UsesJmx.JmxAgentModes;
-import brooklyn.event.feed.jmx.JmxAttributePollConfig;
-import brooklyn.event.feed.jmx.JmxFeed;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-import brooklyn.test.JmxService;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-public class EntityPollingTest {
-
-    private static final Logger LOG = LoggerFactory.getLogger(EntityPollingTest.class);
-
-    private JmxService jmxService;
-    private TestApplication app;
-    private SoftwareProcess entity;
-    
-    private static final BasicAttributeSensor<String> stringAttribute = new BasicAttributeSensor<String>(
-            String.class, "brooklyn.test.stringAttribute", "Brooklyn testing int attribute");
-    private String objectName = "Brooklyn:type=MyTestMBean,name=myname";
-    
-    private static final ObjectName jmxObjectName;
-    static {
-        try {
-            jmxObjectName = new ObjectName("Brooklyn:type=MyTestMBean,name=myname");
-        } catch (MalformedObjectNameException e) {
-            throw Exceptions.propagate(e);
-        }
-    }
-
-    private static final String attributeName = "myattrib";
-
-    public static class SubVanillaJavaApp extends VanillaJavaAppImpl {
-        private JmxFeed feed;
-        
-        @Override protected void connectSensors() {
-            super.connectSensors();
-   
-            // Add a sensor that we can explicitly set in jmx
-            feed = JmxFeed.builder()
-                .entity(this)
-                .pollAttribute(new JmxAttributePollConfig<String>(stringAttribute)
-                    .objectName(jmxObjectName)
-                    .attributeName(attributeName))
-                .build();
-        }
-
-        @Override
-        public void disconnectSensors() {
-            super.disconnectSensors();
-            if (feed != null) feed.stop();
-        }
-        
-        @SuppressWarnings({ "rawtypes", "unchecked" })
-        @Override
-        public Class getDriverInterface() {
-            return null;
-        }
-
-        @Override
-        public VanillaJavaAppSshDriver newDriver(MachineLocation loc) {
-            return new VanillaJavaAppSshDriver(this, (SshMachineLocation)loc) {
-                @Override public void install() {
-                    // no-op
-                }
-                @Override public void customize() {
-                    // no-op
-                }
-                @Override public void launch() {
-                    // no-op
-                }
-                @Override public boolean isRunning() {
-                    return true;
-                }
-                @Override public void stop() {
-                    // no-op
-                }
-                @Override public void kill() {
-                    // no-op
-                }
-            };
-        }
-    };        
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() {
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        
-        /*
-         * Create an entity, using real entity code, but that swaps out the external process
-         * for a JmxService that we can control in the test.        
-         */
-        entity = app.createAndManageChild(EntitySpec.create(SoftwareProcess.class).impl(SubVanillaJavaApp.class)
-                .configure("rmiRegistryPort", 40123)
-                .configure("mxbeanStatsEnabled", false)
-                .configure(UsesJmx.JMX_AGENT_MODE, JmxAgentModes.JMX_RMI_CUSTOM_AGENT));
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-        if (jmxService != null) jmxService.shutdown();
-    }
-
-    // Tests that the happy path works
-    @Test(groups="Integration")
-    public void testSimpleConnection() throws Exception {
-        jmxService = new JmxService("localhost", 40123);
-        jmxService.registerMBean(ImmutableMap.of(attributeName, "myval"), objectName);
-
-        app.start(ImmutableList.of(new SshMachineLocation(MutableMap.of("address", "localhost"))));
-        
-        // Starts with value defined when registering...
-        EntityTestUtils.assertAttributeEqualsEventually(entity, stringAttribute, "myval");
-    }
-
-    // Test that connect will keep retrying (e.g. start script returns before the JMX server is up)
-    @Test(groups="Integration")
-    public void testEntityWithDelayedJmxStartupWillKeepRetrying() {
-        // In 2 seconds time, we'll start the JMX server
-        Thread t = new Thread(new Runnable() {
-            public void run() {
-                try {
-                    Thread.sleep(2000);
-                    jmxService = new JmxService("localhost", 40123);
-                    jmxService.registerMBean(ImmutableMap.of(attributeName, "myval"), objectName);
-                } catch (Exception e) {
-                    LOG.error("Error in testEntityWithDelayedJmxStartupWillKeepRetrying", e);
-                    throw Exceptions.propagate(e);
-                }
-            }});
-
-        try {
-            t.start();
-            app.start(ImmutableList.of(new SshMachineLocation(MutableMap.of("address", "localhost"))));
-
-            EntityTestUtils.assertAttributeEqualsEventually(entity, stringAttribute, "myval");
-            
-        } finally {
-            t.interrupt();
-        }
-    }
-    
-    @Test(groups="Integration")
-    public void testJmxConnectionGoesDownRequiringReconnect() throws Exception {
-        jmxService = new JmxService("localhost", 40123);
-        jmxService.registerMBean(ImmutableMap.of(attributeName, "myval"), objectName);
-
-        app.start(ImmutableList.of(new SshMachineLocation(MutableMap.of("address", "localhost"))));
-        
-        EntityTestUtils.assertAttributeEqualsEventually(entity, stringAttribute, "myval");
-        
-        // Shutdown the MBeanServer - simulates network failure so can't connect
-        jmxService.shutdown();
-        
-        // TODO Want a better way of determining that the entity is down; ideally should have 
-        // sensor for entity-down that's wired up to a JMX attribute?
-        Thread.sleep(5000);
-
-        // Restart MBeanServer, and set attribute to different value; expect it to be polled again
-        jmxService = new JmxService("localhost", 40123);
-        jmxService.registerMBean(ImmutableMap.of(attributeName, "myval2"), objectName);
-        
-        EntityTestUtils.assertAttributeEqualsEventually(entity, stringAttribute, "myval2");
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/java/ExampleVanillaMain.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/java/ExampleVanillaMain.java b/software/base/src/test/java/brooklyn/entity/java/ExampleVanillaMain.java
deleted file mode 100644
index 65c3903..0000000
--- a/software/base/src/test/java/brooklyn/entity/java/ExampleVanillaMain.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-public class ExampleVanillaMain {
-    public static void main(String[] args) throws Exception {
-        System.out.println("In VanillaJavaExampleMain.main");
-        Thread.sleep(100*1000);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/java/ExampleVanillaMainCpuHungry.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/java/ExampleVanillaMainCpuHungry.java b/software/base/src/test/java/brooklyn/entity/java/ExampleVanillaMainCpuHungry.java
deleted file mode 100644
index fe2179d..0000000
--- a/software/base/src/test/java/brooklyn/entity/java/ExampleVanillaMainCpuHungry.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-public class ExampleVanillaMainCpuHungry {
-    private static final int MAX_TIME_MILLIS = 100*1000;
-    private static final int CALCULATIONS_PER_CYCLE = 100000;
-    private static final int SLEEP_PER_CYCLE_MILLIS = 1;
-    
-    public static void main(String[] args) throws Exception {
-        System.out.println("In ExampleVanillaMainCpuHungry.main");
-        long startTime = System.currentTimeMillis();
-        long count = 0;
-        double total = 0;
-        do {
-            for (int i = 0; i < CALCULATIONS_PER_CYCLE; i++) {
-                total += Math.sqrt(Math.random());
-                count++;
-            }
-            Thread.sleep(SLEEP_PER_CYCLE_MILLIS);
-        } while ((System.currentTimeMillis() - startTime) < MAX_TIME_MILLIS);
-        
-        System.out.println("Did "+count+" random square roots, took "+(System.currentTimeMillis()-startTime)+"ms; total = "+total);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/java/JavaOptsTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/java/JavaOptsTest.java b/software/base/src/test/java/brooklyn/entity/java/JavaOptsTest.java
deleted file mode 100644
index 958f126..0000000
--- a/software/base/src/test/java/brooklyn/entity/java/JavaOptsTest.java
+++ /dev/null
@@ -1,357 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import static org.testng.Assert.fail;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.collections.MutableSet;
-import org.apache.brooklyn.util.core.internal.ssh.RecordingSshTool;
-import org.apache.brooklyn.util.core.internal.ssh.SshTool;
-import org.apache.brooklyn.util.core.internal.ssh.RecordingSshTool.ExecCmd;
-import org.apache.brooklyn.util.jmx.jmxmp.JmxmpAgent;
-import org.apache.brooklyn.util.text.Strings;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.MapDifference.ValueDifference;
-import com.google.common.collect.Maps;
-
-@SuppressWarnings({ "rawtypes", "unchecked" })
-public class JavaOptsTest extends BrooklynAppUnitTestSupport {
-
-    // TODO Test setting classpath; but this works by customize() copying all the artifacts into /lib/*
-    // so that we can simply set this on the classpath...
-    
-    private static final Logger log = LoggerFactory.getLogger(JavaOptsTest.class);
-    
-    private SshMachineLocation loc;
-    
-    @BeforeMethod(alwaysRun=true)
-    @Override
-    public void setUp() throws Exception {
-        RecordingSshTool.execScriptCmds.clear();
-        super.setUp();
-        loc = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                .configure("address", "localhost")
-                .configure(SshTool.PROP_TOOL_CLASS, RecordingSshTool.class.getName()));
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    @Override
-    public void tearDown() throws Exception {
-        super.tearDown();
-        RecordingSshTool.execScriptCmds.clear();
-    }
-    
-    @Test
-    public void testSimpleLaunchesJavaProcess() {
-        VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
-            .configure("main", "my.Main").configure("useJmx", false));
-        app.start(ImmutableList.of(loc));
-        
-        String runDir = javaProcess.getRunDir();
-        Map<String,String> expectedEnvs = ImmutableMap.<String,String>of();
-        List<String> expectedCmds = ImmutableList.of(String.format("java $JAVA_OPTS -cp \"%1$s/lib\" my.Main  >> %1$s/console 2>&1 </dev/null &", runDir));
-        
-        assertHasExpectedCmds(expectedCmds, expectedEnvs);
-    }
-    
-    @Test
-    public void testPassesJavaArgs() {
-        VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
-            .configure("main", "my.Main").configure("useJmx", false).configure("args", ImmutableList.of("a1", "a2")));
-        app.start(ImmutableList.of(loc));
-        
-        String runDir = javaProcess.getRunDir();
-        Map<String,String> expectedEnvs = ImmutableMap.<String,String>of();
-        List<String> expectedCmds = ImmutableList.of(String.format("java $JAVA_OPTS -cp \"%1$s/lib\" my.Main \"a1\" \"a2\" >> %1$s/console 2>&1 </dev/null &", runDir));
-        
-        assertHasExpectedCmds(expectedCmds, expectedEnvs);
-    }
-    
-    @Test
-    public void testPassesJavaOpts() {
-        VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
-            .configure("main", "my.Main").configure("useJmx", false).configure("javaOpts", ImmutableList.of("-abc")));
-        app.start(ImmutableList.of(loc));
-        
-        String runDir = javaProcess.getRunDir();
-        String defaultJavaOpts = "-Xms128m -Xmx512m -XX:MaxPermSize=512m";
-        String expectedJavaOpts = defaultJavaOpts+" -abc";
-        Map<String,String> expectedEnvs = ImmutableMap.<String,String>of("JAVA_OPTS", expectedJavaOpts);
-        List<String> expectedCmds = ImmutableList.of(String.format("java $JAVA_OPTS -cp \"%1$s/lib\" my.Main  >> %1$s/console 2>&1 </dev/null &", runDir));
-        
-        assertHasExpectedCmds(expectedCmds, expectedEnvs);
-    }
-
-    @Test
-    public void testPassesJavaSysProps() {
-        VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
-            .configure("main", "my.Main").configure("useJmx", false).configure("javaSysProps", ImmutableMap.of("mykey", "myval")));
-
-        app.start(ImmutableList.of(loc));
-        
-        String runDir = javaProcess.getRunDir();
-        String defaultJavaOpts = "-Xms128m -Xmx512m -XX:MaxPermSize=512m";
-        String expectedJavaOpts = defaultJavaOpts+" -Dmykey=myval";
-        Map<String,String> expectedEnvs = ImmutableMap.<String,String>of("JAVA_OPTS", expectedJavaOpts);
-        List<String> expectedCmds = ImmutableList.of(String.format("java $JAVA_OPTS -cp \"%1$s/lib\" my.Main  >> %1$s/console 2>&1 </dev/null &", runDir));
-        
-        assertHasExpectedCmds(expectedCmds, expectedEnvs);
-    }
-    
-    @Test
-    public void testPassesJavaOptsOverridingDefaults() {
-        VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
-            .configure("main", "my.Main").configure("useJmx", false).configure("javaOpts", ImmutableList.of("-Xmx567m", "-XX:MaxPermSize=567m")));
-        app.start(ImmutableList.of(loc));
-        
-        String runDir = javaProcess.getRunDir();
-        Object expectedJavaOpts = MutableSet.of("-Xms128m", "-Xmx567m", "-XX:MaxPermSize=567m");
-        Map<String,Object> expectedEnvs = ImmutableMap.<String,Object>of("JAVA_OPTS", expectedJavaOpts);
-        List<String> expectedCmds = ImmutableList.of(String.format("java $JAVA_OPTS -cp \"%1$s/lib\" my.Main  >> %1$s/console 2>&1 </dev/null &", runDir));
-
-        assertHasExpectedCmds(expectedCmds, expectedEnvs);
-    }
-    
-    public static class TestingJavaOptsVanillaJavaAppImpl extends VanillaJavaAppImpl {
-        @Override public VanillaJavaAppSshDriver newDriver(MachineLocation loc) {
-            return new VanillaJavaAppSshDriver(this, (SshMachineLocation)loc) {
-                @Override protected List<String> getCustomJavaConfigOptions() {
-                    return MutableList.<String>builder()
-                        .addAll(super.getCustomJavaConfigOptions())
-                        .add("-server")
-                        .build();
-                };
-            };
-        }
-    }
-    
-    @Test
-    public void testPassesJavaOptsObeyingMutualExclusions() {
-        VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class, TestingJavaOptsVanillaJavaAppImpl.class)
-            .configure("main", "my.Main").configure("useJmx", false).configure("javaOpts", ImmutableList.of("-client")));
-        app.start(ImmutableList.of(loc));
-        
-        String runDir = javaProcess.getRunDir();
-        String defaultJavaOpts = "-Xms128m -Xmx512m -XX:MaxPermSize=512m";
-        String expectedJavaOpts = defaultJavaOpts+" -client";
-        Map<String,String> expectedEnvs = ImmutableMap.<String,String>of("JAVA_OPTS", expectedJavaOpts);
-        List<String> expectedCmds = ImmutableList.of(String.format("java $JAVA_OPTS -cp \"%1$s/lib\" my.Main  >> %1$s/console 2>&1 </dev/null &", runDir));
-        
-        assertHasExpectedCmds(expectedCmds, expectedEnvs);
-    }
-    
-    /**
-     * Asserts that one of the scripts executed had these commands, and these environment variables.
-     * There could be other commands in between though.
-     */
-    private void assertHasExpectedCmds(List<String> expectedCmds, Map<String,?> expectedEnvs) {
-        if (RecordingSshTool.execScriptCmds.isEmpty())
-            fail("No commands recorded");
-        
-        for (ExecCmd cmd : RecordingSshTool.execScriptCmds) {
-            // TODO Check expectedCmds in-order
-            
-            // check if expectedEnv is a set, then the string value contains all elements in the set
-            Map<Object, ValueDifference<Object>> difference = Maps.<Object,Object>difference(cmd.env, expectedEnvs).entriesDiffering();
-            boolean same = difference.isEmpty();
-            if (!same) {
-                Set<Object> differingKeys = new LinkedHashSet<Object>(difference.keySet());
-                Iterator<Object> ki = differingKeys.iterator();
-                while (ki.hasNext()) {
-                    Object key = ki.next();
-                    Object expectationHere = expectedEnvs.get(key);
-                    Object valueHere = cmd.env.get(key);
-                    if (valueHere==null) break;
-                    
-                    if (expectationHere instanceof Set) {
-                        Set mutableExpectationHere = new LinkedHashSet(((Set)expectationHere));
-                        Iterator si = ((Set)mutableExpectationHere).iterator();
-                        while (si.hasNext()) {
-                            Object oneExpectationHere = si.next();
-                            if (valueHere.toString().contains(Strings.toString(oneExpectationHere)))
-                                si.remove();
-                            else break;
-                        }
-                        if (mutableExpectationHere.isEmpty())
-                            differingKeys.remove(key);
-                        else
-                            // not the same
-                            break;
-                    } else {
-                        // not the same
-                        break;
-                    }
-                }
-                if (differingKeys.isEmpty())
-                    same = true;
-            }
-            
-            if (cmd.commands.containsAll(expectedCmds) && same) {
-                return;
-            }
-        }
-        
-        for (ExecCmd cmd : RecordingSshTool.execScriptCmds) {
-            log.info("Command:");
-            log.info("\tEnv:");
-            for (Map.Entry<?,?> entry : cmd.env.entrySet()) {
-                log.info("\t\t"+entry.getKey()+" = "+entry.getValue());
-            }
-            log.info("\tCmds:");
-            for (String c : cmd.commands) {
-                log.info("\t\t"+c);
-            }
-        }
-        
-        fail("Cmd not present: expected="+expectedCmds+"/"+expectedEnvs+"; actual="+RecordingSshTool.execScriptCmds);
-    }
-
-    public static class TestingNoSensorsVanillaJavaAppImpl extends VanillaJavaAppImpl {
-        protected void connectSensors() {
-            /* nothing here */
-            setAttribute(SERVICE_UP, true);
-        }
-    }
-    
-    private void assertJmxWithPropsHasPhrases(Map props,
-            List<String> expectedPhrases,
-            List<String> forbiddenPhrases) {
-        if (!props.containsKey("main")) props.put("main", "my.Main");
-        @SuppressWarnings({ "unused" })
-        VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class, TestingNoSensorsVanillaJavaAppImpl.class)
-            .configure(props));
-        app.start(ImmutableList.of(loc));
-        
-        List<String> phrases = new ArrayList<String>(expectedPhrases);
-        Set<String> forbiddenPhrasesFound = new LinkedHashSet<String>();
-        for (ExecCmd cmd : RecordingSshTool.execScriptCmds) {
-            String biggun = ""+cmd.env+" "+cmd.commands;
-            Iterator<String> pi = phrases.iterator();
-            while (pi.hasNext()) {
-                String phrase = pi.next();
-                if (biggun.contains(phrase)) pi.remove();
-            }
-            if (forbiddenPhrases!=null)
-                for (String p: forbiddenPhrases)
-                    if (biggun.contains(p)) forbiddenPhrasesFound.add(p);
-        }
-        
-        if (!phrases.isEmpty()) {
-            log.warn("Missing phrases in commands: "+phrases+"\nCOMMANDS: "+RecordingSshTool.execScriptCmds);
-            fail("Missing phrases in commands: "+phrases);
-        }
-        if (!forbiddenPhrasesFound.isEmpty()) {
-            log.warn("Forbidden phrases found in commands: "+forbiddenPhrasesFound+"\nCOMMANDS: "+RecordingSshTool.execScriptCmds);
-            fail("Forbidden phrases found in commands: "+forbiddenPhrasesFound);
-        }
-    }
-    
-    private static final List<String> EXPECTED_BASIC_JMX_OPTS = Arrays.asList(
-            "-Dcom.sun.management.jmxremote",
-            "-Dcom.sun.management.jmxremote.ssl=false",
-            "-Dcom.sun.management.jmxremote.authenticate=false"
-        );
-
-    private static final List<String> FORBIDDEN_BASIC_JMX_OPTS = Arrays.asList(
-            "-Dcom.sun.management.jmxremote.ssl=true",
-            
-            // often breaks things, as this is an advertised hostname usually;
-            // it typically listens on all interfaces anyway
-            "-Djava.rmi.server.hostname=0.0.0.0"
-        );
-
-    @Test
-    public void testBasicJmxFromFlag() {
-        assertJmxWithPropsHasPhrases(
-                MutableMap.builder().
-                put("useJmx", true).
-                build(), 
-            EXPECTED_BASIC_JMX_OPTS,
-            FORBIDDEN_BASIC_JMX_OPTS);
-    }
-
-    @Test
-    public void testBasicJmxFromConfig() {
-        assertJmxWithPropsHasPhrases(
-                MutableMap.builder().
-                put(UsesJmx.USE_JMX, true).
-                build(), 
-            EXPECTED_BASIC_JMX_OPTS,
-            FORBIDDEN_BASIC_JMX_OPTS);
-    }
-
-    @Test
-    public void testBasicJmxConfigFromDefault() {
-        assertJmxWithPropsHasPhrases(
-                MutableMap.builder().
-                build(), 
-            EXPECTED_BASIC_JMX_OPTS,
-            FORBIDDEN_BASIC_JMX_OPTS);
-    }
-    
-    @Test
-    public void testSecureJmxConfigFromDefault() {
-        final List<String> EXPECTED_SECURE_JMX_OPTS = Arrays.asList(
-                "-Dcom.sun.management.jmxremote",
-                "-Dbrooklyn.jmxmp.port=31009",
-                "-Dcom.sun.management.jmxremote.ssl=true",
-                "-D"+JmxmpAgent.AUTHENTICATE_CLIENTS_PROPERTY+"=true",
-                "keyStore", "/jmx-keystore",
-                "trustStore", "/jmx-truststore",
-                "-javaagent", "brooklyn-jmxmp-agent"
-            );
-
-        final List<String> FORBIDDEN_SECURE_JMX_OPTS = Arrays.asList(
-                "-Dcom.sun.management.jmxremote.authenticate=true",
-                "-Dcom.sun.management.jmxremote.ssl=false",
-                // hostname isn't forbidden -- but it is generally not used now
-                "-Djava.rmi.server.hostname="
-            );
-        
-        assertJmxWithPropsHasPhrases(
-                MutableMap.builder()
-                        .put(UsesJmx.JMX_SSL_ENABLED, true)
-                        .put(UsesJmx.JMX_PORT, 31009)
-                        .build(), 
-                EXPECTED_SECURE_JMX_OPTS,
-                FORBIDDEN_SECURE_JMX_OPTS);
-    }
-}


[31/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/java/JmxSupport.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/java/JmxSupport.java b/software/base/src/main/java/brooklyn/entity/java/JmxSupport.java
deleted file mode 100644
index f21697d..0000000
--- a/software/base/src/main/java/brooklyn/entity/java/JmxSupport.java
+++ /dev/null
@@ -1,359 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import java.util.EnumSet;
-import java.util.List;
-
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.config.ConfigKey.HasConfigKey;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.event.feed.jmx.JmxHelper;
-
-import org.apache.brooklyn.location.access.BrooklynAccessUtils;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.BrooklynMavenArtifacts;
-import org.apache.brooklyn.util.core.ResourceUtils;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.jmx.jmxmp.JmxmpAgent;
-import org.apache.brooklyn.util.jmx.jmxrmi.JmxRmiAgent;
-import org.apache.brooklyn.util.maven.MavenArtifact;
-import org.apache.brooklyn.util.maven.MavenRetriever;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.brooklyn.util.text.Strings;
-
-import com.google.common.base.Preconditions;
-import com.google.common.net.HostAndPort;
-
-public class JmxSupport implements UsesJmx {
-
-    private static final Logger log = LoggerFactory.getLogger(JmxSupport.class);
-
-    private final Entity entity;
-    private final String runDir;
-
-    private Boolean isJmx;
-    private Boolean isSecure;
-    private JmxAgentModes jmxAgentMode;
-
-    private static boolean warnedAboutNotOnClasspath = false;
-
-    /** run dir may be null if it is not accessed */
-    public JmxSupport(Entity entity, @Nullable String runDir) {
-        this.entity = Preconditions.checkNotNull(entity, "entity must be supplied");
-        this.runDir = runDir;
-    }
-
-    @Nonnull
-    public String getRunDir() {
-        return Preconditions.checkNotNull(runDir, "runDir must have been supplied to perform this operation");
-    }
-
-    public Entity getEntity() {
-        return entity;
-    }
-
-    <T> T getConfig(ConfigKey<T> key) {
-        return getEntity().getConfig(key);
-    }
-
-    <T> T getConfig(HasConfigKey<T> key) {
-        return getEntity().getConfig(key);
-    }
-
-    <T> void setConfig(ConfigKey<T> key, T value) {
-        ((EntityLocal)getEntity()).setConfig(key, value);
-    }
-
-    public Maybe<SshMachineLocation> getMachine() {
-        return Locations.findUniqueSshMachineLocation(entity.getLocations());
-    }
-
-    public boolean isJmx() {
-        init();
-        return isJmx;
-    }
-
-    public JmxAgentModes getJmxAgentMode() {
-        init();
-        if (jmxAgentMode==null) return JmxAgentModes.NONE;
-        return jmxAgentMode;
-    }
-
-    public boolean isSecure() {
-        init();
-        if (isSecure==null) return false;
-        return isSecure;
-    }
-
-    protected synchronized void init() {
-        if (isJmx!=null)
-            return;
-
-        if (Boolean.FALSE.equals(entity.getConfig(USE_JMX))) {
-            isJmx = false;
-            return;
-        }
-        isJmx = true;
-        jmxAgentMode = entity.getConfig(JMX_AGENT_MODE);
-        if (jmxAgentMode==null) jmxAgentMode = JmxAgentModes.AUTODETECT;
-
-        isSecure = entity.getConfig(JMX_SSL_ENABLED);
-        if (isSecure==null) isSecure = false;
-
-        if (jmxAgentMode==JmxAgentModes.AUTODETECT) {
-            if (isSecure()) {
-                jmxAgentMode = JmxAgentModes.JMXMP;
-            } else {
-                jmxAgentMode = JmxAgentModes.JMXMP_AND_RMI;
-                if (!ResourceUtils.create(this).doesUrlExist(getJmxAgentJarUrl())) {
-                    // can happen e.g. if eclipse build
-                    log.warn("JMX agent JAR not found ("+getJmxAgentJarUrl()+") when auto-detecting JMX settings for "+entity+"; " +
-                            "likely cause is an incomplete build (e.g. from Eclipse; run a maven build then retry in the IDE); "+
-                            "reverting to NONE (use built-in Java JMX support, which will not go through firewalls)");
-                    jmxAgentMode = JmxAgentModes.NONE;
-                }
-            }
-
-            ((EntityLocal)entity).setConfig(JMX_AGENT_MODE, jmxAgentMode);
-        }
-
-        if (isSecure && jmxAgentMode!=JmxAgentModes.JMXMP) {
-            String msg = "JMX SSL is specified, but it requires JMXMP which is disabled, when configuring "+entity;
-            log.warn(msg);
-            throw new IllegalStateException(msg);
-        }
-    }
-
-    public void setJmxUrl() {
-        ((EntityInternal)entity).setAttribute(JMX_URL, getJmxUrl());
-    }
-
-    public String getJmxUrl() {
-        init();
-
-        HostAndPort jmx = BrooklynAccessUtils.getBrooklynAccessibleAddress(entity, entity.getAttribute(JMX_PORT));
-
-        if (EnumSet.of(JmxAgentModes.JMXMP, JmxAgentModes.JMXMP_AND_RMI).contains(getJmxAgentMode())) {
-            return JmxHelper.toJmxmpUrl(jmx.getHostText(), jmx.getPort());
-        } else {
-            if (getJmxAgentMode() == JmxAgentModes.NONE) {
-                fixPortsForModeNone();
-            }
-            // this will work for agent or agentless
-            HostAndPort rmi = BrooklynAccessUtils.getBrooklynAccessibleAddress(entity, entity.getAttribute(RMI_REGISTRY_PORT));
-            return JmxHelper.toRmiJmxUrl(jmx.getHostText(), jmx.getPort(), rmi.getPort(),
-                    entity.getAttribute(JMX_CONTEXT));
-        }
-    }
-
-    /** mode NONE cannot set a JMX (RMI server) port; it needs an RMI registry port,
-     * then gets redirected to an anonymous RMI server port;
-     * both the hostname and the anonymous port must be accessible to use this mode
-     * (hence the use of the other agents in most cases) */
-    protected int fixPortsForModeNone() {
-        assert getJmxAgentMode()==JmxAgentModes.NONE;
-        Integer jmxRemotePort = getEntity().getAttribute(JMX_PORT);
-        Integer rmiRegistryPort = getEntity().getAttribute(RMI_REGISTRY_PORT);
-        if (rmiRegistryPort!=null && rmiRegistryPort>0) {
-            if (jmxRemotePort==null || jmxRemotePort!=rmiRegistryPort) {
-                if (jmxRemotePort!=null && jmxRemotePort>0) {
-                    // ignore RMI registry port when mode 'none' is set -- set same as JMX port here
-                    // (bit irritating, but JMX_PORT will be ignored in this mode)
-                    log.warn("Ignoring JMX_PORT "+jmxRemotePort+" when configuring agentless JMX on "+getEntity()+"; will use RMI_REGISTRY_PORT "+rmiRegistryPort);
-                }
-                jmxRemotePort = rmiRegistryPort;
-                ((EntityLocal)getEntity()).setAttribute(JMX_PORT, jmxRemotePort);
-            }
-        } else {
-            if (jmxRemotePort==null || jmxRemotePort<=0) {
-                throw new IllegalStateException("Invalid JMX_PORT "+jmxRemotePort+" and RMI_REGISTRY_PORT "+rmiRegistryPort+" when configuring JMX "+getJmxAgentMode()+" on "+getEntity());
-            }
-            ((EntityLocal)getEntity()).setAttribute(RMI_REGISTRY_PORT, jmxRemotePort);
-        }
-        return jmxRemotePort;
-    }
-
-    public List<String> getJmxJavaConfigOptions() {
-        if (EnumSet.<JmxAgentModes>of(JmxAgentModes.NONE, JmxAgentModes.JMX_RMI).contains(getJmxAgentMode())) {
-            return MutableList.of();
-        } else {
-            return MutableList.of(String.format("-javaagent:%s", getJmxAgentJarDestinationFilePath()));
-        }
-    }
-
-    public String getJmxAgentJarDestinationFilePath() {
-        // cache the local path so we continue to work post-rebind to a different version
-        String result = getEntity().getAttribute(JMX_AGENT_LOCAL_PATH);
-        if (Strings.isNonBlank(result)) return result;
-        result = getJmxAgentJarDestinationFilePathDefault();
-        ((EntityInternal)getEntity()).setAttribute(JMX_AGENT_LOCAL_PATH, result);
-        return result;
-    }
-    
-    public String getJmxAgentJarDestinationFilePathDefault() {
-        return Urls.mergePaths(getRunDir(), getJmxAgentJarBasename());
-    }
-
-    @Nullable public MavenArtifact getJmxAgentJarMavenArtifact() {
-        switch (getJmxAgentMode()) {
-        case JMXMP:
-        case JMXMP_AND_RMI:
-            MavenArtifact result = BrooklynMavenArtifacts.artifact(null, "brooklyn-jmxmp-agent", "jar", "with-dependencies");
-            // the "with-dependencies" variant is needed; however the filename then has the classifier segment _replaced_ by "shaded" when this filename is created
-            result.setCustomFileNameAfterArtifactMarker("shaded");
-            result.setClassifierFileNameMarker("");
-            return result;
-        case JMX_RMI_CUSTOM_AGENT:
-            return BrooklynMavenArtifacts.jar("brooklyn-jmxrmi-agent");
-        default:
-            return null;
-        }
-    }
-
-    /** @deprecated since 0.6.0; use {@link #getJmxAgentJarMavenArtifact()} */
-    @Deprecated
-    public String getJmxAgentJarBasename() {
-        MavenArtifact artifact = getJmxAgentJarMavenArtifact();
-        if (artifact==null)
-            throw new IllegalStateException("Either JMX is not enabled or there is an error in the configuration (JMX mode "+getJmxAgentMode()+" does not support agent JAR)");
-        return artifact.getFilename();
-    }
-
-    /** returns URL for accessing the java agent, throwing if not applicable;
-     * prefers on classpath where it should be, but will fall back to taking from maven hosted
-     * (known problem in Eclipse where JARs are not always copied)
-     */
-    public String getJmxAgentJarUrl() {
-        MavenArtifact artifact = getJmxAgentJarMavenArtifact();
-        if (artifact==null)
-            throw new IllegalStateException("Either JMX is not enabled or there is an error in the configuration (JMX mode "+getJmxAgentMode()+" does not support agent JAR)");
-        String jar = "classpath://" + artifact.getFilename();
-        if (ResourceUtils.create(this).doesUrlExist(jar))
-            return jar;
-
-        String result = MavenRetriever.localUrl(artifact);
-        if (warnedAboutNotOnClasspath) {
-            log.debug("JMX JAR for "+artifact+" is not on the classpath; taking from "+result);
-        } else {
-            log.warn("JMX JAR for "+artifact+" is not on the classpath; taking from "+result+" (subsequent similar messages will be logged at debug)");
-            warnedAboutNotOnClasspath = true;
-        }
-        return result;
-    }
-
-    /** applies _some_ of the common settings needed to connect via JMX */
-    public void applyJmxJavaSystemProperties(MutableMap.Builder<String,Object> result) {
-        if (!isJmx()) return ;
-
-        Integer jmxPort = Preconditions.checkNotNull(entity.getAttribute(JMX_PORT), "jmx port must not be null for %s", entity);
-        HostAndPort jmx = BrooklynAccessUtils.getBrooklynAccessibleAddress(entity, jmxPort);
-        Integer jmxRemotePort = getEntity().getAttribute(JMX_PORT);
-        String hostName = jmx.getHostText();
-
-        result.put("com.sun.management.jmxremote", null);
-        result.put("java.rmi.server.hostname", hostName);
-
-        switch (getJmxAgentMode()) {
-        case JMXMP_AND_RMI:
-            Integer rmiRegistryPort = Preconditions.checkNotNull(entity.getAttribute(UsesJmx.RMI_REGISTRY_PORT), "registry port (config val %s)", entity.getConfig(UsesJmx.RMI_REGISTRY_PORT));
-            result.put(JmxmpAgent.RMI_REGISTRY_PORT_PROPERTY, rmiRegistryPort);
-        case JMXMP:
-            if (jmxRemotePort==null || jmxRemotePort<=0)
-                throw new IllegalStateException("Unsupported JMX port "+jmxRemotePort+" - when applying system properties ("+getJmxAgentMode()+" / "+getEntity()+")");
-            result.put(JmxmpAgent.JMXMP_PORT_PROPERTY, jmxRemotePort);
-            // with JMXMP don't try to tell it the hostname -- it isn't needed for JMXMP, and if specified
-            // it will break if the hostname we see is not known at the server, e.g. a forwarding public IP
-            result.remove("java.rmi.server.hostname");
-            break;
-        case JMX_RMI_CUSTOM_AGENT:
-            if (jmxRemotePort==null || jmxRemotePort<=0)
-                throw new IllegalStateException("Unsupported JMX port "+jmxRemotePort+" - when applying system properties ("+getJmxAgentMode()+" / "+getEntity()+")");
-            result.put(JmxRmiAgent.RMI_REGISTRY_PORT_PROPERTY, Preconditions.checkNotNull(entity.getAttribute(UsesJmx.RMI_REGISTRY_PORT), "registry port"));
-            result.put(JmxRmiAgent.JMX_SERVER_PORT_PROPERTY, jmxRemotePort);
-            break;
-        case NONE:
-            jmxRemotePort = fixPortsForModeNone();
-        case JMX_RMI:
-            result.put("com.sun.management.jmxremote.port", jmxRemotePort);
-            result.put("java.rmi.server.useLocalHostname", "true");
-            break;
-        default:
-            throw new IllegalStateException("Unsupported JMX mode - when applying system properties ("+getJmxAgentMode()+" / "+getEntity()+")");
-        }
-
-        if (isSecure()) {
-            // set values true, and apply keys pointing to keystore / truststore
-            getJmxSslSupport().applyAgentJmxJavaSystemProperties(result);
-        } else {
-            result.
-                put("com.sun.management.jmxremote.ssl", false).
-                put("com.sun.management.jmxremote.authenticate", false);
-        }
-    }
-
-    /** installs files needed for JMX, to the runDir given in constructor, assuming the runDir has been created */
-    public void install() {
-        if (EnumSet.of(JmxAgentModes.JMXMP_AND_RMI, JmxAgentModes.JMXMP, JmxAgentModes.JMX_RMI_CUSTOM_AGENT).contains(getJmxAgentMode())) {
-            Tasks.setBlockingDetails("Copying JMX agent jar to server.");
-            try {
-                getMachine().get().copyTo(ResourceUtils.create(this).getResourceFromUrl(
-                        getJmxAgentJarUrl()), getJmxAgentJarDestinationFilePath());
-            } finally {
-                Tasks.resetBlockingDetails();
-            }
-        }
-        if (isSecure()) {
-            getJmxSslSupport().install();
-        }
-    }
-
-    protected JmxmpSslSupport getJmxSslSupport() {
-        return new JmxmpSslSupport(this);
-    }
-
-    /** sets JMR_RMI_CUSTOM_AGENT as the connection mode for the indicated apps.
-     * <p>
-     * TODO callers of this method have RMI dependencies in the actual app;
-     * we should look at removing them, so that those pieces of software can run behind
-     * forwarding public IP's and over SSL (both reasons JMXMP is preferred by us!)
-     */
-    public void recommendJmxRmiCustomAgent() {
-        // set JMX_RMI because the registry is needed (i think)
-        Maybe<Object> jmx = entity.getConfigRaw(UsesJmx.JMX_AGENT_MODE, true);
-        if (!jmx.isPresentAndNonNull()) {
-            setConfig(UsesJmx.JMX_AGENT_MODE, JmxAgentModes.JMX_RMI_CUSTOM_AGENT);
-        } else if (jmx.get()!=JmxAgentModes.JMX_RMI_CUSTOM_AGENT) {
-            log.warn("Entity "+entity+" may not function unless running JMX_RMI_CUSTOM_AGENT mode (asked to use "+jmx.get()+")");
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/java/JmxmpSslSupport.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/java/JmxmpSslSupport.java b/software/base/src/main/java/brooklyn/entity/java/JmxmpSslSupport.java
deleted file mode 100644
index c1595b1..0000000
--- a/software/base/src/main/java/brooklyn/entity/java/JmxmpSslSupport.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.security.KeyPair;
-import java.security.KeyStore;
-import java.security.PrivateKey;
-import java.security.cert.Certificate;
-import java.security.cert.X509Certificate;
-
-import org.apache.brooklyn.util.collections.MutableMap.Builder;
-import org.apache.brooklyn.util.core.crypto.FluentKeySigner;
-import org.apache.brooklyn.util.core.crypto.SecureKeys;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.jmx.jmxmp.JmxmpAgent;
-import org.apache.brooklyn.util.net.Urls;
-
-import com.google.common.base.Preconditions;
-
-public class JmxmpSslSupport {
-
-    final static String BROOKLYN_VERSION = "0.8.0-SNAPSHOT";  // BROOKLYN_VERSION (updated by script)
-    
-    private final JmxSupport jmxSupport;
-    
-    private KeyStore agentTrustStore;
-    private KeyStore agentKeyStore;
-    
-    public JmxmpSslSupport(JmxSupport jmxSupport) {
-        this.jmxSupport = Preconditions.checkNotNull(jmxSupport);
-    }
-    
-    public String getJmxSslKeyStoreFilePath() {
-        return Urls.mergePaths(jmxSupport.getRunDir(), "jmx-keystore");
-    }
-    
-    public String getJmxSslTrustStoreFilePath() {
-        return Urls.mergePaths(jmxSupport.getRunDir(), "jmx-truststore");
-    }
-    
-    public void applyAgentJmxJavaSystemProperties(Builder<String, Object> result) {
-        result.
-            put(JmxmpAgent.USE_SSL_PROPERTY, true).
-            put(JmxmpAgent.AUTHENTICATE_CLIENTS_PROPERTY, true).
-            // the option below wants a jmxremote.password file; we use certs (above) to authenticate
-            put("com.sun.management.jmxremote.authenticate", false);
-
-        result.
-            put(JmxmpAgent.JMXMP_KEYSTORE_FILE_PROPERTY, getJmxSslKeyStoreFilePath()).
-            put(JmxmpAgent.JMXMP_TRUSTSTORE_FILE_PROPERTY, getJmxSslTrustStoreFilePath());
-    }
-
-    public FluentKeySigner getBrooklynRootSigner() {
-        // TODO use brooklyn root CA keys etc
-        return new FluentKeySigner("brooklyn-root");
-    }
-
-    /** builds remote keystores, stores config keys/certs, and copies necessary files across */
-    public void install() {
-        try {
-            // build truststore and keystore
-            FluentKeySigner signer = getBrooklynRootSigner();
-            KeyPair jmxAgentKey = SecureKeys.newKeyPair();
-            X509Certificate jmxAgentCert = signer.newCertificateFor("jmxmp-agent", jmxAgentKey);
-
-            agentKeyStore = SecureKeys.newKeyStore();
-            agentKeyStore.setKeyEntry("jmxmp-agent", jmxAgentKey.getPrivate(), 
-                    // TODO jmx.ssl.agent.keyPassword
-                    "".toCharArray(),
-                    new Certificate[] { jmxAgentCert });
-            ByteArrayOutputStream agentKeyStoreBytes = new ByteArrayOutputStream();
-            agentKeyStore.store(agentKeyStoreBytes, 
-                    // TODO jmx.ssl.agent.keyStorePassword
-                    "".toCharArray());
-            
-            agentTrustStore = SecureKeys.newKeyStore();
-            agentTrustStore.setCertificateEntry("brooklyn", getJmxAccessCert());
-            ByteArrayOutputStream agentTrustStoreBytes = new ByteArrayOutputStream();
-            agentTrustStore.store(agentTrustStoreBytes, "".toCharArray());
-            
-            // install the truststore and keystore and rely on JmxSupport to install the agent
-            Tasks.setBlockingDetails("Copying keystore and truststore to the server.");
-            try {
-                jmxSupport.getMachine().get().copyTo(new ByteArrayInputStream(agentKeyStoreBytes.toByteArray()), getJmxSslKeyStoreFilePath());
-                jmxSupport.getMachine().get().copyTo(new ByteArrayInputStream(agentTrustStoreBytes.toByteArray()), getJmxSslTrustStoreFilePath());
-            } finally {
-                Tasks.resetBlockingDetails();
-            }
-
-        } catch (Exception e) {
-            throw Exceptions.propagate(e);
-        }
-    }
-
-    public synchronized Certificate getJmxAccessCert() {
-        Certificate cert = jmxSupport.getConfig(UsesJmx.JMX_SSL_ACCESS_CERT);
-        if (cert!=null) return cert;
-        // TODO load from keyStoreUrl
-        KeyPair jmxAccessKey = SecureKeys.newKeyPair();
-        X509Certificate jmxAccessCert = getBrooklynRootSigner().newCertificateFor("brooklyn-jmx-access", jmxAccessKey);
-
-        jmxSupport.setConfig(UsesJmx.JMX_SSL_ACCESS_CERT, jmxAccessCert);
-        jmxSupport.setConfig(UsesJmx.JMX_SSL_ACCESS_KEY, jmxAccessKey.getPrivate());
-        
-        return jmxAccessCert;
-    }
-    
-    public synchronized PrivateKey getJmxAccessKey() {
-        PrivateKey key = jmxSupport.getConfig(UsesJmx.JMX_SSL_ACCESS_KEY);
-        if (key!=null) return key;
-        getJmxAccessCert();
-        return jmxSupport.getConfig(UsesJmx.JMX_SSL_ACCESS_KEY);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/java/UsesJava.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/java/UsesJava.java b/software/base/src/main/java/brooklyn/entity/java/UsesJava.java
deleted file mode 100644
index 5e0ef59..0000000
--- a/software/base/src/main/java/brooklyn/entity/java/UsesJava.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.config.MapConfigKey;
-import org.apache.brooklyn.core.config.SetConfigKey;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Maps;
-
-public interface UsesJava {
-
-    /** system properties (-D) to append to JAVA_OPTS; normally accessed through {@link JavaEntityMethods#javaSysProp(String)} */
-    @SetFromFlag("javaSysProps")
-    public static final MapConfigKey<String> JAVA_SYSPROPS = new MapConfigKey<String>(String.class,
-            "java.sysprops", "Java command line system properties", Maps.<String,String>newLinkedHashMap());
-
-    /**
-     * Used to set java options. These options are prepended to the defaults.
-     * They can also be used to override defaults. The rules for overrides are:
-     * <ul>
-     *   <li>If contains a mutually exclusive setting, then the others are removed. Those supported are:
-     *     <ul>
-     *       <li>"-client" and "-server"
-     *     </ul>
-     *   <li>If value has a well-known prefix indicating it's a key-value pair. Those supported are:
-     *     <ul>
-     *       <li>"-Xmx"
-     *       <li>"-Xms"
-     *       <li>"-Xss"
-     *     </ul>
-     *   <li>If value contains "=" then see if there's a default that matches the section up to the "=".
-     *       If there is, then remove the original and just include this.
-     *       e.g. "-XX:MaxPermSize=512m" could be overridden in this way.
-     * </ul>
-     */
-    @SetFromFlag("javaOpts")
-    public static final SetConfigKey<String> JAVA_OPTS = new SetConfigKey<String>(String.class,
-            "java.opts", "Java command line options", ImmutableSet.<String>of());
-
-    public static final ConfigKey<Boolean> CHECK_JAVA_HOSTNAME_BUG = ConfigKeys.newBooleanConfigKey(
-            "java.check.hostname.bug", "Check whether hostname is too long and will likely crash Java" +
-                    "due to bug 7089443", true);
-
-    @SetFromFlag("javaVersionRequired")
-    ConfigKey<String> JAVA_VERSION_REQUIRED = ConfigKeys.newStringConfigKey("java.version.required", "Java version required", "1.7");
-
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/java/UsesJavaMXBeans.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/java/UsesJavaMXBeans.java b/software/base/src/main/java/brooklyn/entity/java/UsesJavaMXBeans.java
deleted file mode 100644
index f122cf5..0000000
--- a/software/base/src/main/java/brooklyn/entity/java/UsesJavaMXBeans.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-
-public interface UsesJavaMXBeans {
-
-    @SetFromFlag("mxbeanStatsEnabled")
-    ConfigKey<Boolean> MXBEAN_STATS_ENABLED =
-            ConfigKeys.newBooleanConfigKey("java.metrics.mxbeanStatsEnabled", "Enables collection of JVM stats from the MXBeans, such as memory and thread usage (default is true)", true);
-
-    AttributeSensor<Long> USED_HEAP_MEMORY =
-            Sensors.newLongSensor("java.metrics.heap.used", "Current heap size (bytes)");
-    AttributeSensor<Long> INIT_HEAP_MEMORY =
-            Sensors.newLongSensor("java.metrics.heap.init", "Initial heap size (bytes)");
-    AttributeSensor<Long> COMMITTED_HEAP_MEMORY =
-            Sensors.newLongSensor("java.metrics.heap.committed", "Commited heap size (bytes)");
-    AttributeSensor<Long> MAX_HEAP_MEMORY =
-            Sensors.newLongSensor("java.metrics.heap.max", "Max heap size (bytes)");
-    AttributeSensor<Long> NON_HEAP_MEMORY_USAGE =
-            Sensors.newLongSensor("java.metrics.nonheap.used", "Current non-heap size (bytes)");
-    AttributeSensor<Integer> CURRENT_THREAD_COUNT =
-            Sensors.newIntegerSensor( "java.metrics.threads.current", "Current number of threads");
-    AttributeSensor<Integer> PEAK_THREAD_COUNT =
-            Sensors.newIntegerSensor("java.metrics.threads.max", "Peak number of threads");
-
-    // runtime system attributes
-    AttributeSensor<Long> START_TIME =
-            Sensors.newLongSensor("java.metrics.starttime", "Start time of Java process (UTC)");
-    AttributeSensor<Long> UP_TIME =
-            Sensors.newLongSensor("java.metrics.uptime", "Uptime of Java process (millis, elapsed since start)");
-    
-    //operating system attributes
-    AttributeSensor<Double> PROCESS_CPU_TIME = Sensors.newDoubleSensor( 
-            "java.metrics.processCpuTime.total", "Process CPU time (total millis since start)");
-    AttributeSensor<Double> PROCESS_CPU_TIME_FRACTION_LAST = Sensors.newDoubleSensor( 
-            "java.metrics.processCpuTime.fraction.last", "Fraction of CPU time used, reported by JVM (percentage, last datapoint)");
-    AttributeSensor<Double> PROCESS_CPU_TIME_FRACTION_IN_WINDOW = Sensors.newDoubleSensor( 
-            "java.metrics.processCpuTime.fraction.windowed", "Fraction of CPU time used, reported by JVM (percentage, over time window)");
-    
-    AttributeSensor<Integer> AVAILABLE_PROCESSORS =
-            Sensors.newIntegerSensor("java.metrics.processors.available", "number of processors available to the Java virtual machine");
-    AttributeSensor<Double> SYSTEM_LOAD_AVERAGE
-            = Sensors.newDoubleSensor("java.metrics.systemload.average", "average system load");
-    AttributeSensor<Long> TOTAL_PHYSICAL_MEMORY_SIZE =
-            Sensors.newLongSensor("java.metrics.physicalmemory.total", "The physical memory available to the operating system");
-    AttributeSensor<Long> FREE_PHYSICAL_MEMORY_SIZE =
-            Sensors.newLongSensor("java.metrics.physicalmemory.free", "The free memory available to the operating system");
-
-    // GC attributes
-    AttributeSensor<Map> GARBAGE_COLLECTION_TIME = new BasicAttributeSensor<Map>(Map.class, "java.metrics.gc.time", "garbage collection time");
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/java/UsesJmx.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/java/UsesJmx.java b/software/base/src/main/java/brooklyn/entity/java/UsesJmx.java
deleted file mode 100644
index ee8c376..0000000
--- a/software/base/src/main/java/brooklyn/entity/java/UsesJmx.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import java.security.PrivateKey;
-import java.security.cert.Certificate;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.location.PortRange;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.BasicConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.location.basic.PortRanges;
-import org.apache.brooklyn.sensor.core.AttributeSensorAndConfigKey;
-import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
-import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-
-public interface UsesJmx extends UsesJava {
-
-    public static final int DEFAULT_JMX_PORT = 1099; // RMI port?
-
-    @SetFromFlag("useJmx")
-    ConfigKey<Boolean> USE_JMX = ConfigKeys.newConfigKey("jmx.enabled", "JMX enabled", Boolean.TRUE);
-
-    /** Chosen by Java itself by default, setting this will only have any effect if using an agent. */
-    @SetFromFlag("jmxPort")
-    PortAttributeSensorAndConfigKey JMX_PORT = new PortAttributeSensorAndConfigKey(
-        "jmx.direct.port", "JMX direct/private port (e.g. JMX RMI server port, or JMXMP port, but not RMI registry port)", PortRanges.fromString("31001+"));
-    
-    // Default is deliberately null for this unused config; if we used "31001+" then we'd potentially give this sensor 
-    // the value 31001 and jmx.direct.port the value 31002. See https://issues.apache.org/jira/browse/BROOKLYN-98
-    /** @deprecated since 0.7.0, kept for rebinding with the anonymous class; code should only ever use {@link #JMX_PORT} */ @Deprecated
-    PortAttributeSensorAndConfigKey JMX_PORT_LEGACY = new PortAttributeSensorAndConfigKey(
-            "jmx.direct.port.legacy.NOT_USED", "Legacy definition JMX direct/private port (e.g. JMX RMI server port, or JMXMP port, but not RMI registry port)", null) {
-        private static final long serialVersionUID = 3846846080809179437L;
-        @Override protected Integer convertConfigToSensor(PortRange value, Entity entity) {
-            // TODO when using JmxAgentModes.NONE we should *not* convert, but leave it null
-            // (e.g. to prevent a warning in e.g. ActiveMQIntegrationTest)
-            // [there was - previously - a note about needing to move these keys to UsesJmx,
-            // that has been done, so not sure if there is anything more needed or if we can just
-            // check here entity.getConfig(JMX_AGENT_MODE) ... needs testing of course]
-            return super.convertConfigToSensor(value, entity);
-        }
-    };
-    
-    /** Well-known port used by Java itself to start the RMI registry where JMX private port can be discovered, ignored if using JMXMP agent. */
-    @SetFromFlag("rmiRegistryPort")
-    PortAttributeSensorAndConfigKey RMI_REGISTRY_PORT = ConfigKeys.newPortSensorAndConfigKey(
-            "rmi.registry.port", "RMI registry port, used for discovering JMX (private) port", PortRanges.fromString("1099,19099+"));
-
-    @SetFromFlag("jmxContext")
-    AttributeSensorAndConfigKey<String, String> JMX_CONTEXT = ConfigKeys.newStringSensorAndConfigKey("jmx.context", "JMX context path", "jmxrmi");
-
-    AttributeSensor<String> JMX_URL = new BasicAttributeSensorAndConfigKey<String>(
-            String.class, "jmx.service.url", "The URL for connecting to the MBean Server");
-
-    /** Forces JMX to be secured, using JMXMP so it gets through firewalls <em>and</em> SSL/TLS. */
-    @SetFromFlag("jmxSecure")
-    ConfigKey<Boolean> JMX_SSL_ENABLED = ConfigKeys.newBooleanConfigKey("jmx.ssl.enabled", "JMX over JMXMP enabled with SSL/TLS", Boolean.FALSE);
-
-    enum JmxAgentModes {
-        /** Auto-detect the agent to use based on location. Prefer {@link #JMXMP} except at localhost which uses {@link #JMX_RMI_CUSTOM_AGENT}. */
-        AUTODETECT,
-
-        /** JMXMP which permits firewall access through a single port {@link UsesJmx#JMX_PORT}. */
-        JMXMP,
-
-        /** Start {@link #JMXMP} along with an RMI Registry on {@link UsesJmx#RMI_REGISTRY_PORT}, redirecting to an anonymous high-numbered port as the RMI server. */
-        JMXMP_AND_RMI,
-
-        /** JMX over RMI custom agent which permits access through a known {@link UsesJmx#RMI_REGISTRY_PORT}, redirected to a known {@link UsesJmx#JMX_PORT}.
-         * Both ports must be opened on the firewall, and the same hostname resolvable on the target machine and by the client */
-        JMX_RMI_CUSTOM_AGENT,
-
-        /** As with {@link UsesJmx#JMX_RMI_CUSTOM_AGENT} but no custom agent requred, entity must handle pots correctly.  */
-        JMX_RMI,
-
-        /** Do not install a JMX agent. Use the default {@link UsesJmx#RMI_REGISTRY_PORT}, redirected to an unknown port for JMX. */
-        NONE
-    }
-
-    @SetFromFlag("jmxAgentMode")
-    ConfigKey<JmxAgentModes> JMX_AGENT_MODE = ConfigKeys.newConfigKey("jmx.agent.mode",
-            "What type of JMX agent to use; defaults to null (autodetect) which means " +
-            "JMXMP_AND_RMI allowing firewall access through a single port as well as local access supporting jconsole " +
-            "(unless JMX_SSL_ENABLED is set, in which case it is JMXMP only)",
-            JmxAgentModes.AUTODETECT);
-
-    /* Currently these are only used to connect, so only applies where systems set this up themselves. */
-    AttributeSensorAndConfigKey<String, String> JMX_USER = ConfigKeys.newStringSensorAndConfigKey("jmx.user", "JMX username");
-    AttributeSensorAndConfigKey<String, String> JMX_PASSWORD = ConfigKeys.newStringSensorAndConfigKey("jmx.password", "JMX password");
-    
-    AttributeSensorAndConfigKey<String, String> JMX_AGENT_LOCAL_PATH = ConfigKeys.newStringSensorAndConfigKey("jmx.agent.local.path", "Path to JMX driver on the local machine");
-
-    /*
-     * Synopsis of how the keys work for JMX_SSL:
-     *
-     * BROOKLYN
-     *  * brooklyn ROOT key + cert ->
-     *      used to identify things brooklyn has signed, ie to confirm their identity
-     *      signs all certs created by brooklyn
-     *      (created per entity if not specified as input)
-     *  * brooklyn JMX ACCESS key + cert ->
-     *      used to authenticate brooklyn to remote JMX agent
-     *      typically, but not necessarily, signed by ROOT cert
-     *      (typically created per entity, unless specified;
-     *      global would probably be fine but more work;
-     *      however it is important that this _not_ sign agents keys,
-     *      to prevent agents from accessing other agents)
-     *
-     * AGENT (e.g. JMX server in each managed java process)
-     *  * gets AGENT key + cert ->
-     *      signed by brooklyn ROOT, used to authenticate itself to brooklyn
-     *      (brooklyn trusts this; does not need to remember this)
-     *  * trusts only the relevant brooklyn JMX ACCESS key (its truststore contains that cert)
-     */
-
-    /* TODO brooklyn ROOT key
-     *
-    public static final ConfigKey<String> BROOKLYN_SSL_ROOT_KEYSTORE_URL = new BasicConfigKey<String>(
-            String.class, "brooklyn.ssl.root.keyStoreUrl", "URL to keystore Brooklyn should use as root private key and certificate-signing authority", null);
-
-    public static final ConfigKey<String> BROOKLYN_SSL_ROOT_KEY_DATA = new BasicConfigKey<String>(
-            String.class, "brooklyn.ssl.root.key", "root private key (RSA string format), used to sign managed servers", null);
-    public static final ConfigKey<String> BROOKLYN_SSL_ROOT_CERT_DATA = new BasicConfigKey<String>(
-            String.class, "brooklyn.ssl.root.cert", "certificate for root private key (RSA string format)", null);
-
-     * brooklyn.ssl.root.keyStorePassword
-     * brooklyn.ssl.root.keyAlias (if null, looks for one called 'brooklyn', otherwise takes the first key)
-     * brooklyn.ssl.root.keyPassword
-     */
-
-    public static final ConfigKey<PrivateKey> JMX_SSL_ACCESS_KEY = new BasicConfigKey<PrivateKey>(
-            PrivateKey.class, "jmx.ssl.access.key", "key used to access a JMX agent (typically per entity, embedded in the managed JVM)", null);
-    public static final ConfigKey<Certificate> JMX_SSL_ACCESS_CERT = new BasicConfigKey<Certificate>(
-            Certificate.class, "jmx.ssl.access.cert", "certificate of key used to access a JMX agent", null);
-
-    /* TODO specify a keystore from which to get the access key
-     * (above keys are set programmatically, typically _not_ by the user ... keystore would be the way to do that)
-     *
-     * jmx.ssl.access.keyStoreUrl (optional)
-     * jmx.ssl.access.keyStorePassword (optional)
-     * jmx.ssl.access.keyAlias (optional)
-     */
-
-    /* could allow user to specify additional certs for JMX agents which should be trusted
-     *
-     * jmx.ssl.access.trustStoreUrl
-     */
-
-    /* optionally: could allow JMX agent to trust additional accessers,
-     * and/or use known keys in the case that other accessers might want to authenticate the JMX server
-     *
-     * NB currently agent keys are not stored in brooklyn... no reason to as
-     * (a) currently we trust jmx agents; and (b) for agent-auth we should simply sign keys;
-     * either way, seems fine for brooklyn to throw them away once they are installed on the remote machine)
-     *
-     * jmx.ssl.agent.keyStoreUrl
-     * jmx.ssl.agent.keyStorePassword
-     * jmx.ssl.agent.keyAlias
-     * jmx.ssl.agent.keyPassword
-     *
-     * jmx.ssl.agent.trustStoreUrl
-     */
-
-    /* optionally: this could be set to disallow attaching to JMX through the attach mechanism
-     * (but this option is generally not considered needed, as JVM attachment is
-     * already restricted to localhost and to the the user running the process)
-     *
-     * -XX:+DisableAttachMechanism
-     */
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/java/VanillaJavaApp.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/java/VanillaJavaApp.java b/software/base/src/main/java/brooklyn/entity/java/VanillaJavaApp.java
deleted file mode 100644
index eb62d62..0000000
--- a/software/base/src/main/java/brooklyn/entity/java/VanillaJavaApp.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-
-@ImplementedBy(VanillaJavaAppImpl.class)
-public interface VanillaJavaApp extends SoftwareProcess, UsesJava, UsesJmx, UsesJavaMXBeans {
-
-    // TODO Make jmxPollPeriod @SetFromFlag easier to use: currently a confusion over long and TimeDuration, and 
-    // no ability to set default value (can't just set field because config vals read/set in super-constructor :-(
-
-    @SetFromFlag("args")
-    ConfigKey<List> ARGS = ConfigKeys.newConfigKey(List.class,
-            "vanillaJavaApp.args", "Arguments for launching the java app", Lists.newArrayList());
-    
-    @SetFromFlag(value="main", nullable=false)
-    ConfigKey<String> MAIN_CLASS = ConfigKeys.newStringConfigKey("vanillaJavaApp.mainClass", "class to launch");
-
-    @SetFromFlag("classpath")
-    ConfigKey<List> CLASSPATH = ConfigKeys.newConfigKey(List.class,
-            "vanillaJavaApp.classpath", "classpath to use, as list of URL entries; " +
-            "these URLs are copied to lib/ and expanded in the case of tar/tgz/zip",
-            Lists.newArrayList());
-
-    AttributeSensor<List> CLASSPATH_FILES = Sensors.newSensor(List.class,
-            "vanillaJavaApp.classpathFiles", "classpath used, list of files");
-
-    @SetFromFlag("jvmXArgs")
-    ConfigKey<List> JVM_XARGS = ConfigKeys.newConfigKey(List.class,
-            "vanillaJavaApp.jvmXArgs", "JVM -X args for the java app (e.g. memory)", 
-            MutableList.of("-Xms128m", "-Xmx512m", "-XX:MaxPermSize=512m"));
-
-    @SetFromFlag("jvmDefines")
-    ConfigKey<Map> JVM_DEFINES = ConfigKeys.newConfigKey(Map.class,
-            "vanillaJavaApp.jvmDefines", "JVM system property definitions for the app",
-            Maps.newLinkedHashMap());
-
-    public String getMainClass();
-    public List<String> getClasspath();
-    public List<String> getClasspathFiles();
-    public Map getJvmDefines();
-    public List getJvmXArgs();
-    public String getRunDir();
-
-    public void kill();
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/java/VanillaJavaAppDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/java/VanillaJavaAppDriver.java b/software/base/src/main/java/brooklyn/entity/java/VanillaJavaAppDriver.java
deleted file mode 100644
index b538d48..0000000
--- a/software/base/src/main/java/brooklyn/entity/java/VanillaJavaAppDriver.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-/**
- * The {@link JavaSoftwareProcessDriver} for a {@link VanillaJavaApp}.
- */
-public interface VanillaJavaAppDriver extends JavaSoftwareProcessDriver {
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/java/VanillaJavaAppImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/java/VanillaJavaAppImpl.java b/software/base/src/main/java/brooklyn/entity/java/VanillaJavaAppImpl.java
deleted file mode 100644
index 856dcd1..0000000
--- a/software/base/src/main/java/brooklyn/entity/java/VanillaJavaAppImpl.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcessImpl;
-import brooklyn.event.feed.jmx.JmxFeed;
-
-import com.google.common.annotations.VisibleForTesting;
-
-public class VanillaJavaAppImpl extends SoftwareProcessImpl implements VanillaJavaApp {
-
-    static {
-        JavaAppUtils.init();
-    }
-
-    private static final Logger log = LoggerFactory.getLogger(VanillaJavaApp.class);
-
-    @SetFromFlag
-    protected long jmxPollPeriod;
-
-    protected JmxFeed jmxFeed;
-
-    public VanillaJavaAppImpl() {}
-
-    @VisibleForTesting
-    public VanillaJavaAppImpl(Map<?,?> properties, Entity parent) {
-        super(properties, parent);
-    }
-
-    public String getMainClass() { return getConfig(MAIN_CLASS); }
-    public List<String> getClasspath() { return getConfig(CLASSPATH); }
-    public List<String> getClasspathFiles() { return getAttribute(CLASSPATH_FILES); }
-    public Map getJvmDefines() { return getConfig(JVM_DEFINES); }
-    public List getJvmXArgs() { return getConfig(JVM_XARGS); }
-
-    public void addToClasspath(String url) {
-        List<String> cp = getConfig(CLASSPATH);
-        List<String> newCP = new ArrayList<String>();
-        if (cp!=null) newCP.addAll(cp);
-        newCP.add(url);
-        setConfig(CLASSPATH, newCP);
-    }
-
-    public void addToClasspath(Collection<String> urls) {
-        List<String> cp = getConfig(CLASSPATH);
-        List<String> newCP = new ArrayList<String>();
-        if (cp!=null) newCP.addAll(cp);
-        newCP.addAll(urls);
-        setConfig(CLASSPATH, newCP);
-    }
-
-    @Override
-    protected void connectSensors() {
-        super.connectSensors();
-
-        if (((VanillaJavaAppDriver) getDriver()).isJmxEnabled()) {
-            jmxPollPeriod = (jmxPollPeriod > 0) ? jmxPollPeriod : 3000;
-            jmxFeed = JavaAppUtils.connectMXBeanSensors(this, jmxPollPeriod);
-        }
-
-        connectServiceUpIsRunning();
-    }
-
-    @Override
-    public void disconnectSensors() {
-        super.disconnectSensors();
-        disconnectServiceUpIsRunning();
-        if (jmxFeed != null) jmxFeed.stop();
-    }
-
-    @Override
-    public Class<? extends VanillaJavaAppDriver> getDriverInterface() {
-        return VanillaJavaAppDriver.class;
-    }
-
-    public String getRunDir() {
-        // FIXME Make this an attribute; don't assume it hsa to be ssh? What uses this?
-        VanillaJavaAppSshDriver driver = (VanillaJavaAppSshDriver) getDriver();
-        return (driver != null) ? driver.getRunDir() : null;
-    }
-
-    @Override
-    public void kill() {
-        getDriver().kill();
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/java/VanillaJavaAppSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/java/VanillaJavaAppSshDriver.java b/software/base/src/main/java/brooklyn/entity/java/VanillaJavaAppSshDriver.java
deleted file mode 100644
index 757bbb4..0000000
--- a/software/base/src/main/java/brooklyn/entity/java/VanillaJavaAppSshDriver.java
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.java;
-
-import static java.lang.String.format;
-
-import java.io.File;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.annotation.Nullable;
-
-import brooklyn.entity.basic.lifecycle.ScriptHelper;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.file.ArchiveBuilder;
-import org.apache.brooklyn.util.core.file.ArchiveUtils;
-import org.apache.brooklyn.util.core.internal.ssh.SshTool;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.text.StringEscapes.BashStringEscapes;
-
-import com.google.common.base.CharMatcher;
-import com.google.common.base.Function;
-import com.google.common.base.Joiner;
-import com.google.common.base.Splitter;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-
-/**
- * The SSH implementation of the {@link VanillaJavaAppDriver}.
- */
-public class VanillaJavaAppSshDriver extends JavaSoftwareProcessSshDriver implements VanillaJavaAppDriver {
-
-    // FIXME this should be a config, either on the entity or -- probably better -- 
-    // an alternative / override timeout on the SshTool for file copy commands
-    final static int NUM_RETRIES_FOR_COPYING = 4;
-    
-    public VanillaJavaAppSshDriver(VanillaJavaAppImpl entity, SshMachineLocation machine) {
-        super(entity, machine);
-    }
-
-    @Override
-    public VanillaJavaAppImpl getEntity() {
-        return (VanillaJavaAppImpl) super.getEntity();
-    }
-
-    @Override
-    protected String getLogFileLocation() {
-        return Os.mergePathsUnix(getRunDir(), "console");
-    }
-
-    @Override
-    public void install() {
-        newScript(INSTALLING).execute();
-    }
-
-    @Override
-    public void customize() {
-        newScript(CUSTOMIZING)
-                .body.append(format("mkdir -p %s/lib", getRunDir()))
-                .failOnNonZeroResultCode()
-                .execute();
-
-        SshMachineLocation machine = getMachine();
-        VanillaJavaApp entity = getEntity();
-        for (String entry : entity.getClasspath()) {
-            // If a local folder, then create archive from contents first
-            if (Urls.isDirectory(entry)) {
-                File jarFile = ArchiveBuilder.jar().addDirContentsAt(new File(entry), "").create();
-                entry = jarFile.getAbsolutePath();
-            }
-
-            // Determine filename
-            String destFile = entry.contains("?") ? entry.substring(0, entry.indexOf('?')) : entry;
-            destFile = destFile.substring(destFile.lastIndexOf('/') + 1);
-
-            ArchiveUtils.deploy(MutableMap.<String, Object>of(), entry, machine, getRunDir(), Os.mergePaths(getRunDir(), "lib"), destFile);
-        }
-
-        ScriptHelper helper = newScript(CUSTOMIZING+"-classpath")
-                .body.append(String.format("ls -1 \"%s\"", Os.mergePaths(getRunDir(), "lib")))
-                .gatherOutput();
-        helper.setFlag(SshTool.PROP_NO_EXTRA_OUTPUT, true);
-        int result = helper.execute();
-        if (result != 0) {
-            throw new IllegalStateException("Error listing classpath files: " + helper.getResultStderr());
-        }
-        String stdout = helper.getResultStdout();
-
-        // Transform stdout into list of files in classpath
-        if (Strings.isBlank(stdout)) {
-            getEntity().setAttribute(VanillaJavaApp.CLASSPATH_FILES, ImmutableList.of(Os.mergePaths(getRunDir(), "lib")));
-        } else {
-            // FIXME Cannot handle spaces in paths properly
-            Iterable<String> lines = Splitter.on(CharMatcher.BREAKING_WHITESPACE).omitEmptyStrings().trimResults().split(stdout);
-            Iterable<String> files = Iterables.transform(lines, new Function<String, String>() {
-                        @Override
-                        public String apply(@Nullable String input) {
-                            return Os.mergePathsUnix(getRunDir(), "lib", input);
-                        }
-                    });
-            getEntity().setAttribute(VanillaJavaApp.CLASSPATH_FILES, ImmutableList.copyOf(files));
-        }
-    }
-
-    public String getClasspath() {
-        @SuppressWarnings("unchecked")
-        List<String> files = getEntity().getAttribute(VanillaJavaApp.CLASSPATH_FILES);
-        if (files == null || files.isEmpty()) {
-            return null;
-        } else {
-            return Joiner.on(":").join(files);
-        }
-    }
-
-    @Override
-    public void launch() {
-        String clazz = getEntity().getMainClass();
-        String args = getArgs();
-
-        newScript(MutableMap.of(USE_PID_FILE, true), LAUNCHING)
-            .body.append(
-                    format("echo \"launching: java $JAVA_OPTS %s %s\"", clazz, args),
-                    format("java $JAVA_OPTS -cp \"%s\" %s %s >> %s/console 2>&1 </dev/null &", getClasspath(), clazz, args, getRunDir())
-                )
-            .execute();
-    }
-
-    public String getArgs(){
-        List<Object> args = getEntity().getConfig(VanillaJavaApp.ARGS);
-        StringBuilder sb = new StringBuilder();
-        Iterator<Object> it = args.iterator();
-        while (it.hasNext()) {
-            Object argO = it.next();
-            try {
-                String arg = Tasks.resolveValue(argO, String.class, getEntity().getExecutionContext());
-                BashStringEscapes.assertValidForDoubleQuotingInBash(arg);
-                sb.append(format("\"%s\"",arg));
-            } catch (Exception e) {
-                throw Exceptions.propagate(e);
-            }
-            if (it.hasNext()) {
-                sb.append(" ");
-            }
-        }
-
-        return sb.toString();
-    }
-
-    @Override
-    public boolean isRunning() {
-        int result = newScript(MutableMap.of(USE_PID_FILE, true), CHECK_RUNNING).execute();
-        return result == 0;
-    }
-
-    @Override
-    public void stop() {
-        newScript(MutableMap.of(USE_PID_FILE, true), STOPPING).execute();
-    }
-
-    @Override
-    public void kill() {
-        newScript(MutableMap.of(USE_PID_FILE, true), KILLING).execute();
-    }
-
-    @Override
-    protected Map getCustomJavaSystemProperties() {
-        return MutableMap.builder()
-                .putAll(super.getCustomJavaSystemProperties())
-                .putAll(getEntity().getJvmDefines())
-                .build();
-    }
-
-    @Override
-    protected List<String> getCustomJavaConfigOptions() {
-        return MutableList.<String>builder()
-                .addAll(super.getCustomJavaConfigOptions())
-                .addAll(getEntity().getJvmXArgs())
-                .build();
-    }
-
-    @Override
-    public Map<String,String> getShellEnvironment() {
-        return MutableMap.<String,String>builder()
-                .putAll(super.getShellEnvironment())
-                .putIfNotNull("CLASSPATH", getClasspath())
-                .build();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/machine/MachineAttributes.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/machine/MachineAttributes.java b/software/base/src/main/java/brooklyn/entity/machine/MachineAttributes.java
deleted file mode 100644
index f1e780e..0000000
--- a/software/base/src/main/java/brooklyn/entity/machine/MachineAttributes.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.machine;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.core.config.render.RendererHints;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.util.guava.Functionals;
-import org.apache.brooklyn.util.math.MathFunctions;
-import org.apache.brooklyn.util.text.ByteSizeStrings;
-import org.apache.brooklyn.util.time.Duration;
-
-import com.google.common.base.Function;
-
-public class MachineAttributes {
-
-    /**
-     * Do not instantiate.
-     */
-    private MachineAttributes() {}
-
-    /*
-     * Sensor attributes for machines.
-     */
-
-    public static final AttributeSensor<Duration> UPTIME = Sensors.newSensor(Duration.class, "machine.uptime", "Current uptime");
-    public static final AttributeSensor<Double> LOAD_AVERAGE = Sensors.newDoubleSensor("machine.loadAverage", "Current load average");
-
-    public static final AttributeSensor<Double> CPU_USAGE = Sensors.newDoubleSensor("machine.cpu", "Current CPU usage");
-    public static final AttributeSensor<Double> AVERAGE_CPU_USAGE = Sensors.newDoubleSensor("cpu.average", "Average CPU usage across the cluster");
-
-    public static final AttributeSensor<Long> FREE_MEMORY = Sensors.newLongSensor("machine.memory.free", "Current free memory");
-    public static final AttributeSensor<Long> TOTAL_MEMORY = Sensors.newLongSensor("machine.memory.total", "Total memory");
-    public static final AttributeSensor<Long> USED_MEMORY = Sensors.newLongSensor("machine.memory.used", "Current memory usage");
-    public static final AttributeSensor<Double> USED_MEMORY_DELTA_PER_SECOND_LAST = Sensors.newDoubleSensor("memory.used.delta", "Change in memory usage per second");
-    public static final AttributeSensor<Double> USED_MEMORY_DELTA_PER_SECOND_IN_WINDOW = Sensors.newDoubleSensor("memory.used.windowed", "Average change in memory usage over 30s");
-
-    private static AtomicBoolean initialized = new AtomicBoolean(false);
-
-    /**
-     * Setup renderer hints.
-     */
-    public static void init() {
-        if (initialized.getAndSet(true)) return;
-
-        final Function<Double, Long> longValue = new Function<Double, Long>() {
-            @Override
-            public Long apply(@Nullable Double input) {
-                if (input == null) return null;
-                return input.longValue();
-            }
-        };
-
-        RendererHints.register(CPU_USAGE, RendererHints.displayValue(MathFunctions.percent(2)));
-        RendererHints.register(AVERAGE_CPU_USAGE, RendererHints.displayValue(MathFunctions.percent(2)));
-
-        RendererHints.register(FREE_MEMORY, RendererHints.displayValue(Functionals.chain(MathFunctions.times(1000L), ByteSizeStrings.metric())));
-        RendererHints.register(TOTAL_MEMORY, RendererHints.displayValue(Functionals.chain(MathFunctions.times(1000L), ByteSizeStrings.metric())));
-        RendererHints.register(USED_MEMORY, RendererHints.displayValue(Functionals.chain(MathFunctions.times(1000L), ByteSizeStrings.metric())));
-        RendererHints.register(USED_MEMORY_DELTA_PER_SECOND_LAST, RendererHints.displayValue(Functionals.chain(longValue, ByteSizeStrings.metric())));
-        RendererHints.register(USED_MEMORY_DELTA_PER_SECOND_IN_WINDOW, RendererHints.displayValue(Functionals.chain(longValue, ByteSizeStrings.metric())));
-    }
-
-    static {
-        init();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/machine/MachineEntity.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/machine/MachineEntity.java b/software/base/src/main/java/brooklyn/entity/machine/MachineEntity.java
deleted file mode 100644
index 46c4515..0000000
--- a/software/base/src/main/java/brooklyn/entity/machine/MachineEntity.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.machine;
-
-import org.apache.brooklyn.api.catalog.Catalog;
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.effector.core.MethodEffector;
-import org.apache.brooklyn.entity.annotation.Effector;
-import org.apache.brooklyn.entity.annotation.EffectorParam;
-import org.apache.brooklyn.util.time.Duration;
-
-import brooklyn.entity.basic.EmptySoftwareProcess;
-
-@Catalog(name="Machine Entity", description="Represents a machine, providing metrics about it (e.g. obtained from ssh)")
-@ImplementedBy(MachineEntityImpl.class)
-public interface MachineEntity extends EmptySoftwareProcess {
-
-    AttributeSensor<Duration> UPTIME = MachineAttributes.UPTIME;
-    AttributeSensor<Double> LOAD_AVERAGE = MachineAttributes.LOAD_AVERAGE;
-    AttributeSensor<Double> CPU_USAGE = MachineAttributes.CPU_USAGE;
-    AttributeSensor<Long> FREE_MEMORY = MachineAttributes.FREE_MEMORY;
-    AttributeSensor<Long> TOTAL_MEMORY = MachineAttributes.TOTAL_MEMORY;
-    AttributeSensor<Long> USED_MEMORY = MachineAttributes.USED_MEMORY;
-
-    MethodEffector<String> EXEC_COMMAND = new MethodEffector<String>(MachineEntity.class, "execCommand");
-    MethodEffector<String> EXEC_COMMAND_TIMEOUT = new MethodEffector<String>(MachineEntity.class, "execCommandTimeout");
-
-    /**
-     * Execute a command and return the output.
-     */
-    @Effector(description = "Execute a command and return the output")
-    String execCommand(
-            @EffectorParam(name = "command", description = "Command") String command);
-
-    /**
-     * Execute a command and return the output, or throw an exception after a timeout.
-     */
-    @Effector(description = "Execute a command and return the output")
-    String execCommandTimeout(
-            @EffectorParam(name = "command", description = "Command") String command,
-            @EffectorParam(name = "timeout", description = "Timeout") Duration timeout);
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/machine/MachineEntityImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/machine/MachineEntityImpl.java b/software/base/src/main/java/brooklyn/entity/machine/MachineEntityImpl.java
deleted file mode 100644
index 7b86248..0000000
--- a/software/base/src/main/java/brooklyn/entity/machine/MachineEntityImpl.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.machine;
-
-import java.util.List;
-import java.util.concurrent.TimeoutException;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-import brooklyn.entity.basic.EmptySoftwareProcessDriver;
-import brooklyn.entity.basic.EmptySoftwareProcessImpl;
-import brooklyn.entity.software.SshEffectorTasks;
-
-import org.apache.brooklyn.location.basic.Machines;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.sensor.feed.ssh.SshFeed;
-import org.apache.brooklyn.sensor.feed.ssh.SshPollConfig;
-import org.apache.brooklyn.sensor.feed.ssh.SshPollValue;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.time.Duration;
-
-import com.google.common.base.Function;
-import com.google.common.base.Functions;
-import com.google.common.base.Splitter;
-
-public class MachineEntityImpl extends EmptySoftwareProcessImpl implements MachineEntity {
-
-    private static final Logger LOG = LoggerFactory.getLogger(MachineEntityImpl.class);
-
-    static {
-        MachineAttributes.init();
-    }
-
-    private transient SshFeed sensorFeed;
-
-    @Override
-    public void init() {
-        LOG.info("Starting server pool machine with id {}", getId());
-        super.init();
-    }
-
-    @Override
-    protected void connectSensors() {
-        super.connectSensors();
-
-        // Sensors linux-specific
-        if (!getMachine().getMachineDetails().getOsDetails().isLinux()) return;
-
-        sensorFeed = SshFeed.builder()
-                .entity(this)
-                .period(Duration.THIRTY_SECONDS)
-                .poll(new SshPollConfig<Duration>(UPTIME)
-                        .command("cat /proc/uptime")
-                        .onFailureOrException(Functions.<Duration>constant(null))
-                        .onSuccess(new Function<SshPollValue, Duration>() {
-                            @Override
-                            public Duration apply(SshPollValue input) {
-                                return Duration.seconds( Double.valueOf( Strings.getFirstWord(input.getStdout()) ) );
-                            }
-                        }))
-                .poll(new SshPollConfig<Double>(LOAD_AVERAGE)
-                        .command("uptime")
-                        .onFailureOrException(Functions.constant(-1d))
-                        .onSuccess(new Function<SshPollValue, Double>() {
-                            @Override
-                            public Double apply(SshPollValue input) {
-                                String loadAverage = Strings.getFirstWordAfter(input.getStdout(), "load average:").replace(",", "");
-                                return Double.valueOf(loadAverage);
-                            }
-                        }))
-                .poll(new SshPollConfig<Double>(CPU_USAGE)
-                        .command("cat /proc/stat")
-                        .onFailureOrException(Functions.constant(-1d))
-                        .onSuccess(new Function<SshPollValue, Double>() {
-                            @Override
-                            public Double apply(SshPollValue input) {
-                                List<String> cpuData = Splitter.on(" ").omitEmptyStrings().splitToList(Strings.getFirstLine(input.getStdout()));
-                                Integer system = Integer.parseInt(cpuData.get(1));
-                                Integer user = Integer.parseInt(cpuData.get(3));
-                                Integer idle = Integer.parseInt(cpuData.get(4));
-                                return (double) (system + user) / (double) (system + user + idle);
-                            }
-                        }))
-                .poll(new SshPollConfig<Long>(USED_MEMORY)
-                        .command("free | grep Mem:")
-                        .onFailureOrException(Functions.constant(-1L))
-                        .onSuccess(new Function<SshPollValue, Long>() {
-                            @Override
-                            public Long apply(SshPollValue input) {
-                                List<String> memoryData = Splitter.on(" ").omitEmptyStrings().splitToList(Strings.getFirstLine(input.getStdout()));
-                                return Long.parseLong(memoryData.get(2));
-                            }
-                        }))
-                .poll(new SshPollConfig<Long>(FREE_MEMORY)
-                        .command("free | grep Mem:")
-                        .onFailureOrException(Functions.constant(-1L))
-                        .onSuccess(new Function<SshPollValue, Long>() {
-                            @Override
-                            public Long apply(SshPollValue input) {
-                                List<String> memoryData = Splitter.on(" ").omitEmptyStrings().splitToList(Strings.getFirstLine(input.getStdout()));
-                                return Long.parseLong(memoryData.get(3));
-                            }
-                        }))
-                .poll(new SshPollConfig<Long>(TOTAL_MEMORY)
-                        .command("free | grep Mem:")
-                        .onFailureOrException(Functions.constant(-1L))
-                        .onSuccess(new Function<SshPollValue, Long>() {
-                            @Override
-                            public Long apply(SshPollValue input) {
-                                List<String> memoryData = Splitter.on(" ").omitEmptyStrings().splitToList(Strings.getFirstLine(input.getStdout()));
-                                return Long.parseLong(memoryData.get(1));
-                            }
-                        }))
-                .build();
-
-    }
-
-    @Override
-    public void disconnectSensors() {
-        if (sensorFeed != null) sensorFeed.stop();
-        super.disconnectSensors();
-    }
-
-    @Override
-    public Class<?> getDriverInterface() {
-        return EmptySoftwareProcessDriver.class;
-    }
-
-    public SshMachineLocation getMachine() {
-        return Machines.findUniqueSshMachineLocation(getLocations()).get();
-    }
-
-    @Override
-    public String execCommand(String command) {
-        return execCommandTimeout(command, Duration.ONE_MINUTE);
-    }
-
-    @Override
-    public String execCommandTimeout(String command, Duration timeout) {
-        ProcessTaskWrapper<String> task = SshEffectorTasks.ssh(command)
-                .environmentVariables(((AbstractSoftwareProcessSshDriver) getDriver()).getShellEnvironment())
-                .requiringZeroAndReturningStdout()
-                .machine(getMachine())
-                .summary(command)
-                .newTask();
-
-        try {
-            String result = DynamicTasks.queueIfPossible(task)
-                    .executionContext(this)
-                    .orSubmitAsync()
-                    .asTask()
-                    .get(timeout);
-            return result;
-        } catch (TimeoutException te) {
-            throw new IllegalStateException("Timed out running command: " + command);
-        } catch (Exception e) {
-            Integer exitCode = task.getExitCode();
-            LOG.warn("Command failed, return code {}: {}", exitCode == null ? -1 : exitCode, task.getStderr());
-            throw Exceptions.propagate(e);
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/pool/ServerPool.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/pool/ServerPool.java b/software/base/src/main/java/brooklyn/entity/pool/ServerPool.java
deleted file mode 100644
index 7ee1f67..0000000
--- a/software/base/src/main/java/brooklyn/entity/pool/ServerPool.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.pool;
-
-import java.util.Collection;
-import java.util.Map;
-
-import com.google.common.annotations.Beta;
-
-import org.apache.brooklyn.api.catalog.Catalog;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.effector.core.MethodEffector;
-import org.apache.brooklyn.entity.annotation.Effector;
-import org.apache.brooklyn.entity.annotation.EffectorParam;
-import org.apache.brooklyn.entity.group.DynamicCluster;
-
-import brooklyn.entity.machine.MachineEntity;
-
-import org.apache.brooklyn.location.cloud.CloudLocationConfig;
-import org.apache.brooklyn.location.dynamic.LocationOwner;
-import org.apache.brooklyn.sensor.core.Sensors;
-
-/**
- * A preallocated server pool is an entity that other applications can deploy to.
- * Behaving as a cluster, the machines it creates for its members are reused.
- * <p/>
- * Notes:
- * <ul>
- *     <li>
- *         The pool does not configure ports appropriately for applications subsequently
- *         deployed. If an entity that is to be run in the pool requires any ports open
- *         other than port 22 then thoses port should be configured with the
- *         {@link CloudLocationConfig#INBOUND_PORTS INBOUND_PORTS}
- *         config key as part of the pool's
- *         {@link brooklyn.entity.basic.SoftwareProcess#PROVISIONING_PROPERTIES PROVISIONING_PROPERTIES}.
- *         For example, in YAML:
- *         <pre>
- *     - type: brooklyn.entity.pool.ServerPool
- *       brooklyn.config:
- *         # Suitable for TomcatServers
- *         provisioning.properties:
- *         inboundPorts: [22, 31880, 8443, 8080, 31001, 1099]
- *         </pre>
- *         This is a limitation of Brooklyn that will be addressed in a future release.
- *     </li>
- * </ul>
- */
-@Catalog(name="Server Pool", description="Creates a pre-allocated server pool, which other applications can deploy to")
-@ImplementedBy(ServerPoolImpl.class)
-@Beta
-public interface ServerPool extends DynamicCluster, LocationOwner<ServerPoolLocation, ServerPool> {
-
-    ConfigKey<Integer> INITIAL_SIZE = ConfigKeys.newConfigKeyWithDefault(DynamicCluster.INITIAL_SIZE, 2);
-
-    AttributeSensor<Integer> AVAILABLE_COUNT = Sensors.newIntegerSensor(
-            "pool.available", "The number of locations in the pool that are unused");
-
-    AttributeSensor<Integer> CLAIMED_COUNT = Sensors.newIntegerSensor(
-            "pool.claimed", "The number of locations in the pool that are in use");
-
-    ConfigKey<EntitySpec<?>> MEMBER_SPEC = ConfigKeys.newConfigKeyWithDefault(DynamicCluster.MEMBER_SPEC,
-            EntitySpec.create(MachineEntity.class));
-
-    MethodEffector<Collection<Entity>> ADD_MACHINES_FROM_SPEC = new MethodEffector<Collection<Entity>>(ServerPool.class, "addExistingMachinesFromSpec");
-
-    public MachineLocation claimMachine(Map<?, ?> flags) throws NoMachinesAvailableException;
-
-    public void releaseMachine(MachineLocation machine);
-
-    /**
-     * Sets the pool to use an existing {@link MachineLocation} as a member. Existing locations
-     * will count towards the capacity of the pool but will not be terminated when the pool is
-     * stopped.
-     * @param machine An existing machine.
-     * @return the new member of the pool, created with the configured {@link #MEMBER_SPEC}.
-     */
-    public Entity addExistingMachine(MachineLocation machine);
-
-    /**
-     * Adds additional machines to the pool by resolving the given spec.
-     * @param spec
-     *          A location spec, e.g. <code>byon:(hosts="user@10.9.1.1,user@10.9.1.2,user@10.9.1.3")</code>
-     * @return the new members of the pool, created with the configured {@link #MEMBER_SPEC}.
-     */
-    @Effector(description = "Adds additional machines to the pool by resolving the given spec.")
-    public Collection<Entity> addExistingMachinesFromSpec(
-            @EffectorParam(name = "spec", description = "Spec") String spec);
-}


[72/72] [abbrv] incubator-brooklyn git commit: This closes #845

Posted by he...@apache.org.
This closes #845


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

Branch: refs/heads/master
Commit: 1811c4b082d6ba95d46602c5b4e97f1389aaa226
Parents: 4b08f90 3fdd120
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Wed Aug 19 12:07:28 2015 +0100
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Wed Aug 19 12:07:28 2015 +0100

----------------------------------------------------------------------
 usage/dist/src/main/dist/bin/brooklyn.ps1 | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
----------------------------------------------------------------------



[24/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriver.java
new file mode 100644
index 0000000..f162ca4
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriver.java
@@ -0,0 +1,443 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import static org.apache.brooklyn.util.JavaGroovyEquivalents.groovyTruth;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.effector.core.EffectorTasks;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
+import com.google.common.base.Optional;
+import com.google.common.base.Splitter;
+import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.gson.internal.Primitives;
+
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.collections.MutableSet;
+import org.apache.brooklyn.util.core.flags.TypeCoercions;
+import org.apache.brooklyn.util.core.internal.ssh.ShellTool;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.core.task.ssh.SshTasks;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskFactory;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.ssh.BashCommands;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.text.StringEscapes.BashStringEscapes;
+
+/**
+ * The SSH implementation of the {@link org.apache.brooklyn.entity.java.JavaSoftwareProcessDriver}.
+ */
+public abstract class JavaSoftwareProcessSshDriver extends AbstractSoftwareProcessSshDriver implements JavaSoftwareProcessDriver {
+
+    public static final Logger log = LoggerFactory.getLogger(JavaSoftwareProcessSshDriver.class);
+
+    public static final List<List<String>> MUTUALLY_EXCLUSIVE_OPTS = ImmutableList.<List<String>> of(ImmutableList.of("-client",
+            "-server"));
+
+    public static final List<String> KEY_VAL_OPT_PREFIXES = ImmutableList.of("-Xmx", "-Xms", "-Xss");
+
+    public JavaSoftwareProcessSshDriver(EntityLocal entity, SshMachineLocation machine) {
+        super(entity, machine);
+
+        entity.setAttribute(Attributes.LOG_FILE_LOCATION, getLogFileLocation());
+    }
+
+    protected abstract String getLogFileLocation();
+
+    public boolean isJmxEnabled() {
+        return (entity instanceof UsesJmx) && (entity.getConfig(UsesJmx.USE_JMX));
+    }
+
+    public boolean isJmxSslEnabled() {
+        return isJmxEnabled() && groovyTruth(entity.getConfig(UsesJmx.JMX_SSL_ENABLED));
+    }
+
+    /**
+     * Sets all JVM options (-X.. -D..) in an environment var JAVA_OPTS.
+     * <p>
+     * That variable is constructed from {@link #getJavaOpts()}, then wrapped _unescaped_ in double quotes. An
+     * error is thrown if there is an unescaped double quote in the string. All other unescaped
+     * characters are permitted, but unless $var expansion or `command` execution is desired (although
+     * this is not confirmed as supported) the generally caller should escape any such characters, for
+     * example using {@link BashStringEscapes#escapeLiteralForDoubleQuotedBash(String)}.
+     */
+    @Override
+    public Map<String, String> getShellEnvironment() {
+        List<String> javaOpts = getJavaOpts();
+
+        for (String it : javaOpts) {
+            BashStringEscapes.assertValidForDoubleQuotingInBash(it);
+        }
+        // do not double quote here; the env var is double quoted subsequently;
+        // spaces should be preceded by double-quote
+        // (if dbl quotes are needed we could pass on the command-line instead of in an env var)
+        String sJavaOpts = Joiner.on(' ').join(javaOpts);
+        return MutableMap.<String, String>builder().putAll(super.getShellEnvironment()).put("JAVA_OPTS", sJavaOpts).build();
+    }
+
+    /**
+     * arguments to pass to the JVM; this is the config options (e.g. -Xmx1024; only the contents of
+     * {@link #getCustomJavaConfigOptions()} by default) and java system properties (-Dk=v; add custom
+     * properties in {@link #getCustomJavaSystemProperties()})
+     * <p>
+     * See {@link #getShellEnvironment()} for discussion of quoting/escaping strategy.
+     **/
+    public List<String> getJavaOpts() {
+        Iterable<String> sysprops = Iterables.transform(getJavaSystemProperties().entrySet(),
+                new Function<Map.Entry<String, ?>, String>() {
+                    public String apply(Map.Entry<String, ?> entry) {
+                        String k = entry.getKey();
+                        Object v = entry.getValue();
+                        try {
+                            if (v != null && Primitives.isWrapperType(v.getClass())) {
+                                v = "" + v;
+                            } else {
+                                v = Tasks.resolveValue(v, Object.class, ((EntityInternal)entity).getExecutionContext());
+                                if (v == null) {
+                                } else if (v instanceof CharSequence) {
+                                } else if (TypeCoercions.isPrimitiveOrBoxer(v.getClass())) {
+                                    v = "" + v;
+                                } else {
+                                    // could do toString, but that's likely not what is desired;
+                                    // probably a type mismatch,
+                                    // post-processing should be specified (common types are accepted
+                                    // above)
+                                    throw new IllegalArgumentException("cannot convert value " + v + " of type " + v.getClass()
+                                            + " to string to pass as JVM property; use a post-processor");
+                                }
+                            }
+                            return "-D" + k + (v != null ? "=" + v : "");
+                        } catch (Exception e) {
+                            log.warn("Error resolving java option key {}, propagating: {}", k, e);
+                            throw Throwables.propagate(e);
+                        }
+                    }
+                });
+
+        Set<String> result = MutableSet.<String> builder().
+                addAll(getJmxJavaConfigOptions()).
+                addAll(getCustomJavaConfigOptions()).
+                addAll(sysprops).
+            build();
+
+        for (String customOpt : entity.getConfig(UsesJava.JAVA_OPTS)) {
+            for (List<String> mutuallyExclusiveOpt : MUTUALLY_EXCLUSIVE_OPTS) {
+                if (mutuallyExclusiveOpt.contains(customOpt)) {
+                    result.removeAll(mutuallyExclusiveOpt);
+                }
+            }
+            for (String keyValOptPrefix : KEY_VAL_OPT_PREFIXES) {
+                if (customOpt.startsWith(keyValOptPrefix)) {
+                    for (Iterator<String> iter = result.iterator(); iter.hasNext();) {
+                        String existingOpt = iter.next();
+                        if (existingOpt.startsWith(keyValOptPrefix)) {
+                            iter.remove();
+                        }
+                    }
+                }
+            }
+            if (customOpt.contains("=")) {
+                String customOptPrefix = customOpt.substring(0, customOpt.indexOf("="));
+
+                for (Iterator<String> iter = result.iterator(); iter.hasNext();) {
+                    String existingOpt = iter.next();
+                    if (existingOpt.startsWith(customOptPrefix)) {
+                        iter.remove();
+                    }
+                }
+            }
+            result.add(customOpt);
+        }
+
+        return ImmutableList.copyOf(result);
+    }
+
+    /**
+     * Returns the complete set of Java system properties (-D defines) to set for the application.
+     * <p>
+     * This is exposed to the JVM as the contents of the {@code JAVA_OPTS} environment variable. Default
+     * set contains config key, custom system properties, and JMX defines.
+     * <p>
+     * Null value means to set -Dkey otherwise it is -Dkey=value.
+     * <p>
+     * See {@link #getShellEnvironment()} for discussion of quoting/escaping strategy.
+     */
+    protected Map<String,?> getJavaSystemProperties() {
+        return MutableMap.<String,Object>builder()
+                .putAll(getCustomJavaSystemProperties())
+                .putAll(isJmxEnabled() ? getJmxJavaSystemProperties() : Collections.<String,Object>emptyMap())
+                .putAll(entity.getConfig(UsesJava.JAVA_SYSPROPS))
+                .build();
+    }
+
+    /**
+     * Return extra Java system properties (-D defines) used by the application.
+     *
+     * Override as needed; default is an empty map.
+     */
+    protected Map getCustomJavaSystemProperties() {
+        return Maps.newLinkedHashMap();
+    }
+
+    /**
+     * Return extra Java config options, ie arguments starting with - which are passed to the JVM prior
+     * to the class name.
+     * <p>
+     * Note defines are handled separately, in {@link #getCustomJavaSystemProperties()}.
+     * <p>
+     * Override as needed; default is an empty list.
+     */
+    protected List<String> getCustomJavaConfigOptions() {
+        return Lists.newArrayList();
+    }
+
+    /** @deprecated since 0.6.0, the config key is always used instead of this */ @Deprecated
+    public Integer getJmxPort() {
+        return !isJmxEnabled() ? Integer.valueOf(-1) : entity.getAttribute(UsesJmx.JMX_PORT);
+    }
+
+    /** @deprecated since 0.6.0, the config key is always used instead of this */ @Deprecated
+    public Integer getRmiRegistryPort() {
+        return !isJmxEnabled() ? -1 : entity.getAttribute(UsesJmx.RMI_REGISTRY_PORT);
+    }
+
+    /** @deprecated since 0.6.0, the config key is always used instead of this */ @Deprecated
+    public String getJmxContext() {
+        return !isJmxEnabled() ? null : entity.getAttribute(UsesJmx.JMX_CONTEXT);
+    }
+
+    /**
+     * Return the configuration properties required to enable JMX for a Java application.
+     *
+     * These should be set as properties in the {@code JAVA_OPTS} environment variable when calling the
+     * run script for the application.
+     */
+    protected Map<String, ?> getJmxJavaSystemProperties() {
+        MutableMap.Builder<String, Object> result = MutableMap.<String, Object> builder();
+
+        if (isJmxEnabled()) {
+            new JmxSupport(getEntity(), getRunDir()).applyJmxJavaSystemProperties(result);
+        }
+
+        return result.build();
+    }
+
+    /**
+     * Return any JVM arguments required, other than the -D defines returned by {@link #getJmxJavaSystemProperties()}
+     */
+    protected List<String> getJmxJavaConfigOptions() {
+        List<String> result = new ArrayList<String>();
+        if (isJmxEnabled()) {
+            result.addAll(new JmxSupport(getEntity(), getRunDir()).getJmxJavaConfigOptions());
+        }
+        return result;
+    }
+
+    /**
+     * Checks for the presence of Java on the entity's location, installing if necessary.
+     * @return true if the required version of Java was found on the machine or if it was installed correctly,
+     * otherwise false.
+     */
+    protected boolean checkForAndInstallJava(String requiredVersion) {
+        int requiredJavaMinor;
+        if (requiredVersion.contains(".")) {
+            List<String> requiredVersionParts = Splitter.on(".").splitToList(requiredVersion);
+            requiredJavaMinor = Integer.valueOf(requiredVersionParts.get(1));
+        } else if (requiredVersion.length() == 1) {
+            requiredJavaMinor = Integer.valueOf(requiredVersion);
+        } else {
+            log.error("java version required {} is not supported", requiredVersion);
+            throw new IllegalArgumentException("Required java version " + requiredVersion + " not supported");
+        }
+        Optional<String> installedJavaVersion = getInstalledJavaVersion();
+        if (installedJavaVersion.isPresent()) {
+            List<String> installedVersionParts = Splitter.on(".").splitToList(installedJavaVersion.get());
+            int javaMajor = Integer.valueOf(installedVersionParts.get(0));
+            int javaMinor = Integer.valueOf(installedVersionParts.get(1));
+            if (javaMajor == 1 && javaMinor >= requiredJavaMinor) {
+                log.debug("Java {} already installed at {}@{}", new Object[]{installedJavaVersion.get(), getEntity(), getLocation()});
+                return true;
+            }
+        }
+        return tryJavaInstall(requiredVersion, BashCommands.installJava(requiredJavaMinor)) == 0;
+    }
+
+    protected int tryJavaInstall(String version, String command) {
+        getLocation().acquireMutex("installing", "installing Java at " + getLocation());
+        try {
+            log.debug("Installing Java {} at {}@{}", new Object[]{version, getEntity(), getLocation()});
+            ProcessTaskFactory<Integer> taskFactory = SshTasks.newSshExecTaskFactory(getLocation(), command)
+                    .summary("install java ("+version+")")
+                    .configure(ShellTool.PROP_EXEC_ASYNC, true);
+            ProcessTaskWrapper<Integer> installCommand = Entities.submit(getEntity(), taskFactory);
+            int result = installCommand.get();
+            if (result != 0) {
+                log.warn("Installation of Java {} failed at {}@{}: {}",
+                        new Object[]{version, getEntity(), getLocation(), installCommand.getStderr()});
+            }
+            return result;
+        } finally {
+            getLocation().releaseMutex("installing");
+        }
+    }
+
+    /**
+    * @deprecated since 0.7.0; instead use {@link #getInstalledJavaVersion()}
+    */
+    @Deprecated
+    protected Optional<String> getCurrentJavaVersion() {
+        return getInstalledJavaVersion();
+    }
+
+    /**
+     * Checks for the version of Java installed on the entity's location over SSH.
+     * @return An Optional containing the version portion of `java -version`, or absent if no Java found.
+     */
+    protected Optional<String> getInstalledJavaVersion() {
+        log.debug("Checking Java version at {}@{}", getEntity(), getLocation());
+        // sed gets stdin like 'java version "1.7.0_45"'
+        ProcessTaskWrapper<Integer> versionCommand = Entities.submit(getEntity(), SshTasks.newSshExecTaskFactory(
+                getLocation(), "java -version 2>&1 | grep \" version\" | sed 's/.*\"\\(.*\\).*\"/\\1/'"));
+        versionCommand.get();
+        String stdOut = versionCommand.getStdout().trim();
+        if (!Strings.isBlank(stdOut)) {
+            log.debug("Found Java version at {}@{}: {}", new Object[] {getEntity(), getLocation(), stdOut});
+            return Optional.of(stdOut);
+        } else {
+            log.debug("Found no Java installed at {}@{}", getEntity(), getLocation());
+            return Optional.absent();
+        }
+    }
+
+    /**
+     * Answers one of "OpenJDK", "Oracle", or other vendor info.
+     */
+    protected Optional<String> getCurrentJavaVendor() {
+        // TODO Also handle IBM jvm
+        log.debug("Checking Java vendor at {}@{}", getEntity(), getLocation());
+        ProcessTaskWrapper<Integer> versionCommand = Entities.submit(getEntity(), SshTasks.newSshExecTaskFactory(
+                getLocation(), "java -version 2>&1 | awk 'NR==2 {print $1}'"));
+        versionCommand.get();
+        String stdOut = versionCommand.getStdout().trim();
+        if (Strings.isBlank(stdOut)) {
+            log.debug("Found no Java installed at {}@{}", getEntity(), getLocation());
+            return Optional.absent();
+        } else if ("Java(TM)".equals(stdOut)) {
+            log.debug("Found Java version at {}@{}: {}", new Object[] {getEntity(), getLocation(), stdOut});
+            return Optional.of("Oracle");
+        } else {
+            return Optional.of(stdOut);
+        }
+    }
+
+    /**
+     * Checks for Java 6 or 7, installing Java 7 if neither are found. Override this method to
+     * check for and install specific versions of Java.
+     *
+     * @see #checkForAndInstallJava(String)
+     */
+    public boolean installJava() {
+        if (entity instanceof UsesJava) {
+            String version = entity.getConfig(UsesJava.JAVA_VERSION_REQUIRED);
+            return checkForAndInstallJava(version);
+        }
+        // by default it installs jdk7
+        return checkForAndInstallJava("1.7");
+    }
+
+    public void installJmxSupport() {
+        if (isJmxEnabled()) {
+            newScript("JMX_SETUP_PREINSTALL").body.append("mkdir -p "+getRunDir()).execute();
+            new JmxSupport(getEntity(), getRunDir()).install();
+        }
+    }
+
+    public void checkJavaHostnameBug() {
+        checkNoHostnameBug();
+
+        try {
+            ProcessTaskWrapper<Integer> hostnameTask = DynamicTasks.queue(SshEffectorTasks.ssh("echo FOREMARKER; hostname -f; echo AFTMARKER")).block();
+            String stdout = Strings.getFragmentBetween(hostnameTask.getStdout(), "FOREMARKER", "AFTMARKER");
+            if (hostnameTask.getExitCode() == 0 && Strings.isNonBlank(stdout)) {
+                String hostname = stdout.trim();
+                Integer len = hostname.length();
+                if (len > 63) {
+                    // likely to cause a java crash due to java bug 7089443 -- set a new short hostname
+                    // http://mail.openjdk.java.net/pipermail/net-dev/2012-July/004603.html
+                    String newHostname = "br-"+getEntity().getId().toLowerCase();
+                    log.info("Detected likelihood of Java hostname bug with hostname length "+len+" for "+getEntity()+"; renaming "+getMachine()+"  to hostname "+newHostname);
+                    DynamicTasks.queue(SshEffectorTasks.ssh(BashCommands.setHostname(newHostname, null))).block();
+                }
+            } else {
+                log.debug("Hostname length could not be determined for location "+EffectorTasks.findSshMachine()+"; not doing Java hostname bug check");
+            }
+        } catch (Exception e) {
+            Exceptions.propagateIfFatal(e);
+            log.warn("Error checking/fixing Java hostname bug (continuing): "+e, e);
+        }
+    }
+
+    @Override
+    public void setup() {
+        DynamicTasks.queue("install java", new Runnable() { public void run() {
+            installJava();
+        }});
+
+        // TODO check java version
+
+        if (getEntity().getConfig(UsesJava.CHECK_JAVA_HOSTNAME_BUG)) {
+            DynamicTasks.queue("check java hostname bug", new Runnable() { public void run() {
+                checkJavaHostnameBug(); }});
+        }
+    }
+
+    @Override
+    public void copyRuntimeResources() {
+        super.copyRuntimeResources();
+
+        if (isJmxEnabled()) {
+            DynamicTasks.queue("install jmx", new Runnable() { public void run() {
+                installJmxSupport(); }});
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxAttributeSensor.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxAttributeSensor.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxAttributeSensor.java
new file mode 100644
index 0000000..bee8126
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxAttributeSensor.java
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import java.util.concurrent.Callable;
+
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.effector.core.AddSensor;
+import org.apache.brooklyn.sensor.core.DependentConfiguration;
+import org.apache.brooklyn.sensor.core.HttpRequestSensor;
+import org.apache.brooklyn.sensor.feed.jmx.JmxAttributePollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
+import org.apache.brooklyn.sensor.feed.jmx.JmxHelper;
+import org.apache.brooklyn.sensor.ssh.SshCommandSensor;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Functions;
+import com.google.common.base.Preconditions;
+
+/**
+ * Configurable {@link org.apache.brooklyn.api.entity.EntityInitializer} which adds a JMX sensor feed to retrieve an
+ * <code>attribute</code> from a JMX <code>objectName</code>.
+ *
+ * @see SshCommandSensor
+ * @see HttpRequestSensor
+ */
+@Beta
+public final class JmxAttributeSensor<T> extends AddSensor<T> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(JmxAttributeSensor.class);
+
+    public static final ConfigKey<String> OBJECT_NAME = ConfigKeys.newStringConfigKey("objectName", "JMX object name for sensor lookup");
+    public static final ConfigKey<String> ATTRIBUTE = ConfigKeys.newStringConfigKey("attribute", "JMX attribute to poll in object");
+    public static final ConfigKey<Object> DEFAULT_VALUE = ConfigKeys.newConfigKey(Object.class, "defaultValue", "Default value for sensor; normally null");
+
+    protected final String objectName;
+    protected final String attribute;
+    protected final Object defaultValue;
+
+    public JmxAttributeSensor(final ConfigBag params) {
+        super(params);
+ 
+        objectName = Preconditions.checkNotNull(params.get(OBJECT_NAME), "objectName");
+        attribute = Preconditions.checkNotNull(params.get(ATTRIBUTE), "attribute");
+        defaultValue = params.get(DEFAULT_VALUE);
+
+        try {
+            ObjectName.getInstance(objectName);
+        } catch (MalformedObjectNameException mone) {
+            throw new IllegalArgumentException("Malformed JMX object name: " + objectName, mone);
+        }
+    }
+
+    @Override
+    public void apply(final EntityLocal entity) {
+        super.apply(entity);
+
+        if (entity instanceof UsesJmx) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Submitting task to add JMX sensor {} to {}", name, entity);
+            }
+
+            Task<Integer> jmxPortTask = DependentConfiguration.attributeWhenReady(entity, UsesJmx.JMX_PORT);
+            Task<JmxFeed> jmxFeedTask = Tasks.<JmxFeed>builder()
+                    .description("Add JMX feed")
+                    .body(new Callable<JmxFeed>() {
+                        @Override
+                        public JmxFeed call() throws Exception {
+                            JmxHelper helper = new JmxHelper(entity);
+                            Duration period = entity.getConfig(SENSOR_PERIOD);
+
+                            JmxFeed feed = JmxFeed.builder()
+                                    .entity(entity)
+                                    .period(period)
+                                    .helper(helper)
+                                    .pollAttribute(new JmxAttributePollConfig<T>(sensor)
+                                            .objectName(objectName)
+                                            .attributeName(attribute)
+                                            .onFailureOrException(Functions.<T>constant((T) defaultValue)))
+                                    .build();
+                           return feed;
+                        }
+                    })
+                    .build();
+            DynamicTasks.submit(Tasks.sequential("Add JMX Sensor " + sensor.getName(), jmxPortTask, jmxFeedTask), entity);
+        } else {
+            throw new IllegalStateException(String.format("Entity %s does not support JMX", entity));
+        }
+
+        // TODO add entity shutdown hook to stop JmxFeed
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxSupport.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxSupport.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxSupport.java
new file mode 100644
index 0000000..5e67d30
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxSupport.java
@@ -0,0 +1,357 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import java.util.EnumSet;
+import java.util.List;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.config.ConfigKey.HasConfigKey;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.location.access.BrooklynAccessUtils;
+import org.apache.brooklyn.location.basic.Locations;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.sensor.feed.jmx.JmxHelper;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.BrooklynMavenArtifacts;
+import org.apache.brooklyn.util.core.ResourceUtils;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.guava.Maybe;
+import org.apache.brooklyn.util.jmx.jmxmp.JmxmpAgent;
+import org.apache.brooklyn.util.jmx.jmxrmi.JmxRmiAgent;
+import org.apache.brooklyn.util.maven.MavenArtifact;
+import org.apache.brooklyn.util.maven.MavenRetriever;
+import org.apache.brooklyn.util.net.Urls;
+import org.apache.brooklyn.util.text.Strings;
+
+import com.google.common.base.Preconditions;
+import com.google.common.net.HostAndPort;
+
+public class JmxSupport implements UsesJmx {
+
+    private static final Logger log = LoggerFactory.getLogger(JmxSupport.class);
+
+    private final Entity entity;
+    private final String runDir;
+
+    private Boolean isJmx;
+    private Boolean isSecure;
+    private JmxAgentModes jmxAgentMode;
+
+    private static boolean warnedAboutNotOnClasspath = false;
+
+    /** run dir may be null if it is not accessed */
+    public JmxSupport(Entity entity, @Nullable String runDir) {
+        this.entity = Preconditions.checkNotNull(entity, "entity must be supplied");
+        this.runDir = runDir;
+    }
+
+    @Nonnull
+    public String getRunDir() {
+        return Preconditions.checkNotNull(runDir, "runDir must have been supplied to perform this operation");
+    }
+
+    public Entity getEntity() {
+        return entity;
+    }
+
+    <T> T getConfig(ConfigKey<T> key) {
+        return getEntity().getConfig(key);
+    }
+
+    <T> T getConfig(HasConfigKey<T> key) {
+        return getEntity().getConfig(key);
+    }
+
+    <T> void setConfig(ConfigKey<T> key, T value) {
+        ((EntityLocal)getEntity()).setConfig(key, value);
+    }
+
+    public Maybe<SshMachineLocation> getMachine() {
+        return Locations.findUniqueSshMachineLocation(entity.getLocations());
+    }
+
+    public boolean isJmx() {
+        init();
+        return isJmx;
+    }
+
+    public JmxAgentModes getJmxAgentMode() {
+        init();
+        if (jmxAgentMode==null) return JmxAgentModes.NONE;
+        return jmxAgentMode;
+    }
+
+    public boolean isSecure() {
+        init();
+        if (isSecure==null) return false;
+        return isSecure;
+    }
+
+    protected synchronized void init() {
+        if (isJmx!=null)
+            return;
+
+        if (Boolean.FALSE.equals(entity.getConfig(USE_JMX))) {
+            isJmx = false;
+            return;
+        }
+        isJmx = true;
+        jmxAgentMode = entity.getConfig(JMX_AGENT_MODE);
+        if (jmxAgentMode==null) jmxAgentMode = JmxAgentModes.AUTODETECT;
+
+        isSecure = entity.getConfig(JMX_SSL_ENABLED);
+        if (isSecure==null) isSecure = false;
+
+        if (jmxAgentMode==JmxAgentModes.AUTODETECT) {
+            if (isSecure()) {
+                jmxAgentMode = JmxAgentModes.JMXMP;
+            } else {
+                jmxAgentMode = JmxAgentModes.JMXMP_AND_RMI;
+                if (!ResourceUtils.create(this).doesUrlExist(getJmxAgentJarUrl())) {
+                    // can happen e.g. if eclipse build
+                    log.warn("JMX agent JAR not found ("+getJmxAgentJarUrl()+") when auto-detecting JMX settings for "+entity+"; " +
+                            "likely cause is an incomplete build (e.g. from Eclipse; run a maven build then retry in the IDE); "+
+                            "reverting to NONE (use built-in Java JMX support, which will not go through firewalls)");
+                    jmxAgentMode = JmxAgentModes.NONE;
+                }
+            }
+
+            ((EntityLocal)entity).setConfig(JMX_AGENT_MODE, jmxAgentMode);
+        }
+
+        if (isSecure && jmxAgentMode!=JmxAgentModes.JMXMP) {
+            String msg = "JMX SSL is specified, but it requires JMXMP which is disabled, when configuring "+entity;
+            log.warn(msg);
+            throw new IllegalStateException(msg);
+        }
+    }
+
+    public void setJmxUrl() {
+        ((EntityInternal)entity).setAttribute(JMX_URL, getJmxUrl());
+    }
+
+    public String getJmxUrl() {
+        init();
+
+        HostAndPort jmx = BrooklynAccessUtils.getBrooklynAccessibleAddress(entity, entity.getAttribute(JMX_PORT));
+
+        if (EnumSet.of(JmxAgentModes.JMXMP, JmxAgentModes.JMXMP_AND_RMI).contains(getJmxAgentMode())) {
+            return JmxHelper.toJmxmpUrl(jmx.getHostText(), jmx.getPort());
+        } else {
+            if (getJmxAgentMode() == JmxAgentModes.NONE) {
+                fixPortsForModeNone();
+            }
+            // this will work for agent or agentless
+            HostAndPort rmi = BrooklynAccessUtils.getBrooklynAccessibleAddress(entity, entity.getAttribute(RMI_REGISTRY_PORT));
+            return JmxHelper.toRmiJmxUrl(jmx.getHostText(), jmx.getPort(), rmi.getPort(),
+                    entity.getAttribute(JMX_CONTEXT));
+        }
+    }
+
+    /** mode NONE cannot set a JMX (RMI server) port; it needs an RMI registry port,
+     * then gets redirected to an anonymous RMI server port;
+     * both the hostname and the anonymous port must be accessible to use this mode
+     * (hence the use of the other agents in most cases) */
+    protected int fixPortsForModeNone() {
+        assert getJmxAgentMode()==JmxAgentModes.NONE;
+        Integer jmxRemotePort = getEntity().getAttribute(JMX_PORT);
+        Integer rmiRegistryPort = getEntity().getAttribute(RMI_REGISTRY_PORT);
+        if (rmiRegistryPort!=null && rmiRegistryPort>0) {
+            if (jmxRemotePort==null || jmxRemotePort!=rmiRegistryPort) {
+                if (jmxRemotePort!=null && jmxRemotePort>0) {
+                    // ignore RMI registry port when mode 'none' is set -- set same as JMX port here
+                    // (bit irritating, but JMX_PORT will be ignored in this mode)
+                    log.warn("Ignoring JMX_PORT "+jmxRemotePort+" when configuring agentless JMX on "+getEntity()+"; will use RMI_REGISTRY_PORT "+rmiRegistryPort);
+                }
+                jmxRemotePort = rmiRegistryPort;
+                ((EntityLocal)getEntity()).setAttribute(JMX_PORT, jmxRemotePort);
+            }
+        } else {
+            if (jmxRemotePort==null || jmxRemotePort<=0) {
+                throw new IllegalStateException("Invalid JMX_PORT "+jmxRemotePort+" and RMI_REGISTRY_PORT "+rmiRegistryPort+" when configuring JMX "+getJmxAgentMode()+" on "+getEntity());
+            }
+            ((EntityLocal)getEntity()).setAttribute(RMI_REGISTRY_PORT, jmxRemotePort);
+        }
+        return jmxRemotePort;
+    }
+
+    public List<String> getJmxJavaConfigOptions() {
+        if (EnumSet.<JmxAgentModes>of(JmxAgentModes.NONE, JmxAgentModes.JMX_RMI).contains(getJmxAgentMode())) {
+            return MutableList.of();
+        } else {
+            return MutableList.of(String.format("-javaagent:%s", getJmxAgentJarDestinationFilePath()));
+        }
+    }
+
+    public String getJmxAgentJarDestinationFilePath() {
+        // cache the local path so we continue to work post-rebind to a different version
+        String result = getEntity().getAttribute(JMX_AGENT_LOCAL_PATH);
+        if (Strings.isNonBlank(result)) return result;
+        result = getJmxAgentJarDestinationFilePathDefault();
+        ((EntityInternal)getEntity()).setAttribute(JMX_AGENT_LOCAL_PATH, result);
+        return result;
+    }
+    
+    public String getJmxAgentJarDestinationFilePathDefault() {
+        return Urls.mergePaths(getRunDir(), getJmxAgentJarBasename());
+    }
+
+    @Nullable public MavenArtifact getJmxAgentJarMavenArtifact() {
+        switch (getJmxAgentMode()) {
+        case JMXMP:
+        case JMXMP_AND_RMI:
+            MavenArtifact result = BrooklynMavenArtifacts.artifact(null, "brooklyn-jmxmp-agent", "jar", "with-dependencies");
+            // the "with-dependencies" variant is needed; however the filename then has the classifier segment _replaced_ by "shaded" when this filename is created
+            result.setCustomFileNameAfterArtifactMarker("shaded");
+            result.setClassifierFileNameMarker("");
+            return result;
+        case JMX_RMI_CUSTOM_AGENT:
+            return BrooklynMavenArtifacts.jar("brooklyn-jmxrmi-agent");
+        default:
+            return null;
+        }
+    }
+
+    /** @deprecated since 0.6.0; use {@link #getJmxAgentJarMavenArtifact()} */
+    @Deprecated
+    public String getJmxAgentJarBasename() {
+        MavenArtifact artifact = getJmxAgentJarMavenArtifact();
+        if (artifact==null)
+            throw new IllegalStateException("Either JMX is not enabled or there is an error in the configuration (JMX mode "+getJmxAgentMode()+" does not support agent JAR)");
+        return artifact.getFilename();
+    }
+
+    /** returns URL for accessing the java agent, throwing if not applicable;
+     * prefers on classpath where it should be, but will fall back to taking from maven hosted
+     * (known problem in Eclipse where JARs are not always copied)
+     */
+    public String getJmxAgentJarUrl() {
+        MavenArtifact artifact = getJmxAgentJarMavenArtifact();
+        if (artifact==null)
+            throw new IllegalStateException("Either JMX is not enabled or there is an error in the configuration (JMX mode "+getJmxAgentMode()+" does not support agent JAR)");
+        String jar = "classpath://" + artifact.getFilename();
+        if (ResourceUtils.create(this).doesUrlExist(jar))
+            return jar;
+
+        String result = MavenRetriever.localUrl(artifact);
+        if (warnedAboutNotOnClasspath) {
+            log.debug("JMX JAR for "+artifact+" is not on the classpath; taking from "+result);
+        } else {
+            log.warn("JMX JAR for "+artifact+" is not on the classpath; taking from "+result+" (subsequent similar messages will be logged at debug)");
+            warnedAboutNotOnClasspath = true;
+        }
+        return result;
+    }
+
+    /** applies _some_ of the common settings needed to connect via JMX */
+    public void applyJmxJavaSystemProperties(MutableMap.Builder<String,Object> result) {
+        if (!isJmx()) return ;
+
+        Integer jmxPort = Preconditions.checkNotNull(entity.getAttribute(JMX_PORT), "jmx port must not be null for %s", entity);
+        HostAndPort jmx = BrooklynAccessUtils.getBrooklynAccessibleAddress(entity, jmxPort);
+        Integer jmxRemotePort = getEntity().getAttribute(JMX_PORT);
+        String hostName = jmx.getHostText();
+
+        result.put("com.sun.management.jmxremote", null);
+        result.put("java.rmi.server.hostname", hostName);
+
+        switch (getJmxAgentMode()) {
+        case JMXMP_AND_RMI:
+            Integer rmiRegistryPort = Preconditions.checkNotNull(entity.getAttribute(UsesJmx.RMI_REGISTRY_PORT), "registry port (config val %s)", entity.getConfig(UsesJmx.RMI_REGISTRY_PORT));
+            result.put(JmxmpAgent.RMI_REGISTRY_PORT_PROPERTY, rmiRegistryPort);
+        case JMXMP:
+            if (jmxRemotePort==null || jmxRemotePort<=0)
+                throw new IllegalStateException("Unsupported JMX port "+jmxRemotePort+" - when applying system properties ("+getJmxAgentMode()+" / "+getEntity()+")");
+            result.put(JmxmpAgent.JMXMP_PORT_PROPERTY, jmxRemotePort);
+            // with JMXMP don't try to tell it the hostname -- it isn't needed for JMXMP, and if specified
+            // it will break if the hostname we see is not known at the server, e.g. a forwarding public IP
+            result.remove("java.rmi.server.hostname");
+            break;
+        case JMX_RMI_CUSTOM_AGENT:
+            if (jmxRemotePort==null || jmxRemotePort<=0)
+                throw new IllegalStateException("Unsupported JMX port "+jmxRemotePort+" - when applying system properties ("+getJmxAgentMode()+" / "+getEntity()+")");
+            result.put(JmxRmiAgent.RMI_REGISTRY_PORT_PROPERTY, Preconditions.checkNotNull(entity.getAttribute(UsesJmx.RMI_REGISTRY_PORT), "registry port"));
+            result.put(JmxRmiAgent.JMX_SERVER_PORT_PROPERTY, jmxRemotePort);
+            break;
+        case NONE:
+            jmxRemotePort = fixPortsForModeNone();
+        case JMX_RMI:
+            result.put("com.sun.management.jmxremote.port", jmxRemotePort);
+            result.put("java.rmi.server.useLocalHostname", "true");
+            break;
+        default:
+            throw new IllegalStateException("Unsupported JMX mode - when applying system properties ("+getJmxAgentMode()+" / "+getEntity()+")");
+        }
+
+        if (isSecure()) {
+            // set values true, and apply keys pointing to keystore / truststore
+            getJmxSslSupport().applyAgentJmxJavaSystemProperties(result);
+        } else {
+            result.
+                put("com.sun.management.jmxremote.ssl", false).
+                put("com.sun.management.jmxremote.authenticate", false);
+        }
+    }
+
+    /** installs files needed for JMX, to the runDir given in constructor, assuming the runDir has been created */
+    public void install() {
+        if (EnumSet.of(JmxAgentModes.JMXMP_AND_RMI, JmxAgentModes.JMXMP, JmxAgentModes.JMX_RMI_CUSTOM_AGENT).contains(getJmxAgentMode())) {
+            Tasks.setBlockingDetails("Copying JMX agent jar to server.");
+            try {
+                getMachine().get().copyTo(ResourceUtils.create(this).getResourceFromUrl(
+                        getJmxAgentJarUrl()), getJmxAgentJarDestinationFilePath());
+            } finally {
+                Tasks.resetBlockingDetails();
+            }
+        }
+        if (isSecure()) {
+            getJmxSslSupport().install();
+        }
+    }
+
+    protected JmxmpSslSupport getJmxSslSupport() {
+        return new JmxmpSslSupport(this);
+    }
+
+    /** sets JMR_RMI_CUSTOM_AGENT as the connection mode for the indicated apps.
+     * <p>
+     * TODO callers of this method have RMI dependencies in the actual app;
+     * we should look at removing them, so that those pieces of software can run behind
+     * forwarding public IP's and over SSL (both reasons JMXMP is preferred by us!)
+     */
+    public void recommendJmxRmiCustomAgent() {
+        // set JMX_RMI because the registry is needed (i think)
+        Maybe<Object> jmx = entity.getConfigRaw(UsesJmx.JMX_AGENT_MODE, true);
+        if (!jmx.isPresentAndNonNull()) {
+            setConfig(UsesJmx.JMX_AGENT_MODE, JmxAgentModes.JMX_RMI_CUSTOM_AGENT);
+        } else if (jmx.get()!=JmxAgentModes.JMX_RMI_CUSTOM_AGENT) {
+            log.warn("Entity "+entity+" may not function unless running JMX_RMI_CUSTOM_AGENT mode (asked to use "+jmx.get()+")");
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxmpSslSupport.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxmpSslSupport.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxmpSslSupport.java
new file mode 100644
index 0000000..36d1773
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/JmxmpSslSupport.java
@@ -0,0 +1,134 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.security.KeyPair;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+
+import org.apache.brooklyn.util.collections.MutableMap.Builder;
+import org.apache.brooklyn.util.core.crypto.FluentKeySigner;
+import org.apache.brooklyn.util.core.crypto.SecureKeys;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.jmx.jmxmp.JmxmpAgent;
+import org.apache.brooklyn.util.net.Urls;
+
+import com.google.common.base.Preconditions;
+
+public class JmxmpSslSupport {
+
+    final static String BROOKLYN_VERSION = "0.8.0-SNAPSHOT";  // BROOKLYN_VERSION (updated by script)
+    
+    private final JmxSupport jmxSupport;
+    
+    private KeyStore agentTrustStore;
+    private KeyStore agentKeyStore;
+    
+    public JmxmpSslSupport(JmxSupport jmxSupport) {
+        this.jmxSupport = Preconditions.checkNotNull(jmxSupport);
+    }
+    
+    public String getJmxSslKeyStoreFilePath() {
+        return Urls.mergePaths(jmxSupport.getRunDir(), "jmx-keystore");
+    }
+    
+    public String getJmxSslTrustStoreFilePath() {
+        return Urls.mergePaths(jmxSupport.getRunDir(), "jmx-truststore");
+    }
+    
+    public void applyAgentJmxJavaSystemProperties(Builder<String, Object> result) {
+        result.
+            put(JmxmpAgent.USE_SSL_PROPERTY, true).
+            put(JmxmpAgent.AUTHENTICATE_CLIENTS_PROPERTY, true).
+            // the option below wants a jmxremote.password file; we use certs (above) to authenticate
+            put("com.sun.management.jmxremote.authenticate", false);
+
+        result.
+            put(JmxmpAgent.JMXMP_KEYSTORE_FILE_PROPERTY, getJmxSslKeyStoreFilePath()).
+            put(JmxmpAgent.JMXMP_TRUSTSTORE_FILE_PROPERTY, getJmxSslTrustStoreFilePath());
+    }
+
+    public FluentKeySigner getBrooklynRootSigner() {
+        // TODO use brooklyn root CA keys etc
+        return new FluentKeySigner("brooklyn-root");
+    }
+
+    /** builds remote keystores, stores config keys/certs, and copies necessary files across */
+    public void install() {
+        try {
+            // build truststore and keystore
+            FluentKeySigner signer = getBrooklynRootSigner();
+            KeyPair jmxAgentKey = SecureKeys.newKeyPair();
+            X509Certificate jmxAgentCert = signer.newCertificateFor("jmxmp-agent", jmxAgentKey);
+
+            agentKeyStore = SecureKeys.newKeyStore();
+            agentKeyStore.setKeyEntry("jmxmp-agent", jmxAgentKey.getPrivate(), 
+                    // TODO jmx.ssl.agent.keyPassword
+                    "".toCharArray(),
+                    new Certificate[] { jmxAgentCert });
+            ByteArrayOutputStream agentKeyStoreBytes = new ByteArrayOutputStream();
+            agentKeyStore.store(agentKeyStoreBytes, 
+                    // TODO jmx.ssl.agent.keyStorePassword
+                    "".toCharArray());
+            
+            agentTrustStore = SecureKeys.newKeyStore();
+            agentTrustStore.setCertificateEntry("brooklyn", getJmxAccessCert());
+            ByteArrayOutputStream agentTrustStoreBytes = new ByteArrayOutputStream();
+            agentTrustStore.store(agentTrustStoreBytes, "".toCharArray());
+            
+            // install the truststore and keystore and rely on JmxSupport to install the agent
+            Tasks.setBlockingDetails("Copying keystore and truststore to the server.");
+            try {
+                jmxSupport.getMachine().get().copyTo(new ByteArrayInputStream(agentKeyStoreBytes.toByteArray()), getJmxSslKeyStoreFilePath());
+                jmxSupport.getMachine().get().copyTo(new ByteArrayInputStream(agentTrustStoreBytes.toByteArray()), getJmxSslTrustStoreFilePath());
+            } finally {
+                Tasks.resetBlockingDetails();
+            }
+
+        } catch (Exception e) {
+            throw Exceptions.propagate(e);
+        }
+    }
+
+    public synchronized Certificate getJmxAccessCert() {
+        Certificate cert = jmxSupport.getConfig(UsesJmx.JMX_SSL_ACCESS_CERT);
+        if (cert!=null) return cert;
+        // TODO load from keyStoreUrl
+        KeyPair jmxAccessKey = SecureKeys.newKeyPair();
+        X509Certificate jmxAccessCert = getBrooklynRootSigner().newCertificateFor("brooklyn-jmx-access", jmxAccessKey);
+
+        jmxSupport.setConfig(UsesJmx.JMX_SSL_ACCESS_CERT, jmxAccessCert);
+        jmxSupport.setConfig(UsesJmx.JMX_SSL_ACCESS_KEY, jmxAccessKey.getPrivate());
+        
+        return jmxAccessCert;
+    }
+    
+    public synchronized PrivateKey getJmxAccessKey() {
+        PrivateKey key = jmxSupport.getConfig(UsesJmx.JMX_SSL_ACCESS_KEY);
+        if (key!=null) return key;
+        getJmxAccessCert();
+        return jmxSupport.getConfig(UsesJmx.JMX_SSL_ACCESS_KEY);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJava.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJava.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJava.java
new file mode 100644
index 0000000..1f80eda
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJava.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.config.MapConfigKey;
+import org.apache.brooklyn.core.config.SetConfigKey;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Maps;
+
+public interface UsesJava {
+
+    /** system properties (-D) to append to JAVA_OPTS; normally accessed through {@link JavaEntityMethods#javaSysProp(String)} */
+    @SetFromFlag("javaSysProps")
+    public static final MapConfigKey<String> JAVA_SYSPROPS = new MapConfigKey<String>(String.class,
+            "java.sysprops", "Java command line system properties", Maps.<String,String>newLinkedHashMap());
+
+    /**
+     * Used to set java options. These options are prepended to the defaults.
+     * They can also be used to override defaults. The rules for overrides are:
+     * <ul>
+     *   <li>If contains a mutually exclusive setting, then the others are removed. Those supported are:
+     *     <ul>
+     *       <li>"-client" and "-server"
+     *     </ul>
+     *   <li>If value has a well-known prefix indicating it's a key-value pair. Those supported are:
+     *     <ul>
+     *       <li>"-Xmx"
+     *       <li>"-Xms"
+     *       <li>"-Xss"
+     *     </ul>
+     *   <li>If value contains "=" then see if there's a default that matches the section up to the "=".
+     *       If there is, then remove the original and just include this.
+     *       e.g. "-XX:MaxPermSize=512m" could be overridden in this way.
+     * </ul>
+     */
+    @SetFromFlag("javaOpts")
+    public static final SetConfigKey<String> JAVA_OPTS = new SetConfigKey<String>(String.class,
+            "java.opts", "Java command line options", ImmutableSet.<String>of());
+
+    public static final ConfigKey<Boolean> CHECK_JAVA_HOSTNAME_BUG = ConfigKeys.newBooleanConfigKey(
+            "java.check.hostname.bug", "Check whether hostname is too long and will likely crash Java" +
+                    "due to bug 7089443", true);
+
+    @SetFromFlag("javaVersionRequired")
+    ConfigKey<String> JAVA_VERSION_REQUIRED = ConfigKeys.newStringConfigKey("java.version.required", "Java version required", "1.7");
+
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJavaMXBeans.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJavaMXBeans.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJavaMXBeans.java
new file mode 100644
index 0000000..4f2d20b
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJavaMXBeans.java
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+
+public interface UsesJavaMXBeans {
+
+    @SetFromFlag("mxbeanStatsEnabled")
+    ConfigKey<Boolean> MXBEAN_STATS_ENABLED =
+            ConfigKeys.newBooleanConfigKey("java.metrics.mxbeanStatsEnabled", "Enables collection of JVM stats from the MXBeans, such as memory and thread usage (default is true)", true);
+
+    AttributeSensor<Long> USED_HEAP_MEMORY =
+            Sensors.newLongSensor("java.metrics.heap.used", "Current heap size (bytes)");
+    AttributeSensor<Long> INIT_HEAP_MEMORY =
+            Sensors.newLongSensor("java.metrics.heap.init", "Initial heap size (bytes)");
+    AttributeSensor<Long> COMMITTED_HEAP_MEMORY =
+            Sensors.newLongSensor("java.metrics.heap.committed", "Commited heap size (bytes)");
+    AttributeSensor<Long> MAX_HEAP_MEMORY =
+            Sensors.newLongSensor("java.metrics.heap.max", "Max heap size (bytes)");
+    AttributeSensor<Long> NON_HEAP_MEMORY_USAGE =
+            Sensors.newLongSensor("java.metrics.nonheap.used", "Current non-heap size (bytes)");
+    AttributeSensor<Integer> CURRENT_THREAD_COUNT =
+            Sensors.newIntegerSensor( "java.metrics.threads.current", "Current number of threads");
+    AttributeSensor<Integer> PEAK_THREAD_COUNT =
+            Sensors.newIntegerSensor("java.metrics.threads.max", "Peak number of threads");
+
+    // runtime system attributes
+    AttributeSensor<Long> START_TIME =
+            Sensors.newLongSensor("java.metrics.starttime", "Start time of Java process (UTC)");
+    AttributeSensor<Long> UP_TIME =
+            Sensors.newLongSensor("java.metrics.uptime", "Uptime of Java process (millis, elapsed since start)");
+    
+    //operating system attributes
+    AttributeSensor<Double> PROCESS_CPU_TIME = Sensors.newDoubleSensor( 
+            "java.metrics.processCpuTime.total", "Process CPU time (total millis since start)");
+    AttributeSensor<Double> PROCESS_CPU_TIME_FRACTION_LAST = Sensors.newDoubleSensor( 
+            "java.metrics.processCpuTime.fraction.last", "Fraction of CPU time used, reported by JVM (percentage, last datapoint)");
+    AttributeSensor<Double> PROCESS_CPU_TIME_FRACTION_IN_WINDOW = Sensors.newDoubleSensor( 
+            "java.metrics.processCpuTime.fraction.windowed", "Fraction of CPU time used, reported by JVM (percentage, over time window)");
+    
+    AttributeSensor<Integer> AVAILABLE_PROCESSORS =
+            Sensors.newIntegerSensor("java.metrics.processors.available", "number of processors available to the Java virtual machine");
+    AttributeSensor<Double> SYSTEM_LOAD_AVERAGE
+            = Sensors.newDoubleSensor("java.metrics.systemload.average", "average system load");
+    AttributeSensor<Long> TOTAL_PHYSICAL_MEMORY_SIZE =
+            Sensors.newLongSensor("java.metrics.physicalmemory.total", "The physical memory available to the operating system");
+    AttributeSensor<Long> FREE_PHYSICAL_MEMORY_SIZE =
+            Sensors.newLongSensor("java.metrics.physicalmemory.free", "The free memory available to the operating system");
+
+    // GC attributes
+    AttributeSensor<Map> GARBAGE_COLLECTION_TIME = new BasicAttributeSensor<Map>(Map.class, "java.metrics.gc.time", "garbage collection time");
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJmx.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJmx.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJmx.java
new file mode 100644
index 0000000..4831826
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/UsesJmx.java
@@ -0,0 +1,190 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import java.security.PrivateKey;
+import java.security.cert.Certificate;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.location.PortRange;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.BasicConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.sensor.core.AttributeSensorAndConfigKey;
+import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
+import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+
+public interface UsesJmx extends UsesJava {
+
+    public static final int DEFAULT_JMX_PORT = 1099; // RMI port?
+
+    @SetFromFlag("useJmx")
+    ConfigKey<Boolean> USE_JMX = ConfigKeys.newConfigKey("jmx.enabled", "JMX enabled", Boolean.TRUE);
+
+    /** Chosen by Java itself by default, setting this will only have any effect if using an agent. */
+    @SetFromFlag("jmxPort")
+    PortAttributeSensorAndConfigKey JMX_PORT = new PortAttributeSensorAndConfigKey(
+        "jmx.direct.port", "JMX direct/private port (e.g. JMX RMI server port, or JMXMP port, but not RMI registry port)", PortRanges.fromString("31001+"));
+    
+    // Default is deliberately null for this unused config; if we used "31001+" then we'd potentially give this sensor 
+    // the value 31001 and jmx.direct.port the value 31002. See https://issues.apache.org/jira/browse/BROOKLYN-98
+    /** @deprecated since 0.7.0, kept for rebinding with the anonymous class; code should only ever use {@link #JMX_PORT} */ @Deprecated
+    PortAttributeSensorAndConfigKey JMX_PORT_LEGACY = new PortAttributeSensorAndConfigKey(
+            "jmx.direct.port.legacy.NOT_USED", "Legacy definition JMX direct/private port (e.g. JMX RMI server port, or JMXMP port, but not RMI registry port)", null) {
+        private static final long serialVersionUID = 3846846080809179437L;
+        @Override protected Integer convertConfigToSensor(PortRange value, Entity entity) {
+            // TODO when using JmxAgentModes.NONE we should *not* convert, but leave it null
+            // (e.g. to prevent a warning in e.g. ActiveMQIntegrationTest)
+            // [there was - previously - a note about needing to move these keys to UsesJmx,
+            // that has been done, so not sure if there is anything more needed or if we can just
+            // check here entity.getConfig(JMX_AGENT_MODE) ... needs testing of course]
+            return super.convertConfigToSensor(value, entity);
+        }
+    };
+    
+    /** Well-known port used by Java itself to start the RMI registry where JMX private port can be discovered, ignored if using JMXMP agent. */
+    @SetFromFlag("rmiRegistryPort")
+    PortAttributeSensorAndConfigKey RMI_REGISTRY_PORT = ConfigKeys.newPortSensorAndConfigKey(
+            "rmi.registry.port", "RMI registry port, used for discovering JMX (private) port", PortRanges.fromString("1099,19099+"));
+
+    @SetFromFlag("jmxContext")
+    AttributeSensorAndConfigKey<String, String> JMX_CONTEXT = ConfigKeys.newStringSensorAndConfigKey("jmx.context", "JMX context path", "jmxrmi");
+
+    AttributeSensor<String> JMX_URL = new BasicAttributeSensorAndConfigKey<String>(
+            String.class, "jmx.service.url", "The URL for connecting to the MBean Server");
+
+    /** Forces JMX to be secured, using JMXMP so it gets through firewalls <em>and</em> SSL/TLS. */
+    @SetFromFlag("jmxSecure")
+    ConfigKey<Boolean> JMX_SSL_ENABLED = ConfigKeys.newBooleanConfigKey("jmx.ssl.enabled", "JMX over JMXMP enabled with SSL/TLS", Boolean.FALSE);
+
+    enum JmxAgentModes {
+        /** Auto-detect the agent to use based on location. Prefer {@link #JMXMP} except at localhost which uses {@link #JMX_RMI_CUSTOM_AGENT}. */
+        AUTODETECT,
+
+        /** JMXMP which permits firewall access through a single port {@link UsesJmx#JMX_PORT}. */
+        JMXMP,
+
+        /** Start {@link #JMXMP} along with an RMI Registry on {@link UsesJmx#RMI_REGISTRY_PORT}, redirecting to an anonymous high-numbered port as the RMI server. */
+        JMXMP_AND_RMI,
+
+        /** JMX over RMI custom agent which permits access through a known {@link UsesJmx#RMI_REGISTRY_PORT}, redirected to a known {@link UsesJmx#JMX_PORT}.
+         * Both ports must be opened on the firewall, and the same hostname resolvable on the target machine and by the client */
+        JMX_RMI_CUSTOM_AGENT,
+
+        /** As with {@link UsesJmx#JMX_RMI_CUSTOM_AGENT} but no custom agent requred, entity must handle pots correctly.  */
+        JMX_RMI,
+
+        /** Do not install a JMX agent. Use the default {@link UsesJmx#RMI_REGISTRY_PORT}, redirected to an unknown port for JMX. */
+        NONE
+    }
+
+    @SetFromFlag("jmxAgentMode")
+    ConfigKey<JmxAgentModes> JMX_AGENT_MODE = ConfigKeys.newConfigKey("jmx.agent.mode",
+            "What type of JMX agent to use; defaults to null (autodetect) which means " +
+            "JMXMP_AND_RMI allowing firewall access through a single port as well as local access supporting jconsole " +
+            "(unless JMX_SSL_ENABLED is set, in which case it is JMXMP only)",
+            JmxAgentModes.AUTODETECT);
+
+    /* Currently these are only used to connect, so only applies where systems set this up themselves. */
+    AttributeSensorAndConfigKey<String, String> JMX_USER = ConfigKeys.newStringSensorAndConfigKey("jmx.user", "JMX username");
+    AttributeSensorAndConfigKey<String, String> JMX_PASSWORD = ConfigKeys.newStringSensorAndConfigKey("jmx.password", "JMX password");
+    
+    AttributeSensorAndConfigKey<String, String> JMX_AGENT_LOCAL_PATH = ConfigKeys.newStringSensorAndConfigKey("jmx.agent.local.path", "Path to JMX driver on the local machine");
+
+    /*
+     * Synopsis of how the keys work for JMX_SSL:
+     *
+     * BROOKLYN
+     *  * brooklyn ROOT key + cert ->
+     *      used to identify things brooklyn has signed, ie to confirm their identity
+     *      signs all certs created by brooklyn
+     *      (created per entity if not specified as input)
+     *  * brooklyn JMX ACCESS key + cert ->
+     *      used to authenticate brooklyn to remote JMX agent
+     *      typically, but not necessarily, signed by ROOT cert
+     *      (typically created per entity, unless specified;
+     *      global would probably be fine but more work;
+     *      however it is important that this _not_ sign agents keys,
+     *      to prevent agents from accessing other agents)
+     *
+     * AGENT (e.g. JMX server in each managed java process)
+     *  * gets AGENT key + cert ->
+     *      signed by brooklyn ROOT, used to authenticate itself to brooklyn
+     *      (brooklyn trusts this; does not need to remember this)
+     *  * trusts only the relevant brooklyn JMX ACCESS key (its truststore contains that cert)
+     */
+
+    /* TODO brooklyn ROOT key
+     *
+    public static final ConfigKey<String> BROOKLYN_SSL_ROOT_KEYSTORE_URL = new BasicConfigKey<String>(
+            String.class, "brooklyn.ssl.root.keyStoreUrl", "URL to keystore Brooklyn should use as root private key and certificate-signing authority", null);
+
+    public static final ConfigKey<String> BROOKLYN_SSL_ROOT_KEY_DATA = new BasicConfigKey<String>(
+            String.class, "brooklyn.ssl.root.key", "root private key (RSA string format), used to sign managed servers", null);
+    public static final ConfigKey<String> BROOKLYN_SSL_ROOT_CERT_DATA = new BasicConfigKey<String>(
+            String.class, "brooklyn.ssl.root.cert", "certificate for root private key (RSA string format)", null);
+
+     * brooklyn.ssl.root.keyStorePassword
+     * brooklyn.ssl.root.keyAlias (if null, looks for one called 'brooklyn', otherwise takes the first key)
+     * brooklyn.ssl.root.keyPassword
+     */
+
+    public static final ConfigKey<PrivateKey> JMX_SSL_ACCESS_KEY = new BasicConfigKey<PrivateKey>(
+            PrivateKey.class, "jmx.ssl.access.key", "key used to access a JMX agent (typically per entity, embedded in the managed JVM)", null);
+    public static final ConfigKey<Certificate> JMX_SSL_ACCESS_CERT = new BasicConfigKey<Certificate>(
+            Certificate.class, "jmx.ssl.access.cert", "certificate of key used to access a JMX agent", null);
+
+    /* TODO specify a keystore from which to get the access key
+     * (above keys are set programmatically, typically _not_ by the user ... keystore would be the way to do that)
+     *
+     * jmx.ssl.access.keyStoreUrl (optional)
+     * jmx.ssl.access.keyStorePassword (optional)
+     * jmx.ssl.access.keyAlias (optional)
+     */
+
+    /* could allow user to specify additional certs for JMX agents which should be trusted
+     *
+     * jmx.ssl.access.trustStoreUrl
+     */
+
+    /* optionally: could allow JMX agent to trust additional accessers,
+     * and/or use known keys in the case that other accessers might want to authenticate the JMX server
+     *
+     * NB currently agent keys are not stored in brooklyn... no reason to as
+     * (a) currently we trust jmx agents; and (b) for agent-auth we should simply sign keys;
+     * either way, seems fine for brooklyn to throw them away once they are installed on the remote machine)
+     *
+     * jmx.ssl.agent.keyStoreUrl
+     * jmx.ssl.agent.keyStorePassword
+     * jmx.ssl.agent.keyAlias
+     * jmx.ssl.agent.keyPassword
+     *
+     * jmx.ssl.agent.trustStoreUrl
+     */
+
+    /* optionally: this could be set to disallow attaching to JMX through the attach mechanism
+     * (but this option is generally not considered needed, as JVM attachment is
+     * already restricted to localhost and to the the user running the process)
+     *
+     * -XX:+DisableAttachMechanism
+     */
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaApp.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaApp.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaApp.java
new file mode 100644
index 0000000..9319406
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaApp.java
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+
+@ImplementedBy(VanillaJavaAppImpl.class)
+public interface VanillaJavaApp extends SoftwareProcess, UsesJava, UsesJmx, UsesJavaMXBeans {
+
+    // TODO Make jmxPollPeriod @SetFromFlag easier to use: currently a confusion over long and TimeDuration, and 
+    // no ability to set default value (can't just set field because config vals read/set in super-constructor :-(
+
+    @SetFromFlag("args")
+    ConfigKey<List> ARGS = ConfigKeys.newConfigKey(List.class,
+            "vanillaJavaApp.args", "Arguments for launching the java app", Lists.newArrayList());
+    
+    @SetFromFlag(value="main", nullable=false)
+    ConfigKey<String> MAIN_CLASS = ConfigKeys.newStringConfigKey("vanillaJavaApp.mainClass", "class to launch");
+
+    @SetFromFlag("classpath")
+    ConfigKey<List> CLASSPATH = ConfigKeys.newConfigKey(List.class,
+            "vanillaJavaApp.classpath", "classpath to use, as list of URL entries; " +
+            "these URLs are copied to lib/ and expanded in the case of tar/tgz/zip",
+            Lists.newArrayList());
+
+    AttributeSensor<List> CLASSPATH_FILES = Sensors.newSensor(List.class,
+            "vanillaJavaApp.classpathFiles", "classpath used, list of files");
+
+    @SetFromFlag("jvmXArgs")
+    ConfigKey<List> JVM_XARGS = ConfigKeys.newConfigKey(List.class,
+            "vanillaJavaApp.jvmXArgs", "JVM -X args for the java app (e.g. memory)", 
+            MutableList.of("-Xms128m", "-Xmx512m", "-XX:MaxPermSize=512m"));
+
+    @SetFromFlag("jvmDefines")
+    ConfigKey<Map> JVM_DEFINES = ConfigKeys.newConfigKey(Map.class,
+            "vanillaJavaApp.jvmDefines", "JVM system property definitions for the app",
+            Maps.newLinkedHashMap());
+
+    public String getMainClass();
+    public List<String> getClasspath();
+    public List<String> getClasspathFiles();
+    public Map getJvmDefines();
+    public List getJvmXArgs();
+    public String getRunDir();
+
+    public void kill();
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppDriver.java
new file mode 100644
index 0000000..fd8c624
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppDriver.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+/**
+ * The {@link JavaSoftwareProcessDriver} for a {@link VanillaJavaApp}.
+ */
+public interface VanillaJavaAppDriver extends JavaSoftwareProcessDriver {
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppImpl.java
new file mode 100644
index 0000000..a81de86
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppImpl.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.annotations.VisibleForTesting;
+
+public class VanillaJavaAppImpl extends SoftwareProcessImpl implements VanillaJavaApp {
+
+    static {
+        JavaAppUtils.init();
+    }
+
+    private static final Logger log = LoggerFactory.getLogger(VanillaJavaApp.class);
+
+    @SetFromFlag
+    protected long jmxPollPeriod;
+
+    protected JmxFeed jmxFeed;
+
+    public VanillaJavaAppImpl() {}
+
+    @VisibleForTesting
+    public VanillaJavaAppImpl(Map<?,?> properties, Entity parent) {
+        super(properties, parent);
+    }
+
+    public String getMainClass() { return getConfig(MAIN_CLASS); }
+    public List<String> getClasspath() { return getConfig(CLASSPATH); }
+    public List<String> getClasspathFiles() { return getAttribute(CLASSPATH_FILES); }
+    public Map getJvmDefines() { return getConfig(JVM_DEFINES); }
+    public List getJvmXArgs() { return getConfig(JVM_XARGS); }
+
+    public void addToClasspath(String url) {
+        List<String> cp = getConfig(CLASSPATH);
+        List<String> newCP = new ArrayList<String>();
+        if (cp!=null) newCP.addAll(cp);
+        newCP.add(url);
+        setConfig(CLASSPATH, newCP);
+    }
+
+    public void addToClasspath(Collection<String> urls) {
+        List<String> cp = getConfig(CLASSPATH);
+        List<String> newCP = new ArrayList<String>();
+        if (cp!=null) newCP.addAll(cp);
+        newCP.addAll(urls);
+        setConfig(CLASSPATH, newCP);
+    }
+
+    @Override
+    protected void connectSensors() {
+        super.connectSensors();
+
+        if (((VanillaJavaAppDriver) getDriver()).isJmxEnabled()) {
+            jmxPollPeriod = (jmxPollPeriod > 0) ? jmxPollPeriod : 3000;
+            jmxFeed = JavaAppUtils.connectMXBeanSensors(this, jmxPollPeriod);
+        }
+
+        connectServiceUpIsRunning();
+    }
+
+    @Override
+    public void disconnectSensors() {
+        super.disconnectSensors();
+        disconnectServiceUpIsRunning();
+        if (jmxFeed != null) jmxFeed.stop();
+    }
+
+    @Override
+    public Class<? extends VanillaJavaAppDriver> getDriverInterface() {
+        return VanillaJavaAppDriver.class;
+    }
+
+    public String getRunDir() {
+        // FIXME Make this an attribute; don't assume it hsa to be ssh? What uses this?
+        VanillaJavaAppSshDriver driver = (VanillaJavaAppSshDriver) getDriver();
+        return (driver != null) ? driver.getRunDir() : null;
+    }
+
+    @Override
+    public void kill() {
+        getDriver().kill();
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppSshDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppSshDriver.java
new file mode 100644
index 0000000..011f4ff
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/java/VanillaJavaAppSshDriver.java
@@ -0,0 +1,211 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import static java.lang.String.format;
+
+import java.io.File;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelper;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.file.ArchiveBuilder;
+import org.apache.brooklyn.util.core.file.ArchiveUtils;
+import org.apache.brooklyn.util.core.internal.ssh.SshTool;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.net.Urls;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.text.StringEscapes.BashStringEscapes;
+
+import com.google.common.base.CharMatcher;
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
+import com.google.common.base.Splitter;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+
+/**
+ * The SSH implementation of the {@link VanillaJavaAppDriver}.
+ */
+public class VanillaJavaAppSshDriver extends JavaSoftwareProcessSshDriver implements VanillaJavaAppDriver {
+
+    // FIXME this should be a config, either on the entity or -- probably better -- 
+    // an alternative / override timeout on the SshTool for file copy commands
+    final static int NUM_RETRIES_FOR_COPYING = 4;
+    
+    public VanillaJavaAppSshDriver(VanillaJavaAppImpl entity, SshMachineLocation machine) {
+        super(entity, machine);
+    }
+
+    @Override
+    public VanillaJavaAppImpl getEntity() {
+        return (VanillaJavaAppImpl) super.getEntity();
+    }
+
+    @Override
+    protected String getLogFileLocation() {
+        return Os.mergePathsUnix(getRunDir(), "console");
+    }
+
+    @Override
+    public void install() {
+        newScript(INSTALLING).execute();
+    }
+
+    @Override
+    public void customize() {
+        newScript(CUSTOMIZING)
+                .body.append(format("mkdir -p %s/lib", getRunDir()))
+                .failOnNonZeroResultCode()
+                .execute();
+
+        SshMachineLocation machine = getMachine();
+        VanillaJavaApp entity = getEntity();
+        for (String entry : entity.getClasspath()) {
+            // If a local folder, then create archive from contents first
+            if (Urls.isDirectory(entry)) {
+                File jarFile = ArchiveBuilder.jar().addDirContentsAt(new File(entry), "").create();
+                entry = jarFile.getAbsolutePath();
+            }
+
+            // Determine filename
+            String destFile = entry.contains("?") ? entry.substring(0, entry.indexOf('?')) : entry;
+            destFile = destFile.substring(destFile.lastIndexOf('/') + 1);
+
+            ArchiveUtils.deploy(MutableMap.<String, Object>of(), entry, machine, getRunDir(), Os.mergePaths(getRunDir(), "lib"), destFile);
+        }
+
+        ScriptHelper helper = newScript(CUSTOMIZING+"-classpath")
+                .body.append(String.format("ls -1 \"%s\"", Os.mergePaths(getRunDir(), "lib")))
+                .gatherOutput();
+        helper.setFlag(SshTool.PROP_NO_EXTRA_OUTPUT, true);
+        int result = helper.execute();
+        if (result != 0) {
+            throw new IllegalStateException("Error listing classpath files: " + helper.getResultStderr());
+        }
+        String stdout = helper.getResultStdout();
+
+        // Transform stdout into list of files in classpath
+        if (Strings.isBlank(stdout)) {
+            getEntity().setAttribute(VanillaJavaApp.CLASSPATH_FILES, ImmutableList.of(Os.mergePaths(getRunDir(), "lib")));
+        } else {
+            // FIXME Cannot handle spaces in paths properly
+            Iterable<String> lines = Splitter.on(CharMatcher.BREAKING_WHITESPACE).omitEmptyStrings().trimResults().split(stdout);
+            Iterable<String> files = Iterables.transform(lines, new Function<String, String>() {
+                        @Override
+                        public String apply(@Nullable String input) {
+                            return Os.mergePathsUnix(getRunDir(), "lib", input);
+                        }
+                    });
+            getEntity().setAttribute(VanillaJavaApp.CLASSPATH_FILES, ImmutableList.copyOf(files));
+        }
+    }
+
+    public String getClasspath() {
+        @SuppressWarnings("unchecked")
+        List<String> files = getEntity().getAttribute(VanillaJavaApp.CLASSPATH_FILES);
+        if (files == null || files.isEmpty()) {
+            return null;
+        } else {
+            return Joiner.on(":").join(files);
+        }
+    }
+
+    @Override
+    public void launch() {
+        String clazz = getEntity().getMainClass();
+        String args = getArgs();
+
+        newScript(MutableMap.of(USE_PID_FILE, true), LAUNCHING)
+            .body.append(
+                    format("echo \"launching: java $JAVA_OPTS %s %s\"", clazz, args),
+                    format("java $JAVA_OPTS -cp \"%s\" %s %s >> %s/console 2>&1 </dev/null &", getClasspath(), clazz, args, getRunDir())
+                )
+            .execute();
+    }
+
+    public String getArgs(){
+        List<Object> args = getEntity().getConfig(VanillaJavaApp.ARGS);
+        StringBuilder sb = new StringBuilder();
+        Iterator<Object> it = args.iterator();
+        while (it.hasNext()) {
+            Object argO = it.next();
+            try {
+                String arg = Tasks.resolveValue(argO, String.class, getEntity().getExecutionContext());
+                BashStringEscapes.assertValidForDoubleQuotingInBash(arg);
+                sb.append(format("\"%s\"",arg));
+            } catch (Exception e) {
+                throw Exceptions.propagate(e);
+            }
+            if (it.hasNext()) {
+                sb.append(" ");
+            }
+        }
+
+        return sb.toString();
+    }
+
+    @Override
+    public boolean isRunning() {
+        int result = newScript(MutableMap.of(USE_PID_FILE, true), CHECK_RUNNING).execute();
+        return result == 0;
+    }
+
+    @Override
+    public void stop() {
+        newScript(MutableMap.of(USE_PID_FILE, true), STOPPING).execute();
+    }
+
+    @Override
+    public void kill() {
+        newScript(MutableMap.of(USE_PID_FILE, true), KILLING).execute();
+    }
+
+    @Override
+    protected Map getCustomJavaSystemProperties() {
+        return MutableMap.builder()
+                .putAll(super.getCustomJavaSystemProperties())
+                .putAll(getEntity().getJvmDefines())
+                .build();
+    }
+
+    @Override
+    protected List<String> getCustomJavaConfigOptions() {
+        return MutableList.<String>builder()
+                .addAll(super.getCustomJavaConfigOptions())
+                .addAll(getEntity().getJvmXArgs())
+                .build();
+    }
+
+    @Override
+    public Map<String,String> getShellEnvironment() {
+        return MutableMap.<String,String>builder()
+                .putAll(super.getShellEnvironment())
+                .putIfNotNull("CLASSPATH", getClasspath())
+                .build();
+    }
+}



[03/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitNodeImpl.java b/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitNodeImpl.java
index 7b64937..e23981f 100644
--- a/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitNodeImpl.java
+++ b/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitNodeImpl.java
@@ -22,6 +22,7 @@ import java.util.Map;
 
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.ssh.SshFeed;
 import org.apache.brooklyn.sensor.feed.ssh.SshPollConfig;
@@ -34,8 +35,6 @@ import org.slf4j.LoggerFactory;
 import com.google.common.base.Function;
 import com.google.common.collect.Iterables;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 public class MonitNodeImpl extends SoftwareProcessImpl implements MonitNode {
     
     private static final Logger LOG = LoggerFactory.getLogger(MonitNodeImpl.class);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitSshDriver.java
----------------------------------------------------------------------
diff --git a/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitSshDriver.java b/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitSshDriver.java
index c24b21d..511b3b0 100644
--- a/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitSshDriver.java
+++ b/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitSshDriver.java
@@ -25,6 +25,8 @@ import java.util.Map;
 
 import org.apache.brooklyn.api.location.OsDetails;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelper;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.os.Os;
@@ -33,9 +35,6 @@ import org.apache.brooklyn.util.ssh.BashCommands;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-import brooklyn.entity.basic.lifecycle.ScriptHelper;
-
 public class MonitSshDriver extends AbstractSoftwareProcessSshDriver implements MonitDriver {
     
     private String remoteControlFilePath;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/monitoring/src/test/java/org/apache/brooklyn/entity/monitoring/monit/MonitIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/monitoring/src/test/java/org/apache/brooklyn/entity/monitoring/monit/MonitIntegrationTest.java b/software/monitoring/src/test/java/org/apache/brooklyn/entity/monitoring/monit/MonitIntegrationTest.java
index 7719451..41eb9d2 100644
--- a/software/monitoring/src/test/java/org/apache/brooklyn/entity/monitoring/monit/MonitIntegrationTest.java
+++ b/software/monitoring/src/test/java/org/apache/brooklyn/entity/monitoring/monit/MonitIntegrationTest.java
@@ -32,6 +32,8 @@ import org.apache.brooklyn.api.location.MachineDetails;
 import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.database.mysql.MySqlNode;
+import org.apache.brooklyn.entity.software.base.SameServerEntity;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
 import org.apache.brooklyn.test.Asserts;
@@ -47,9 +49,6 @@ import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.io.Files;
 
-import brooklyn.entity.basic.SameServerEntity;
-import brooklyn.entity.basic.SoftwareProcess;
-
 public class MonitIntegrationTest extends BrooklynAppLiveTestSupport {
 
     private static final Logger LOG = LoggerFactory.getLogger(MonitIntegrationTest.class);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServer.java
----------------------------------------------------------------------
diff --git a/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServer.java b/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServer.java
index c21a3a8..b848555 100644
--- a/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServer.java
+++ b/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServer.java
@@ -33,9 +33,7 @@ import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.entity.annotation.Effector;
 import org.apache.brooklyn.entity.group.DynamicGroup;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.location.basic.PortRanges;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.Sensors;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerDriver.java
----------------------------------------------------------------------
diff --git a/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerDriver.java b/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerDriver.java
index 50a1994..8eb7d57 100644
--- a/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerDriver.java
+++ b/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerDriver.java
@@ -18,9 +18,9 @@
  */
 package org.apache.brooklyn.entity.network.bind;
 
-import com.google.common.annotations.VisibleForTesting;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
+import com.google.common.annotations.VisibleForTesting;
 
 public interface BindDnsServerDriver extends SoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerImpl.java
----------------------------------------------------------------------
diff --git a/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerImpl.java b/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerImpl.java
index a0916da..6d263b3 100644
--- a/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerImpl.java
+++ b/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerImpl.java
@@ -33,6 +33,7 @@ import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.group.AbstractMembershipTrackingPolicy;
 import org.apache.brooklyn.entity.group.DynamicGroup;
 import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -56,8 +57,6 @@ import com.google.common.collect.Multimap;
 import com.google.common.collect.MultimapBuilder;
 import com.google.common.collect.Multimaps;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import org.apache.brooklyn.location.basic.Machines;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.guava.Maybe;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerSshDriver.java
----------------------------------------------------------------------
diff --git a/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerSshDriver.java b/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerSshDriver.java
index f7b707a..e60955d 100644
--- a/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerSshDriver.java
+++ b/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerSshDriver.java
@@ -28,8 +28,7 @@ import org.slf4j.LoggerFactory;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
 
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerEc2LiveTest.java b/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerEc2LiveTest.java
index 7347a26..7c6391a 100644
--- a/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerEc2LiveTest.java
+++ b/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerEc2LiveTest.java
@@ -20,10 +20,8 @@ package org.apache.brooklyn.entity.network.bind;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 
 public class BindDnsServerEc2LiveTest extends AbstractEc2LiveTest {
     private static final Logger LOG = LoggerFactory.getLogger(BindDnsServerEc2LiveTest.class);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerIntegrationTest.java b/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerIntegrationTest.java
index 824ff04..0b7b90b 100644
--- a/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerIntegrationTest.java
+++ b/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerIntegrationTest.java
@@ -32,6 +32,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.core.EntityPredicates;
 import org.apache.brooklyn.entity.factory.ApplicationBuilder;
 import org.apache.brooklyn.entity.group.DynamicCluster;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
 import org.apache.brooklyn.sensor.enricher.Enrichers;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.slf4j.Logger;
@@ -47,8 +48,6 @@ import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Iterables;
 
-import brooklyn.entity.basic.EmptySoftwareProcess;
-
 public class BindDnsServerIntegrationTest extends RebindTestFixture<TestApplication> {
 
     private static final Logger LOG = LoggerFactory.getLogger(BindDnsServerIntegrationTest.class);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerLiveTest.java
----------------------------------------------------------------------
diff --git a/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerLiveTest.java b/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerLiveTest.java
index d79d69d..7ca5ee6 100644
--- a/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerLiveTest.java
+++ b/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerLiveTest.java
@@ -28,6 +28,8 @@ import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.group.DynamicCluster;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SameServerEntity;
 import org.apache.brooklyn.util.repeat.Repeater;
 import org.apache.brooklyn.util.time.Duration;
 import org.slf4j.Logger;
@@ -38,9 +40,6 @@ import com.google.common.base.Predicate;
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;
 
-import brooklyn.entity.basic.EmptySoftwareProcess;
-import brooklyn.entity.basic.SameServerEntity;
-
 public class BindDnsServerLiveTest {
 
     private static final Logger LOG = LoggerFactory.getLogger(BindDnsServerLiveTest.class);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerSoftlayerLiveTest.java
----------------------------------------------------------------------
diff --git a/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerSoftlayerLiveTest.java b/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerSoftlayerLiveTest.java
index 01a0d1e..f65672c 100644
--- a/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerSoftlayerLiveTest.java
+++ b/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/BindDnsServerSoftlayerLiveTest.java
@@ -19,10 +19,8 @@
 package org.apache.brooklyn.entity.network.bind;
 
 import org.testng.annotations.Test;
-
-import brooklyn.entity.AbstractSoftlayerLiveTest;
-
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractSoftlayerLiveTest;
 
 public class BindDnsServerSoftlayerLiveTest extends AbstractSoftlayerLiveTest {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/DoNothingSoftwareProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/DoNothingSoftwareProcessDriver.java b/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/DoNothingSoftwareProcessDriver.java
index 928dfe0..d12269f 100644
--- a/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/DoNothingSoftwareProcessDriver.java
+++ b/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/DoNothingSoftwareProcessDriver.java
@@ -19,13 +19,11 @@
 package org.apache.brooklyn.entity.network.bind;
 
 import org.apache.brooklyn.api.internal.EntityLocal;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 
 /**
- * Implements methods in {@link brooklyn.entity.basic.AbstractSoftwareProcessSshDriver}.
+ * Implements methods in {@link org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver}.
  * {@link #isRunning()} returns true.
  */
 public class DoNothingSoftwareProcessDriver extends AbstractSoftwareProcessSshDriver {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNode.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNode.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNode.java
index c477539..0919476 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNode.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNode.java
@@ -29,15 +29,11 @@ import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.BasicConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
 import org.apache.brooklyn.entity.database.DatastoreMixins;
-
-import brooklyn.entity.java.UsesJavaMXBeans;
-import brooklyn.entity.java.UsesJmx;
-
+import org.apache.brooklyn.entity.java.UsesJavaMXBeans;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.location.basic.PortRanges;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeDriver.java
index 8a21d52..3893373 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeDriver.java
@@ -18,10 +18,9 @@
  */
 package org.apache.brooklyn.entity.nosql.cassandra;
 
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessDriver;
 import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
 
-import brooklyn.entity.java.JavaSoftwareProcessDriver;
-
 public interface CassandraNodeDriver extends JavaSoftwareProcessDriver {
 
     Integer getGossipPort();

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeImpl.java
index aabb0eb..fd24985 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeImpl.java
@@ -39,16 +39,10 @@ import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.effector.core.EffectorBody;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.JavaAppUtils;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcessImpl;
-import brooklyn.entity.java.JavaAppUtils;
-import brooklyn.event.feed.jmx.JmxAttributePollConfig;
-import brooklyn.event.feed.jmx.JmxFeed;
-import brooklyn.event.feed.jmx.JmxHelper;
-import brooklyn.event.feed.jmx.JmxOperationPollConfig;
-
 import org.apache.brooklyn.location.basic.Machines;
 import org.apache.brooklyn.location.cloud.CloudLocationConfig;
 import org.apache.brooklyn.policy.enricher.RollingTimeWindowMeanEnricher;
@@ -57,6 +51,10 @@ import org.apache.brooklyn.sensor.core.DependentConfiguration;
 import org.apache.brooklyn.sensor.core.Sensors;
 import org.apache.brooklyn.sensor.feed.function.FunctionFeed;
 import org.apache.brooklyn.sensor.feed.function.FunctionPollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxAttributePollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
+import org.apache.brooklyn.sensor.feed.jmx.JmxHelper;
+import org.apache.brooklyn.sensor.feed.jmx.JmxOperationPollConfig;
 import org.apache.brooklyn.util.collections.MutableSet;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 import org.apache.brooklyn.util.core.text.TemplateProcessor;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeSshDriver.java
index c8c8042..7ee2b95 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeSshDriver.java
@@ -41,15 +41,13 @@ import com.google.common.collect.ImmutableSet;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.database.DatastoreMixins;
-
-import brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-import brooklyn.entity.java.UsesJmx;
-import brooklyn.entity.software.SshEffectorTasks;
-
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
 import org.apache.brooklyn.location.basic.Machines;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.collections.MutableSet;
 import org.apache.brooklyn.util.core.task.DynamicTasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseClusterImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseClusterImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseClusterImpl.java
index bea9a5e..7b6d5d8 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseClusterImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseClusterImpl.java
@@ -41,12 +41,10 @@ import org.apache.brooklyn.entity.core.EntityInternal;
 import org.apache.brooklyn.entity.group.AbstractMembershipTrackingPolicy;
 import org.apache.brooklyn.entity.group.DynamicClusterImpl;
 import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
 import org.apache.brooklyn.sensor.enricher.Enrichers;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNode.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNode.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNode.java
index 935eed4..a4d92b6 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNode.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNode.java
@@ -31,14 +31,13 @@ import org.apache.brooklyn.effector.core.MethodEffector;
 import org.apache.brooklyn.entity.annotation.Effector;
 import org.apache.brooklyn.entity.annotation.EffectorParam;
 import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.Sensors;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 import org.apache.brooklyn.util.text.ByteSizeStrings;
 
-import brooklyn.entity.basic.SoftwareProcess;
-
 @Catalog(name="CouchBase Node", description="Couchbase Server is an open source, distributed (shared-nothing architecture) "
         + "NoSQL document-oriented database that is optimized for interactive applications.")
 @ImplementedBy(CouchbaseNodeImpl.class)

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeDriver.java
index 48439ce..b5c797d 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeDriver.java
@@ -19,8 +19,7 @@
 package org.apache.brooklyn.entity.nosql.couchbase;
 
 import org.apache.brooklyn.api.entity.Entity;
-
-import brooklyn.entity.basic.SoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 
 public interface CouchbaseNodeDriver extends SoftwareProcessDriver {
     public String getOsTag();

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeImpl.java
index 1b53cec..6c9bec8 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeImpl.java
@@ -32,12 +32,10 @@ import org.apache.brooklyn.api.sensor.SensorEvent;
 import org.apache.brooklyn.api.sensor.SensorEventListener;
 import org.apache.brooklyn.effector.core.EffectorBody;
 import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.http.auth.UsernamePasswordCredentials;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
 import org.apache.brooklyn.location.cloud.CloudLocationConfig;
 import org.apache.brooklyn.sensor.feed.http.HttpFeed;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeSshDriver.java
index cbc2457..b637210 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeSshDriver.java
@@ -38,15 +38,13 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.drivers.downloads.BasicDownloadRequirement;
 import org.apache.brooklyn.entity.drivers.downloads.DownloadProducerFromUrlAttribute;
 import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.apache.http.auth.UsernamePasswordCredentials;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-import brooklyn.entity.software.SshEffectorTasks;
-
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
 import org.apache.brooklyn.sensor.feed.http.HttpValueFunctions;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.http.HttpTool;
 import org.apache.brooklyn.util.core.http.HttpToolResponse;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGateway.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGateway.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGateway.java
index 55a02dc..9d7d000 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGateway.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGateway.java
@@ -23,13 +23,12 @@ import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.Sensors;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
-import brooklyn.entity.basic.SoftwareProcess;
-
 @ImplementedBy(CouchbaseSyncGatewayImpl.class)
 public interface CouchbaseSyncGateway extends SoftwareProcess {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewayDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewayDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewayDriver.java
index c7feab6..1b29e9f 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewayDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewayDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.nosql.couchbase;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 
 public interface CouchbaseSyncGatewayDriver extends SoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewayImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewayImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewayImpl.java
index 4c1ed12..1931f74 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewayImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewayImpl.java
@@ -18,9 +18,8 @@
  */
 package org.apache.brooklyn.entity.nosql.couchbase;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import org.apache.brooklyn.core.config.render.RendererHints;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
 import org.apache.brooklyn.sensor.feed.http.HttpFeed;
 import org.apache.brooklyn.sensor.feed.http.HttpPollConfig;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewaySshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewaySshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewaySshDriver.java
index 7c31138..7f15f35 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewaySshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewaySshDriver.java
@@ -32,9 +32,7 @@ import org.apache.brooklyn.api.internal.EntityLocal;
 import org.apache.brooklyn.api.location.OsDetails;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.core.EntityPredicates;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
 import org.apache.brooklyn.util.collections.MutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNode.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNode.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNode.java
index a4e1ab2..dd7aef7 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNode.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNode.java
@@ -22,12 +22,11 @@ import org.apache.brooklyn.api.catalog.Catalog;
 import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.WebAppService;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
-import brooklyn.entity.basic.SoftwareProcess;
-
 /**
  * An {@link org.apache.brooklyn.api.entity.Entity} that represents a CouchDB node in a {@link CouchDBCluster}.
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeDriver.java
index 14386a0..59a04b9 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.nosql.couchdb;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 
 public interface CouchDBNodeDriver extends SoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeImpl.java
index d51d8e5..163e126 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeImpl.java
@@ -22,6 +22,7 @@ import java.util.concurrent.TimeUnit;
 
 import javax.annotation.Nullable;
 
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcessImpl;
 import org.apache.brooklyn.entity.webapp.WebAppServiceMethods;
 import org.apache.brooklyn.sensor.feed.http.HttpFeed;
@@ -32,8 +33,6 @@ import org.apache.brooklyn.util.guava.Functionals;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import com.google.common.base.Function;
 import com.google.common.base.Functions;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeSshDriver.java
index 14682c0..3ef5c16 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeSshDriver.java
@@ -26,11 +26,9 @@ import java.util.Set;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNode.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNode.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNode.java
index 34b3cba..8bc238a 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNode.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNode.java
@@ -23,10 +23,8 @@ import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.WebAppServiceConstants;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.entity.database.DatastoreMixins;
 import org.apache.brooklyn.location.basic.PortRanges;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeDriver.java
index bc0e57c..82640cd 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.nosql.elasticsearch;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 
 public interface ElasticSearchNodeDriver extends SoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeImpl.java
index e62d9ce..30e0401 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeImpl.java
@@ -21,9 +21,7 @@ package org.apache.brooklyn.entity.nosql.elasticsearch;
 import static com.google.common.base.Preconditions.checkNotNull;
 
 import org.apache.brooklyn.api.sensor.AttributeSensor;
-
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
 import org.apache.brooklyn.sensor.feed.http.HttpFeed;
 import org.apache.brooklyn.sensor.feed.http.HttpPollConfig;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeSshDriver.java
index a060646..61f9e01 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeSshDriver.java
@@ -27,9 +27,7 @@ import java.util.List;
 import org.apache.brooklyn.api.internal.EntityLocal;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.entity.core.Entities;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Urls;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/AbstractMongoDBServer.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/AbstractMongoDBServer.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/AbstractMongoDBServer.java
index 1847609..159314c 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/AbstractMongoDBServer.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/AbstractMongoDBServer.java
@@ -21,13 +21,12 @@ package org.apache.brooklyn.entity.nosql.mongodb;
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.sensor.core.AttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
-import brooklyn.entity.basic.SoftwareProcess;
-
 public interface AbstractMongoDBServer extends SoftwareProcess, Entity {
 
     // TODO Need to properly test v2.4.x and v2.5.x support.

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/AbstractMongoDBSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/AbstractMongoDBSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/AbstractMongoDBSshDriver.java
index b524c74..3b5ddc6 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/AbstractMongoDBSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/AbstractMongoDBSshDriver.java
@@ -25,12 +25,10 @@ import java.util.Map;
 import org.apache.brooklyn.api.internal.EntityLocal;
 import org.apache.brooklyn.api.location.OsDetails;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-import brooklyn.entity.basic.lifecycle.ScriptHelper;
-
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBClientDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBClientDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBClientDriver.java
index 4bbfabd..f48f743 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBClientDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBClientDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.nosql.mongodb;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 
 public interface MongoDBClientDriver extends SoftwareProcessDriver {
     void runScript(String preStart, String scriptName);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBClientImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBClientImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBClientImpl.java
index c8683a0..9a1a0e9 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBClientImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBClientImpl.java
@@ -18,10 +18,9 @@
  */
 package org.apache.brooklyn.entity.nosql.mongodb;
 
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.entity.trait.Startable;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 public class MongoDBClientImpl extends SoftwareProcessImpl implements MongoDBClient {
     
     @Override

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBDriver.java
index b7d93f0..e66b8e7 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.nosql.mongodb;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 
 public interface MongoDBDriver extends SoftwareProcessDriver {
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBServerImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBServerImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBServerImpl.java
index f930e4a..89d7504 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBServerImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBServerImpl.java
@@ -25,12 +25,10 @@ import java.util.concurrent.TimeUnit;
 import org.apache.brooklyn.api.sensor.SensorEvent;
 import org.apache.brooklyn.api.sensor.SensorEventListener;
 import org.apache.brooklyn.core.config.render.RendererHints;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.bson.BasicBSONObject;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
 import org.apache.brooklyn.sensor.feed.function.FunctionFeed;
 import org.apache.brooklyn.sensor.feed.function.FunctionPollConfig;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/CoLocatedMongoDBRouter.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/CoLocatedMongoDBRouter.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/CoLocatedMongoDBRouter.java
index 5fde133..490455c 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/CoLocatedMongoDBRouter.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/CoLocatedMongoDBRouter.java
@@ -26,11 +26,10 @@ import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.software.base.SameServerEntity;
 import org.apache.brooklyn.sensor.core.Sensors;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
-import brooklyn.entity.basic.SameServerEntity;
-
 import com.google.common.reflect.TypeToken;
 
 @ImplementedBy(CoLocatedMongoDBRouterImpl.class)

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/CoLocatedMongoDBRouterImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/CoLocatedMongoDBRouterImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/CoLocatedMongoDBRouterImpl.java
index 5aaad97..ac25e48 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/CoLocatedMongoDBRouterImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/CoLocatedMongoDBRouterImpl.java
@@ -23,12 +23,11 @@ import java.util.Collection;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.SameServerEntityImpl;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
 import org.apache.brooklyn.sensor.enricher.Enrichers;
 
-import brooklyn.entity.basic.SameServerEntityImpl;
-
 import com.google.common.base.Predicates;
 import com.google.common.collect.Iterables;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerDriver.java
index 7963b22..9ccaccd 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.nosql.mongodb.sharding;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 
 public interface MongoDBConfigServerDriver extends SoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerImpl.java
index b8ce2b8..faa6ed6 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerImpl.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.nosql.mongodb.sharding;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 
 public class MongoDBConfigServerImpl extends SoftwareProcessImpl implements MongoDBConfigServer {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBRouterDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBRouterDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBRouterDriver.java
index 3c7a30c..5ca17ac 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBRouterDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBRouterDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.nosql.mongodb.sharding;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 
 public interface MongoDBRouterDriver extends SoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBRouterImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBRouterImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBRouterImpl.java
index 4d471ef..5698ee6 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBRouterImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBRouterImpl.java
@@ -22,11 +22,10 @@ import java.util.concurrent.Callable;
 import java.util.concurrent.TimeUnit;
 
 import org.apache.brooklyn.entity.nosql.mongodb.MongoDBClientSupport;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.sensor.feed.function.FunctionFeed;
 import org.apache.brooklyn.sensor.feed.function.FunctionPollConfig;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import com.google.common.base.Functions;
 
 public class MongoDBRouterImpl extends SoftwareProcessImpl implements MongoDBRouter {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStore.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStore.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStore.java
index a9b388a..9f27f5f 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStore.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStore.java
@@ -23,13 +23,12 @@ import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.Sensors;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
-import brooklyn.entity.basic.SoftwareProcess;
-
 /**
  * An entity that represents a Redis key-value store service.
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreDriver.java
index ba77cfd..63424ba 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.nosql.redis;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 
 public interface RedisStoreDriver extends SoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreImpl.java
index 020e03f..c92f678 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreImpl.java
@@ -24,11 +24,9 @@ import javax.annotation.Nullable;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.ssh.SshFeed;
 import org.apache.brooklyn.sensor.feed.ssh.SshPollConfig;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreSshDriver.java
index 279185d..4c10689 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreSshDriver.java
@@ -24,11 +24,9 @@ import java.util.List;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.os.Os;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNode.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNode.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNode.java
index a8c014d..ca8eac2 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNode.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNode.java
@@ -30,14 +30,13 @@ import org.apache.brooklyn.effector.core.MethodEffector;
 import org.apache.brooklyn.entity.annotation.Effector;
 import org.apache.brooklyn.entity.annotation.EffectorParam;
 import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.java.UsesJava;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.sensor.core.AttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.Sensors;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.java.UsesJava;
-
 import com.google.common.collect.ImmutableList;
 import com.google.common.reflect.TypeToken;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeDriver.java
index b9339cf..f42c85d 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeDriver.java
@@ -18,10 +18,10 @@
  */
 package org.apache.brooklyn.entity.nosql.riak;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
-
 import java.util.List;
 
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
+
 public interface RiakNodeDriver extends SoftwareProcessDriver {
 
     String getRiakEtcDir();

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeImpl.java
index 9894f10..aa74dff 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeImpl.java
@@ -30,10 +30,8 @@ import javax.annotation.Nullable;
 import org.apache.brooklyn.api.location.MachineProvisioningLocation;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.entity.webapp.WebAppServiceMethods;
-
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
 import org.apache.brooklyn.location.cloud.CloudLocationConfig;
 import org.apache.brooklyn.sensor.core.AttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeSshDriver.java
index cbf515f..d3953dc 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeSshDriver.java
@@ -36,18 +36,15 @@ import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 
-import brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.lifecycle.ScriptHelper;
-import brooklyn.entity.software.SshEffectorTasks;
-
 import org.apache.brooklyn.api.location.OsDetails;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelper;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.task.DynamicTasks;
 import org.apache.brooklyn.util.core.task.ssh.SshTasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServer.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServer.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServer.java
index 31268bf..1b89e07 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServer.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServer.java
@@ -25,12 +25,10 @@ import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.java.UsesJava;
-import brooklyn.entity.java.UsesJavaMXBeans;
-import brooklyn.entity.java.UsesJmx;
-
+import org.apache.brooklyn.entity.java.UsesJava;
+import org.apache.brooklyn.entity.java.UsesJavaMXBeans;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.location.basic.PortRanges;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerDriver.java
index 72e1049..866aedb 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerDriver.java
@@ -18,8 +18,8 @@
  */
 package org.apache.brooklyn.entity.nosql.solr;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
-import brooklyn.entity.java.JavaSoftwareProcessDriver;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 
 public interface SolrServerDriver extends JavaSoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerImpl.java
index 4454908..128bd4b 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerImpl.java
@@ -18,9 +18,8 @@
  */
 package org.apache.brooklyn.entity.nosql.solr;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
 import org.apache.brooklyn.sensor.feed.http.HttpFeed;
 import org.apache.brooklyn.sensor.feed.http.HttpPollConfig;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerSshDriver.java
index d76259d..3c41f95 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerSshDriver.java
@@ -24,13 +24,12 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
-import brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-import brooklyn.entity.java.UsesJmx;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.file.ArchiveUtils;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterTest.java
index 285f398..4a3676d 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterTest.java
@@ -30,6 +30,8 @@ import org.apache.brooklyn.api.location.LocationSpec;
 import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.EntityInternal;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcessSshDriver;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.apache.brooklyn.util.core.ResourceUtils;
 import org.apache.brooklyn.util.core.text.TemplateProcessor;
@@ -40,10 +42,6 @@ import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.EmptySoftwareProcess;
-import brooklyn.entity.basic.EmptySoftwareProcessSshDriver;
-
 import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraFabricTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraFabricTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraFabricTest.java
index e906ae9..24ff8ba 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraFabricTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraFabricTest.java
@@ -35,6 +35,7 @@ import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.EntityInternal;
 import org.apache.brooklyn.entity.lifecycle.Lifecycle;
 import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.apache.brooklyn.util.time.Duration;
@@ -42,9 +43,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.EmptySoftwareProcess;
-
 import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Predicate;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeEc2LiveTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeEc2LiveTest.java
index d416379..3899c3b 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeEc2LiveTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeEc2LiveTest.java
@@ -20,13 +20,12 @@ package org.apache.brooklyn.entity.nosql.cassandra;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.nosql.cassandra.AstyanaxSupport.AstyanaxSample;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.collect.ImmutableList;
 
 public class CassandraNodeEc2LiveTest extends AbstractEc2LiveTest {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewayEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewayEc2LiveTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewayEc2LiveTest.java
index 7dc1fd9..651c8ef 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewayEc2LiveTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewayEc2LiveTest.java
@@ -23,13 +23,12 @@ import java.util.Map;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.group.DynamicCluster;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeEc2LiveTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeEc2LiveTest.java
index a9e5371..13a3e60 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeEc2LiveTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeEc2LiveTest.java
@@ -20,13 +20,12 @@ package org.apache.brooklyn.entity.nosql.couchdb;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.collect.ImmutableList;
 
 public class CouchDBNodeEc2LiveTest extends AbstractEc2LiveTest {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBEc2LiveTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBEc2LiveTest.java
index e943323..6306b4e 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBEc2LiveTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBEc2LiveTest.java
@@ -18,8 +18,6 @@
  */
 package org.apache.brooklyn.entity.nosql.mongodb;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.collect.ImmutableList;
 import com.mongodb.DBObject;
 
@@ -31,6 +29,7 @@ import static org.testng.Assert.assertEquals;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.test.EntityTestUtils;
 
 public class MongoDBEc2LiveTest extends AbstractEc2LiveTest {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBReplicaSetEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBReplicaSetEc2LiveTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBReplicaSetEc2LiveTest.java
index eb9b8c3..7095c82 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBReplicaSetEc2LiveTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBReplicaSetEc2LiveTest.java
@@ -18,8 +18,6 @@
  */
 package org.apache.brooklyn.entity.nosql.mongodb;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.mongodb.DBObject;
@@ -28,6 +26,7 @@ import groovy.time.TimeDuration;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.group.DynamicCluster;
 import org.apache.brooklyn.test.Asserts;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBRestartIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBRestartIntegrationTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBRestartIntegrationTest.java
index 6cde664..17f5c6b 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBRestartIntegrationTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBRestartIntegrationTest.java
@@ -20,13 +20,12 @@ package org.apache.brooklyn.entity.nosql.mongodb;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.entity.nosql.mongodb.MongoDBServer;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessRestartIntegrationTest;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.basic.AbstractSoftwareProcessRestartIntegrationTest;
-import brooklyn.entity.basic.SoftwareProcess;
-
 /**
  * Tests restart of the software *process* (as opposed to the VM).
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBSoftLayerLiveTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBSoftLayerLiveTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBSoftLayerLiveTest.java
index 9ed7400..be6c33b 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBSoftLayerLiveTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBSoftLayerLiveTest.java
@@ -22,6 +22,7 @@ import static org.testng.Assert.assertEquals;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractSoftlayerLiveTest;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -30,8 +31,6 @@ import org.testng.annotations.Test;
 import com.google.common.collect.ImmutableList;
 import com.mongodb.DBObject;
 
-import brooklyn.entity.AbstractSoftlayerLiveTest;
-
 public class MongoDBSoftLayerLiveTest extends AbstractSoftlayerLiveTest {
 
     @SuppressWarnings("unused")

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBShardedDeploymentEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBShardedDeploymentEc2LiveTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBShardedDeploymentEc2LiveTest.java
index b567edd..90fc928 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBShardedDeploymentEc2LiveTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBShardedDeploymentEc2LiveTest.java
@@ -23,6 +23,7 @@ import groovy.time.TimeDuration;
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.nosql.mongodb.MongoDBReplicaSet;
 import org.apache.brooklyn.entity.nosql.mongodb.MongoDBServer;
@@ -30,8 +31,6 @@ import org.apache.brooklyn.test.Asserts;
 import org.testng.Assert;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/redis/RedisEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/redis/RedisEc2LiveTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/redis/RedisEc2LiveTest.java
index 774b6de..2db5287 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/redis/RedisEc2LiveTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/redis/RedisEc2LiveTest.java
@@ -22,13 +22,12 @@ import javax.annotation.Nullable;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakClusterEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakClusterEc2LiveTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakClusterEc2LiveTest.java
index 5e61a1a..aca9019 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakClusterEc2LiveTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakClusterEc2LiveTest.java
@@ -20,14 +20,13 @@ package org.apache.brooklyn.entity.nosql.riak;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Iterables;



[66/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterToObjectStore.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterToObjectStore.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterToObjectStore.java
new file mode 100644
index 0000000..10f349a
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/BrooklynMementoPersisterToObjectStore.java
@@ -0,0 +1,697 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.io.IOException;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.api.catalog.CatalogItem;
+import org.apache.brooklyn.api.mgmt.rebind.PersistenceExceptionHandler;
+import org.apache.brooklyn.api.mgmt.rebind.RebindExceptionHandler;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMemento;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoManifest;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoPersister;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.CatalogItemMemento;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.Memento;
+import org.apache.brooklyn.api.objs.BrooklynObject;
+import org.apache.brooklyn.api.objs.BrooklynObjectType;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.config.StringConfigMap;
+import org.apache.brooklyn.core.catalog.internal.CatalogUtils;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.mgmt.classloading.ClassLoaderFromBrooklynClassLoadingContext;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore.StoreObjectAccessor;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore.StoreObjectAccessorWithLock;
+import org.apache.brooklyn.core.mgmt.rebind.PeriodicDeltaChangeListener;
+import org.apache.brooklyn.core.mgmt.rebind.PersisterDeltaImpl;
+import org.apache.brooklyn.core.mgmt.rebind.dto.BrooklynMementoImpl;
+import org.apache.brooklyn.core.mgmt.rebind.dto.BrooklynMementoManifestImpl;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.xstream.XmlUtil;
+import org.apache.brooklyn.util.exceptions.CompoundRuntimeException;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+
+import com.google.common.annotations.Beta;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Objects;
+import com.google.common.base.Stopwatch;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+
+/** Implementation of the {@link BrooklynMementoPersister} backed by a pluggable
+ * {@link PersistenceObjectStore} such as a file system or a jclouds object store */
+public class BrooklynMementoPersisterToObjectStore implements BrooklynMementoPersister {
+
+    // TODO Crazy amount of duplication between handling entity, location, policy, enricher + feed;
+    // Need to remove that duplication.
+
+    // TODO Should stop() take a timeout, and shutdown the executor gracefully?
+    
+    private static final Logger LOG = LoggerFactory.getLogger(BrooklynMementoPersisterToObjectStore.class);
+
+    public static final ConfigKey<Integer> PERSISTER_MAX_THREAD_POOL_SIZE = ConfigKeys.newIntegerConfigKey(
+            "persister.threadpool.maxSize",
+            "Maximum number of concurrent operations for persistence (reads/writes/deletes of *different* objects)", 
+            10);
+
+    public static final ConfigKey<Integer> PERSISTER_MAX_SERIALIZATION_ATTEMPTS = ConfigKeys.newIntegerConfigKey(
+            "persister.maxSerializationAttempts",
+            "Maximum number of attempts to serialize a memento (e.g. if first attempts fail because of concurrent modifications of an entity)", 
+            5);
+
+    private final PersistenceObjectStore objectStore;
+    private final MementoSerializer<Object> serializerWithStandardClassLoader;
+
+    private final Map<String, StoreObjectAccessorWithLock> writers = new LinkedHashMap<String, PersistenceObjectStore.StoreObjectAccessorWithLock>();
+
+    private final ListeningExecutorService executor;
+
+    private volatile boolean writesAllowed = false;
+    private volatile boolean writesShuttingDown = false;
+    private StringConfigMap brooklynProperties;
+    
+    private List<Delta> queuedDeltas = new CopyOnWriteArrayList<BrooklynMementoPersister.Delta>();
+    
+    /**
+     * Lock used on writes (checkpoint + delta) so that {@link #waitForWritesCompleted(Duration)} can block
+     * for any concurrent call to complete.
+     */
+    private final ReadWriteLock lock = new ReentrantReadWriteLock(true);
+
+    public BrooklynMementoPersisterToObjectStore(PersistenceObjectStore objectStore, StringConfigMap brooklynProperties, ClassLoader classLoader) {
+        this.objectStore = checkNotNull(objectStore, "objectStore");
+        this.brooklynProperties = brooklynProperties;
+        
+        int maxSerializationAttempts = brooklynProperties.getConfig(PERSISTER_MAX_SERIALIZATION_ATTEMPTS);
+        MementoSerializer<Object> rawSerializer = new XmlMementoSerializer<Object>(classLoader);
+        this.serializerWithStandardClassLoader = new RetryingMementoSerializer<Object>(rawSerializer, maxSerializationAttempts);
+
+        int maxThreadPoolSize = brooklynProperties.getConfig(PERSISTER_MAX_THREAD_POOL_SIZE);
+
+        objectStore.createSubPath("entities");
+        objectStore.createSubPath("locations");
+        objectStore.createSubPath("policies");
+        objectStore.createSubPath("enrichers");
+        objectStore.createSubPath("feeds");
+        objectStore.createSubPath("catalog");
+
+        // FIXME does it belong here or to ManagementPlaneSyncRecordPersisterToObjectStore ?
+        objectStore.createSubPath("plane");
+        
+        executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(maxThreadPoolSize, new ThreadFactory() {
+            @Override public Thread newThread(Runnable r) {
+                // Note: Thread name referenced in logback-includes' ThreadNameDiscriminator
+                return new Thread(r, "brooklyn-persister");
+            }}));
+    }
+
+    public MementoSerializer<Object> getMementoSerializer() {
+        return getSerializerWithStandardClassLoader();
+    }
+    
+    protected MementoSerializer<Object> getSerializerWithStandardClassLoader() {
+        return serializerWithStandardClassLoader;
+    }
+    
+    protected MementoSerializer<Object> getSerializerWithCustomClassLoader(LookupContext lookupContext, BrooklynObjectType type, String objectId) {
+        ClassLoader cl = getCustomClassLoaderForBrooklynObject(lookupContext, type, objectId);
+        if (cl==null) return serializerWithStandardClassLoader;
+        return getSerializerWithCustomClassLoader(lookupContext, cl);
+    }
+    
+    protected MementoSerializer<Object> getSerializerWithCustomClassLoader(LookupContext lookupContext, ClassLoader classLoader) {
+        int maxSerializationAttempts = brooklynProperties.getConfig(PERSISTER_MAX_SERIALIZATION_ATTEMPTS);
+        MementoSerializer<Object> rawSerializer = new XmlMementoSerializer<Object>(classLoader);
+        MementoSerializer<Object> result = new RetryingMementoSerializer<Object>(rawSerializer, maxSerializationAttempts);
+        result.setLookupContext(lookupContext);
+        return result;
+    }
+    
+    @Nullable protected ClassLoader getCustomClassLoaderForBrooklynObject(LookupContext lookupContext, BrooklynObjectType type, String objectId) {
+        BrooklynObject item = lookupContext.peek(type, objectId);
+        String catalogItemId = (item == null) ? null : item.getCatalogItemId();
+        // TODO enrichers etc aren't yet known -- would need to backtrack to the entity to get them from bundles
+        if (catalogItemId == null) {
+            return null;
+        }
+        // See RebindIteration.BrooklynObjectInstantiator.load(), for handling where catalog item is missing;
+        // similar logic here.
+        CatalogItem<?, ?> catalogItem = CatalogUtils.getCatalogItemOptionalVersion(lookupContext.lookupManagementContext(), catalogItemId);
+        if (catalogItem == null) {
+            // TODO do we need to only log once, rather than risk log.warn too often? I think this only happens on rebind, so ok.
+            LOG.warn("Unable to load catalog item "+catalogItemId+" for custom class loader of "+type+" "+objectId+"; will use default class loader");
+            return null;
+        } else {
+            return ClassLoaderFromBrooklynClassLoadingContext.of(CatalogUtils.newClassLoadingContext(lookupContext.lookupManagementContext(), catalogItem));
+        }
+    }
+    
+    @Override public void enableWriteAccess() {
+        writesAllowed = true;
+    }
+    
+    @Override
+    public void disableWriteAccess(boolean graceful) {
+        writesShuttingDown = true;
+        try {
+            writesAllowed = false;
+            // a very long timeout to ensure we don't lose state. 
+            // If persisting thousands of entities over slow network to Object Store, could take minutes.
+            waitForWritesCompleted(Duration.ONE_HOUR);
+            
+        } catch (Exception e) {
+            throw Exceptions.propagate(e);
+        } finally {
+            writesShuttingDown = false;
+        }
+    }
+    
+    @Override 
+    public void stop(boolean graceful) {
+        disableWriteAccess(graceful);
+        
+        if (executor != null) {
+            if (graceful) {
+                executor.shutdown();
+                try {
+                    // should be quick because we've just turned off writes, waiting for their completion
+                    executor.awaitTermination(1, TimeUnit.MINUTES);
+                } catch (InterruptedException e) {
+                    throw Exceptions.propagate(e);
+                }
+            } else {
+                executor.shutdownNow();
+            }
+        }
+    }
+
+    public PersistenceObjectStore getObjectStore() {
+        return objectStore;
+    }
+
+    protected StoreObjectAccessorWithLock getWriter(String path) {
+        String id = path.substring(path.lastIndexOf('/')+1);
+        synchronized (writers) {
+            StoreObjectAccessorWithLock writer = writers.get(id);
+            if (writer == null) {
+                writer = new StoreObjectAccessorLocking( objectStore.newAccessor(path) );
+                writers.put(id, writer);
+            }
+            return writer;
+        }
+    }
+
+    private Map<String,String> makeIdSubPathMap(Iterable<String> subPathLists) {
+        Map<String,String> result = MutableMap.of();
+        for (String subpath: subPathLists) {
+            String id = subpath;
+            id = id.substring(id.lastIndexOf('/')+1);
+            id = id.substring(id.lastIndexOf('\\')+1);
+            // assumes id is the filename; should work even if not, as id is later read from xpath
+            // but you'll get warnings (and possibility of loss if there is a collision)
+            result.put(id, subpath);
+        }
+        return result;
+    }
+    
+    protected BrooklynMementoRawData listMementoSubPathsAsData(final RebindExceptionHandler exceptionHandler) {
+        final BrooklynMementoRawData.Builder subPathDataBuilder = BrooklynMementoRawData.builder();
+
+        Stopwatch stopwatch = Stopwatch.createStarted();
+        try {
+            for (BrooklynObjectType type: BrooklynPersistenceUtils.STANDARD_BROOKLYN_OBJECT_TYPE_PERSISTENCE_ORDER)
+                subPathDataBuilder.putAll(type, makeIdSubPathMap(objectStore.listContentsWithSubPath(type.getSubPathName())));
+            
+        } catch (Exception e) {
+            Exceptions.propagateIfFatal(e);
+            exceptionHandler.onLoadMementoFailed(BrooklynObjectType.UNKNOWN, "Failed to list files", e);
+            throw new IllegalStateException("Failed to list memento files in "+objectStore, e);
+        }
+
+        BrooklynMementoRawData subPathData = subPathDataBuilder.build();
+        LOG.debug("Loaded rebind lists; took {}: {} entities, {} locations, {} policies, {} enrichers, {} feeds, {} catalog items; from {}", new Object[]{
+            Time.makeTimeStringRounded(stopwatch),
+            subPathData.getEntities().size(), subPathData.getLocations().size(), subPathData.getPolicies().size(), subPathData.getEnrichers().size(), 
+            subPathData.getFeeds().size(), subPathData.getCatalogItems().size(),
+            objectStore.getSummaryName() });
+        
+        return subPathData;
+    }
+    
+    public BrooklynMementoRawData loadMementoRawData(final RebindExceptionHandler exceptionHandler) {
+        BrooklynMementoRawData subPathData = listMementoSubPathsAsData(exceptionHandler);
+        
+        final BrooklynMementoRawData.Builder builder = BrooklynMementoRawData.builder();
+        
+        Visitor loaderVisitor = new Visitor() {
+            @Override
+            public void visit(BrooklynObjectType type, String id, String contentsSubpath) throws Exception {
+                String contents = null;
+                try {
+                    contents = read(contentsSubpath);
+                } catch (Exception e) {
+                    Exceptions.propagateIfFatal(e);
+                    exceptionHandler.onLoadMementoFailed(type, "memento "+id+" read error", e);
+                }
+                
+                String xmlId = (String) XmlUtil.xpath(contents, "/"+type.toCamelCase()+"/id");
+                String safeXmlId = Strings.makeValidFilename(xmlId);
+                if (!Objects.equal(id, safeXmlId))
+                    LOG.warn("ID mismatch on "+type.toCamelCase()+", "+id+" from path, "+safeXmlId+" from xml");
+                
+                builder.put(type, xmlId, contents);
+            }
+        };
+
+        Stopwatch stopwatch = Stopwatch.createStarted();
+
+        visitMemento("loading raw", subPathData, loaderVisitor, exceptionHandler);
+        
+        BrooklynMementoRawData result = builder.build();
+
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Loaded rebind raw data; took {}; {} entities, {} locations, {} policies, {} enrichers, {} feeds, {} catalog items, from {}", new Object[]{
+                     Time.makeTimeStringRounded(stopwatch.elapsed(TimeUnit.MILLISECONDS)), result.getEntities().size(), 
+                     result.getLocations().size(), result.getPolicies().size(), result.getEnrichers().size(),
+                     result.getFeeds().size(), result.getCatalogItems().size(),
+                     objectStore.getSummaryName() });
+        }
+
+        return result;
+    }
+
+    @Override
+    public BrooklynMementoManifest loadMementoManifest(BrooklynMementoRawData mementoData, final RebindExceptionHandler exceptionHandler) throws IOException {
+        if (mementoData==null)
+            mementoData = loadMementoRawData(exceptionHandler);
+        
+        final BrooklynMementoManifestImpl.Builder builder = BrooklynMementoManifestImpl.builder();
+
+        Visitor visitor = new Visitor() {
+            @Override
+            public void visit(BrooklynObjectType type, String objectId, final String contents) throws Exception {
+                final String prefix = "/"+type.toCamelCase()+"/";
+
+                class XPathHelper {
+                    private String get(String innerPath) {
+                        return (String) XmlUtil.xpath(contents, prefix+innerPath);
+                    }
+                }
+                XPathHelper x = new XPathHelper();
+                
+                switch (type) {
+                    case ENTITY:
+                        builder.entity(x.get("id"), x.get("type"), 
+                            Strings.emptyToNull(x.get("parent")), Strings.emptyToNull(x.get("catalogItemId")));
+                        break;
+                    case LOCATION:
+                    case POLICY:
+                    case ENRICHER:
+                    case FEED:
+                        builder.putType(type, x.get("id"), x.get("type"));
+                        break;
+                    case CATALOG_ITEM:
+                        try {
+                            CatalogItemMemento memento = (CatalogItemMemento) getSerializerWithStandardClassLoader().fromString(contents);
+                            if (memento == null) {
+                                LOG.warn("No "+type.toCamelCase()+"-memento deserialized from " + objectId + "; ignoring and continuing");
+                            } else {
+                                builder.catalogItem(memento);
+                            }
+                        } catch (Exception e) {
+                            exceptionHandler.onLoadMementoFailed(type, "memento "+objectId+" early catalog deserialization error", e);
+                        }
+                        break;
+                    default:
+                        throw new IllegalStateException("Unexpected brooklyn type: "+type);
+                }
+            }
+        };
+
+        Stopwatch stopwatch = Stopwatch.createStarted();
+
+        visitMemento("manifests", mementoData, visitor, exceptionHandler);
+        
+        BrooklynMementoManifest result = builder.build();
+
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Loaded rebind manifests; took {}: {} entities, {} locations, {} policies, {} enrichers, {} feeds, {} catalog items; from {}", new Object[]{
+                     Time.makeTimeStringRounded(stopwatch), 
+                     result.getEntityIdToManifest().size(), result.getLocationIdToType().size(), 
+                     result.getPolicyIdToType().size(), result.getEnricherIdToType().size(), result.getFeedIdToType().size(), 
+                     result.getCatalogItemMementos().size(),
+                     objectStore.getSummaryName() });
+        }
+
+        return result;
+    }
+    
+    @Override
+    public BrooklynMemento loadMemento(BrooklynMementoRawData mementoData, final LookupContext lookupContext, final RebindExceptionHandler exceptionHandler) throws IOException {
+        if (mementoData==null)
+            mementoData = loadMementoRawData(exceptionHandler);
+
+        Stopwatch stopwatch = Stopwatch.createStarted();
+
+        final BrooklynMementoImpl.Builder builder = BrooklynMementoImpl.builder();
+        
+        Visitor visitor = new Visitor() {
+            @Override
+            public void visit(BrooklynObjectType type, String objectId, String contents) throws Exception {
+                try {
+                    Memento memento = (Memento) getSerializerWithCustomClassLoader(lookupContext, type, objectId).fromString(contents);
+                    if (memento == null) {
+                        LOG.warn("No "+type.toCamelCase()+"-memento deserialized from " + objectId + "; ignoring and continuing");
+                    } else {
+                        builder.memento(memento);
+                    }
+                } catch (Exception e) {
+                    exceptionHandler.onLoadMementoFailed(type, "memento "+objectId+" deserialization error", e);
+                }
+            }
+
+        };
+
+        // TODO not convinced this is single threaded on reads; maybe should get a new one each time?
+        getSerializerWithStandardClassLoader().setLookupContext(lookupContext);
+        try {
+            visitMemento("deserialization", mementoData, visitor, exceptionHandler);
+        } finally {
+            getSerializerWithStandardClassLoader().unsetLookupContext();
+        }
+
+        BrooklynMemento result = builder.build();
+        
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Loaded rebind mementos; took {}: {} entities, {} locations, {} policies, {} enrichers, {} feeds, {} catalog items, from {}", new Object[]{
+                      Time.makeTimeStringRounded(stopwatch.elapsed(TimeUnit.MILLISECONDS)), result.getEntityIds().size(), 
+                      result.getLocationIds().size(), result.getPolicyIds().size(), result.getEnricherIds().size(), 
+                      result.getFeedIds().size(), result.getCatalogItemIds().size(),
+                      objectStore.getSummaryName() });
+        }
+        
+        return result;
+    }
+    
+    protected interface Visitor {
+        public void visit(BrooklynObjectType type, String id, String contents) throws Exception;
+    }
+    
+    protected void visitMemento(final String phase, final BrooklynMementoRawData rawData, final Visitor visitor, final RebindExceptionHandler exceptionHandler) {
+        List<ListenableFuture<?>> futures = Lists.newArrayList();
+        
+        class VisitorWrapper implements Runnable {
+            private final BrooklynObjectType type;
+            private final Map.Entry<String,String> objectIdAndData;
+            public VisitorWrapper(BrooklynObjectType type, Map.Entry<String,String> objectIdAndData) {
+                this.type = type;
+                this.objectIdAndData = objectIdAndData;
+            }
+            public void run() {
+                try {
+                    visitor.visit(type, objectIdAndData.getKey(), objectIdAndData.getValue());
+                } catch (Exception e) {
+                    Exceptions.propagateIfFatal(e);
+                    exceptionHandler.onLoadMementoFailed(type, "memento "+objectIdAndData.getKey()+" "+phase+" error", e);
+                }
+            }
+        }
+        
+        for (BrooklynObjectType type: BrooklynPersistenceUtils.STANDARD_BROOKLYN_OBJECT_TYPE_PERSISTENCE_ORDER) {
+            for (final Map.Entry<String,String> entry : rawData.getObjectsOfType(type).entrySet()) {
+                futures.add(executor.submit(new VisitorWrapper(type, entry)));
+            }
+        }
+
+        try {
+            // Wait for all, failing fast if any exceptions.
+            Futures.allAsList(futures).get();
+        } catch (Exception e) {
+            Exceptions.propagateIfFatal(e);
+            
+            List<Exception> exceptions = Lists.newArrayList();
+            
+            for (ListenableFuture<?> future : futures) {
+                if (future.isDone()) {
+                    try {
+                        future.get();
+                    } catch (InterruptedException e2) {
+                        throw Exceptions.propagate(e2);
+                    } catch (ExecutionException e2) {
+                        LOG.warn("Problem loading memento ("+phase+"): "+e2, e2);
+                        exceptions.add(e2);
+                    }
+                    future.cancel(true);
+                }
+            }
+            if (exceptions.isEmpty()) {
+                throw Exceptions.propagate(e);
+            } else {
+                // Normally there should be at lesat one failure; otherwise all.get() would not have failed.
+                throw new CompoundRuntimeException("Problem loading mementos ("+phase+")", exceptions);
+            }
+        }
+    }
+
+    protected void checkWritesAllowed() {
+        if (!writesAllowed && !writesShuttingDown) {
+            throw new IllegalStateException("Writes not allowed in "+this);
+        }
+    }
+    
+    /** See {@link BrooklynPersistenceUtils} for conveniences for using this method. */
+    @Override
+    @Beta
+    public void checkpoint(BrooklynMementoRawData newMemento, PersistenceExceptionHandler exceptionHandler) {
+        checkWritesAllowed();
+        try {
+            lock.writeLock().lockInterruptibly();
+        } catch (InterruptedException e) {
+            throw Exceptions.propagate(e);
+        }
+        
+        try {
+            objectStore.prepareForMasterUse();
+            
+            Stopwatch stopwatch = Stopwatch.createStarted();
+            List<ListenableFuture<?>> futures = Lists.newArrayList();
+            
+            for (BrooklynObjectType type: BrooklynPersistenceUtils.STANDARD_BROOKLYN_OBJECT_TYPE_PERSISTENCE_ORDER) {
+                for (Map.Entry<String, String> entry : newMemento.getObjectsOfType(type).entrySet()) {
+                    futures.add(asyncPersist(type.getSubPathName(), type, entry.getKey(), entry.getValue(), exceptionHandler));
+                }
+            }
+            
+            try {
+                // Wait for all the tasks to complete or fail, rather than aborting on the first failure.
+                // But then propagate failure if any fail. (hence the two calls).
+                Futures.successfulAsList(futures).get();
+                Futures.allAsList(futures).get();
+            } catch (Exception e) {
+                throw Exceptions.propagate(e);
+            }
+            if (LOG.isDebugEnabled()) LOG.debug("Checkpointed entire memento in {}", Time.makeTimeStringRounded(stopwatch));
+        } finally {
+            lock.writeLock().unlock();
+        }
+    }
+
+    @Override
+    public void delta(Delta delta, PersistenceExceptionHandler exceptionHandler) {
+        checkWritesAllowed();
+
+        while (!queuedDeltas.isEmpty()) {
+            Delta extraDelta = queuedDeltas.remove(0);
+            doDelta(extraDelta, exceptionHandler, true);
+        }
+
+        doDelta(delta, exceptionHandler, false);
+    }
+    
+    protected void doDelta(Delta delta, PersistenceExceptionHandler exceptionHandler, boolean previouslyQueued) {
+        Stopwatch stopwatch = deltaImpl(delta, exceptionHandler);
+        
+        if (LOG.isDebugEnabled()) LOG.debug("Checkpointed "+(previouslyQueued ? "previously queued " : "")+"delta of memento in {}: "
+                + "updated {} entities, {} locations, {} policies, {} enrichers, {} catalog items; "
+                + "removed {} entities, {} locations, {} policies, {} enrichers, {} catalog items",
+                    new Object[] {Time.makeTimeStringRounded(stopwatch),
+                        delta.entities().size(), delta.locations().size(), delta.policies().size(), delta.enrichers().size(), delta.catalogItems().size(),
+                        delta.removedEntityIds().size(), delta.removedLocationIds().size(), delta.removedPolicyIds().size(), delta.removedEnricherIds().size(), delta.removedCatalogItemIds().size()});
+    }
+    
+    @Override
+    public void queueDelta(Delta delta) {
+        queuedDeltas.add(delta);
+    }
+    
+    /**
+     * Concurrent calls will queue-up (the lock is "fair", which means an "approximately arrival-order policy").
+     * Current usage is with the {@link PeriodicDeltaChangeListener} so we expect only one call at a time.
+     * 
+     * TODO Longer term, if we care more about concurrent calls we could merge the queued deltas so that we
+     * don't do unnecessary repeated writes of an entity.
+     */
+    private Stopwatch deltaImpl(Delta delta, PersistenceExceptionHandler exceptionHandler) {
+        try {
+            lock.writeLock().lockInterruptibly();
+        } catch (InterruptedException e) {
+            throw Exceptions.propagate(e);
+        }
+        try {
+            objectStore.prepareForMasterUse();
+            
+            Stopwatch stopwatch = Stopwatch.createStarted();
+            List<ListenableFuture<?>> futures = Lists.newArrayList();
+            
+            for (BrooklynObjectType type: BrooklynPersistenceUtils.STANDARD_BROOKLYN_OBJECT_TYPE_PERSISTENCE_ORDER) {
+                for (Memento entity : delta.getObjectsOfType(type)) {
+                    futures.add(asyncPersist(type.getSubPathName(), entity, exceptionHandler));
+                }
+            }
+            for (BrooklynObjectType type: BrooklynPersistenceUtils.STANDARD_BROOKLYN_OBJECT_TYPE_PERSISTENCE_ORDER) {
+                for (String id : delta.getRemovedIdsOfType(type)) {
+                    futures.add(asyncDelete(type.getSubPathName(), id, exceptionHandler));
+                }
+            }
+            
+            try {
+                // Wait for all the tasks to complete or fail, rather than aborting on the first failure.
+                // But then propagate failure if any fail. (hence the two calls).
+                Futures.successfulAsList(futures).get();
+                Futures.allAsList(futures).get();
+            } catch (Exception e) {
+                throw Exceptions.propagate(e);
+            }
+            
+            return stopwatch;
+        } finally {
+            lock.writeLock().unlock();
+        }
+    }
+
+    @Override
+    public void waitForWritesCompleted(Duration timeout) throws InterruptedException, TimeoutException {
+        boolean locked = lock.readLock().tryLock(timeout.toMillisecondsRoundingUp(), TimeUnit.MILLISECONDS);
+        if (locked) {
+            ImmutableSet<StoreObjectAccessorWithLock> wc;
+            synchronized (writers) {
+                wc = ImmutableSet.copyOf(writers.values());
+            }
+            lock.readLock().unlock();
+            
+            // Belt-and-braces: the lock above should be enough to ensure no outstanding writes, because
+            // each writer is now synchronous.
+            for (StoreObjectAccessorWithLock writer : wc) {
+                writer.waitForCurrentWrites(timeout);
+            }
+        } else {
+            throw new TimeoutException("Timeout waiting for writes to "+objectStore);
+        }
+    }
+
+    private String read(String subPath) {
+        StoreObjectAccessor objectAccessor = objectStore.newAccessor(subPath);
+        return objectAccessor.get();
+    }
+
+    private void persist(String subPath, Memento memento, PersistenceExceptionHandler exceptionHandler) {
+        try {
+            getWriter(getPath(subPath, memento.getId())).put(getSerializerWithStandardClassLoader().toString(memento));
+        } catch (Exception e) {
+            exceptionHandler.onPersistMementoFailed(memento, e);
+        }
+    }
+    
+    private void persist(String subPath, BrooklynObjectType type, String id, String content, PersistenceExceptionHandler exceptionHandler) {
+        try {
+            if (content==null) {
+                LOG.warn("Null content for "+type+" "+id);
+            }
+            getWriter(getPath(subPath, id)).put(content);
+        } catch (Exception e) {
+            exceptionHandler.onPersistRawMementoFailed(type, id, e);
+        }
+    }
+    
+    private void delete(String subPath, String id, PersistenceExceptionHandler exceptionHandler) {
+        try {
+            StoreObjectAccessorWithLock w = getWriter(getPath(subPath, id));
+            w.delete();
+            synchronized (writers) {
+                writers.remove(id);
+            }
+        } catch (Exception e) {
+            exceptionHandler.onDeleteMementoFailed(id, e);
+        }
+    }
+
+    private ListenableFuture<?> asyncPersist(final String subPath, final Memento memento, final PersistenceExceptionHandler exceptionHandler) {
+        return executor.submit(new Runnable() {
+            public void run() {
+                persist(subPath, memento, exceptionHandler);
+            }});
+    }
+
+    private ListenableFuture<?> asyncPersist(final String subPath, final BrooklynObjectType type, final String id, final String content, final PersistenceExceptionHandler exceptionHandler) {
+        return executor.submit(new Runnable() {
+            public void run() {
+                persist(subPath, type, id, content, exceptionHandler);
+            }});
+    }
+
+    private ListenableFuture<?> asyncDelete(final String subPath, final String id, final PersistenceExceptionHandler exceptionHandler) {
+        return executor.submit(new Runnable() {
+            public void run() {
+                delete(subPath, id, exceptionHandler);
+            }});
+    }
+    
+    private String getPath(String subPath, String id) {
+        return subPath+"/"+Strings.makeValidFilename(id);
+    }
+
+    @Override
+    public String getBackingStoreDescription() {
+        return getObjectStore().getSummaryName();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/BrooklynPersistenceUtils.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/BrooklynPersistenceUtils.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/BrooklynPersistenceUtils.java
new file mode 100644
index 0000000..b3db32c
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/BrooklynPersistenceUtils.java
@@ -0,0 +1,269 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.api.catalog.CatalogItem;
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
+import org.apache.brooklyn.api.mgmt.ha.ManagementPlaneSyncRecord;
+import org.apache.brooklyn.api.mgmt.ha.MementoCopyMode;
+import org.apache.brooklyn.api.mgmt.rebind.PersistenceExceptionHandler;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.Memento;
+import org.apache.brooklyn.api.objs.BrooklynObject;
+import org.apache.brooklyn.api.objs.BrooklynObjectType;
+import org.apache.brooklyn.api.policy.Policy;
+import org.apache.brooklyn.api.sensor.Enricher;
+import org.apache.brooklyn.api.sensor.Feed;
+import org.apache.brooklyn.core.mgmt.ha.ManagementPlaneSyncRecordPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.internal.LocalLocationManager;
+import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.mgmt.rebind.PersistenceExceptionHandlerImpl;
+import org.apache.brooklyn.core.mgmt.rebind.transformer.CompoundTransformer;
+import org.apache.brooklyn.core.mgmt.rebind.transformer.CompoundTransformerLoader;
+import org.apache.brooklyn.core.objs.BrooklynObjectInternal;
+import org.apache.brooklyn.core.server.BrooklynServerConfig;
+import org.apache.brooklyn.core.server.BrooklynServerPaths;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.util.core.ResourceUtils;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Stopwatch;
+import com.google.common.collect.ImmutableList;
+
+public class BrooklynPersistenceUtils {
+
+    private static final Logger log = LoggerFactory.getLogger(BrooklynPersistenceUtils.class);
+    
+    @Beta
+    public static final List<BrooklynObjectType> STANDARD_BROOKLYN_OBJECT_TYPE_PERSISTENCE_ORDER = ImmutableList.of( 
+        BrooklynObjectType.ENTITY, BrooklynObjectType.LOCATION, BrooklynObjectType.POLICY,
+        BrooklynObjectType.ENRICHER, BrooklynObjectType.FEED, BrooklynObjectType.CATALOG_ITEM);
+
+    /** Creates a {@link PersistenceObjectStore} for general-purpose use. */
+    public static PersistenceObjectStore newPersistenceObjectStore(ManagementContext managementContext,
+            String locationSpec, String locationContainer) {
+        
+        return newPersistenceObjectStore(managementContext, locationSpec, locationContainer,
+            PersistMode.AUTO, HighAvailabilityMode.STANDBY);
+    }
+    
+    /** Creates a {@link PersistenceObjectStore} for use with a specified set of modes. */
+    public static PersistenceObjectStore newPersistenceObjectStore(ManagementContext managementContext,
+            String locationSpec, String locationContainer, PersistMode persistMode, HighAvailabilityMode highAvailabilityMode) {
+        PersistenceObjectStore destinationObjectStore;
+        locationContainer = BrooklynServerPaths.newMainPersistencePathResolver(managementContext).location(locationSpec).dir(locationContainer).resolve();
+
+        Location location = null;
+        if (Strings.isBlank(locationSpec)) {
+            location = managementContext.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class)
+                .configure(LocalLocationManager.CREATE_UNMANAGED, true));
+        } else {
+            location = managementContext.getLocationRegistry().resolve(locationSpec, false, null).get();
+            if (!(location instanceof LocationWithObjectStore)) {
+                throw new IllegalArgumentException("Destination location "+location+" does not offer a persistent store");
+            }
+        }
+        destinationObjectStore = ((LocationWithObjectStore)location).newPersistenceObjectStore(locationContainer);
+        
+        destinationObjectStore.injectManagementContext(managementContext);
+        destinationObjectStore.prepareForSharedUse(persistMode, highAvailabilityMode);
+        return destinationObjectStore;
+    }
+
+    public static void writeMemento(ManagementContext managementContext, BrooklynMementoRawData memento,
+            PersistenceObjectStore destinationObjectStore) {
+        BrooklynMementoPersisterToObjectStore persister = new BrooklynMementoPersisterToObjectStore(
+            destinationObjectStore,
+            ((ManagementContextInternal)managementContext).getBrooklynProperties(),
+            managementContext.getCatalogClassLoader());
+        PersistenceExceptionHandler exceptionHandler = PersistenceExceptionHandlerImpl.builder().build();
+        persister.enableWriteAccess();
+        persister.checkpoint(memento, exceptionHandler);
+    }
+
+    public static void writeManagerMemento(ManagementContext managementContext, ManagementPlaneSyncRecord optionalPlaneRecord,
+            PersistenceObjectStore destinationObjectStore) {
+        if (optionalPlaneRecord != null) {
+            ManagementPlaneSyncRecordPersisterToObjectStore managementPersister = new ManagementPlaneSyncRecordPersisterToObjectStore(
+                    managementContext, destinationObjectStore, managementContext.getCatalogClassLoader());
+            managementPersister.checkpoint(optionalPlaneRecord);
+        }
+    }
+
+    public static CompoundTransformer loadTransformer(ResourceUtils resources, String transformationsFileUrl) {
+        if (Strings.isBlank(transformationsFileUrl)) {
+            return CompoundTransformer.NOOP; 
+        } else {
+            String contents = resources.getResourceAsString(transformationsFileUrl);
+            return CompoundTransformerLoader.load(contents);
+        }
+    }
+
+    public static Memento newObjectMemento(BrooklynObject instance) {
+        return ((BrooklynObjectInternal)instance).getRebindSupport().getMemento();
+    }
+    
+    public static BrooklynMementoRawData newStateMemento(ManagementContext mgmt, MementoCopyMode source) {
+        switch (source) {
+        case LOCAL: 
+            return newStateMementoFromLocal(mgmt); 
+        case REMOTE: 
+            return mgmt.getRebindManager().retrieveMementoRawData(); 
+        case AUTO: 
+            throw new IllegalStateException("Copy mode AUTO not supported here");
+        }
+        throw new IllegalStateException("Should not come here, unknown mode "+source);
+    }
+    
+    public static ManagementPlaneSyncRecord newManagerMemento(ManagementContext mgmt, MementoCopyMode source) {
+        switch (source) {
+        case LOCAL: 
+            return mgmt.getHighAvailabilityManager().getLastManagementPlaneSyncRecord();
+        case REMOTE: 
+            return mgmt.getHighAvailabilityManager().loadManagementPlaneSyncRecord(true);
+        case AUTO: 
+            throw new IllegalStateException("Copy mode AUTO not supported here");
+        }
+        throw new IllegalStateException("Should not come here, unknown mode "+source);
+    }
+    
+
+    private static BrooklynMementoRawData newStateMementoFromLocal(ManagementContext mgmt) {
+        BrooklynMementoRawData.Builder result = BrooklynMementoRawData.builder();
+        MementoSerializer<Object> rawSerializer = new XmlMementoSerializer<Object>(mgmt.getClass().getClassLoader());
+        RetryingMementoSerializer<Object> serializer = new RetryingMementoSerializer<Object>(rawSerializer, 1);
+        
+        for (Location instance: mgmt.getLocationManager().getLocations())
+            result.location(instance.getId(), serializer.toString(newObjectMemento(instance)));
+        for (Entity instance: mgmt.getEntityManager().getEntities()) {
+            instance = Entities.deproxy(instance);
+            result.entity(instance.getId(), serializer.toString(newObjectMemento(instance)));
+            for (Feed instanceAdjunct: ((EntityInternal)instance).feeds().getFeeds())
+                result.feed(instanceAdjunct.getId(), serializer.toString(newObjectMemento(instanceAdjunct)));
+            for (Enricher instanceAdjunct: instance.getEnrichers())
+                result.enricher(instanceAdjunct.getId(), serializer.toString(newObjectMemento(instanceAdjunct)));
+            for (Policy instanceAdjunct: instance.getPolicies())
+                result.policy(instanceAdjunct.getId(), serializer.toString(newObjectMemento(instanceAdjunct)));
+        }
+        for (CatalogItem<?,?> instance: mgmt.getCatalog().getCatalogItems())
+            result.catalogItem(instance.getId(), serializer.toString(newObjectMemento(instance)));
+        
+        return result.build();
+    }
+
+    /** generates and writes mementos for the given mgmt context to the given targetStore;
+     * this may be taken from {@link MementoCopyMode#LOCAL} current state 
+     * or {@link MementoCopyMode#REMOTE} persisted state, or the default {@link MementoCopyMode#AUTO} detected
+     */
+    public static void writeMemento(ManagementContext mgmt, PersistenceObjectStore targetStore, MementoCopyMode source) {
+        if (source==null || source==MementoCopyMode.AUTO) 
+            source = (mgmt.getHighAvailabilityManager().getNodeState()==ManagementNodeState.MASTER ? MementoCopyMode.LOCAL : MementoCopyMode.REMOTE);
+
+        Stopwatch timer = Stopwatch.createStarted();
+        
+        BrooklynMementoRawData dataRecord = newStateMemento(mgmt, source); 
+        ManagementPlaneSyncRecord mgmtRecord = newManagerMemento(mgmt, source);
+
+        writeMemento(mgmt, dataRecord, targetStore);
+        writeManagerMemento(mgmt, mgmtRecord, targetStore);
+        
+        log.debug("Wrote full memento to "+targetStore+" in "+Time.makeTimeStringRounded(Duration.of(timer)));
+    }
+
+    public static enum CreateBackupMode { PROMOTION, DEMOTION, CUSTOM;
+        @Override public String toString() { return super.toString().toLowerCase(); }
+    }
+    
+    public static void createBackup(ManagementContext managementContext, CreateBackupMode mode, MementoCopyMode source) {
+        if (source==null || source==MementoCopyMode.AUTO) {
+            switch (mode) {
+            case PROMOTION: source = MementoCopyMode.REMOTE; break;
+            case DEMOTION: source = MementoCopyMode.LOCAL; break;
+            default:
+                throw new IllegalArgumentException("Cannot detect copy mode for "+mode+"/"+source);
+            }
+        }
+        BrooklynMementoRawData memento = null;
+        ManagementPlaneSyncRecord planeState = null;
+        
+        try {
+            log.debug("Loading persisted state on "+mode+" for backup purposes");
+            memento = newStateMemento(managementContext, source);
+            try {
+                planeState = newManagerMemento(managementContext, source);
+            } catch (Exception e) {
+                Exceptions.propagateIfFatal(e);
+                log.warn("Unable to access management plane sync state on "+mode+" (ignoring): "+e, e);
+            }
+        
+            PersistenceObjectStore destinationObjectStore = null;
+            String backupSpec = managementContext.getConfig().getConfig(BrooklynServerConfig.PERSISTENCE_BACKUPS_LOCATION_SPEC);
+            String nonBackupSpec = managementContext.getConfig().getConfig(BrooklynServerConfig.PERSISTENCE_LOCATION_SPEC);
+            try {
+                String backupContainer = BrooklynServerPaths.newBackupPersistencePathResolver(managementContext)
+                    .location(backupSpec).nonBackupLocation(nonBackupSpec).resolveWithSubpathFor(managementContext, mode.toString());
+                destinationObjectStore = BrooklynPersistenceUtils.newPersistenceObjectStore(managementContext, backupSpec, backupContainer);
+                log.debug("Backing up persisted state on "+mode+", to "+destinationObjectStore.getSummaryName());
+                BrooklynPersistenceUtils.writeMemento(managementContext, memento, destinationObjectStore);
+                BrooklynPersistenceUtils.writeManagerMemento(managementContext, planeState, destinationObjectStore);
+                if (!memento.isEmpty()) {
+                    log.info("Back-up of persisted state created on "+mode+", in "+destinationObjectStore.getSummaryName());
+                } else {
+                    log.debug("Back-up of (empty) persisted state created on "+mode+", in "+destinationObjectStore.getSummaryName());
+                }
+                
+            } catch (Exception e) {
+                Exceptions.propagateIfFatal(e);
+                PersistenceObjectStore failedStore = destinationObjectStore;
+                if (!Strings.isBlank(backupSpec) && !"localhost".equals(backupSpec)) {
+                    String failedSpec = backupSpec;
+                    backupSpec = "localhost";
+                    String backupContainer = BrooklynServerPaths.newBackupPersistencePathResolver(managementContext)
+                        .location(backupSpec).nonBackupLocation(nonBackupSpec).resolveWithSubpathFor(managementContext, mode.toString());
+                    destinationObjectStore = BrooklynPersistenceUtils.newPersistenceObjectStore(managementContext, backupSpec, backupContainer);
+                    log.warn("Persisted state back-up to "+(failedStore!=null ? failedStore.getSummaryName() : failedSpec)
+                        +" failed with "+e, e);
+                    
+                    log.debug("Backing up persisted state on "+mode+", locally because remote failed, to "+destinationObjectStore.getSummaryName());
+                    BrooklynPersistenceUtils.writeMemento(managementContext, memento, destinationObjectStore);
+                    BrooklynPersistenceUtils.writeManagerMemento(managementContext, planeState, destinationObjectStore);
+                    log.info("Back-up of persisted state created on "+mode+", locally because remote failed, in "+destinationObjectStore.getSummaryName());
+                }
+            }
+        } catch (Exception e) {
+            Exceptions.propagateIfFatal(e);
+            log.warn("Unable to backup management plane sync state on "+mode+" (ignoring): "+e, e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/CatalogItemLibrariesConverter.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/CatalogItemLibrariesConverter.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/CatalogItemLibrariesConverter.java
new file mode 100644
index 0000000..ce6731b
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/CatalogItemLibrariesConverter.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+import org.apache.brooklyn.api.catalog.CatalogItem.CatalogBundle;
+import org.apache.brooklyn.api.catalog.CatalogItem.CatalogItemLibraries;
+import org.apache.brooklyn.core.catalog.internal.CatalogBundleDto;
+
+import com.thoughtworks.xstream.converters.Converter;
+import com.thoughtworks.xstream.converters.MarshallingContext;
+import com.thoughtworks.xstream.converters.UnmarshallingContext;
+import com.thoughtworks.xstream.io.HierarchicalStreamReader;
+import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
+
+/**
+ *  Convert old-style rebind file formats to the latest version.
+ *  The code is needed only during transition to the new version, can be removed after a while.
+ */
+@Deprecated
+public class CatalogItemLibrariesConverter implements Converter {
+
+    @Override
+    public boolean canConvert(@SuppressWarnings("rawtypes") Class type) {
+        return CatalogItemLibraries.class.isAssignableFrom(type) ||
+                Collection.class.isAssignableFrom(type);
+    }
+
+    @Override
+    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
+        context.convertAnother(source);
+    }
+
+    @Override
+    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
+        Object obj = context.convertAnother(context.currentObject(), context.getRequiredType());
+        if (CatalogItemLibraries.class.isAssignableFrom(context.getRequiredType())) {
+            CatalogItemLibraries libs = (CatalogItemLibraries)obj;
+            Collection<String> bundles = libs.getBundles();
+            Collection<CatalogBundle> libraries = new ArrayList<CatalogBundle>(bundles.size());
+            for (String url : bundles) {
+                libraries.add(new CatalogBundleDto(null, null, url));
+            }
+            return libraries;
+        } else {
+            return obj;
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/FileBasedObjectStore.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/FileBasedObjectStore.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/FileBasedObjectStore.java
new file mode 100644
index 0000000..cd54053
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/FileBasedObjectStore.java
@@ -0,0 +1,425 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static java.lang.String.format;
+
+import java.io.File;
+import java.io.FileFilter;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.core.server.BrooklynServerConfig;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.internal.ssh.process.ProcessTool;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.exceptions.FatalConfigurationRuntimeException;
+import org.apache.brooklyn.util.io.FileUtil;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.os.Os.DeletionResult;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Function;
+import com.google.common.base.Objects;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableList;
+import com.google.common.io.Files;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+
+/**
+ * @author Andrea Turli
+ */
+public class FileBasedObjectStore implements PersistenceObjectStore {
+
+    private static final Logger log = LoggerFactory.getLogger(FileBasedObjectStore.class);
+
+    private static final int SHUTDOWN_TIMEOUT_MS = 10*1000;
+
+    private final File basedir;
+    private final ListeningExecutorService executor;
+    private ManagementContext mgmt;
+    private boolean prepared = false;
+    private boolean deferredBackupNeeded = false;
+    private AtomicBoolean doneFirstContentiousWrite = new AtomicBoolean(false);
+
+    /**
+     * @param basedir
+     */
+    public FileBasedObjectStore(File basedir) {
+        this.basedir = checkPersistenceDirPlausible(basedir);
+        this.executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
+        log.debug("File-based objectStore will use directory {}", basedir);
+        // don't check accessible yet, we do that when we prepare
+    }
+
+    @Override
+    public String getSummaryName() {
+        return getBaseDir().getAbsolutePath();
+    }
+    
+    public File getBaseDir() {
+        return basedir;
+    }
+    
+    public void prepareForMasterUse() {
+        if (doneFirstContentiousWrite.get())
+            return;
+        synchronized (this) {
+            if (doneFirstContentiousWrite.get())
+                return;
+            try {
+                if (deferredBackupNeeded) {
+                    // defer backup and path creation until first write
+                    // this way if node is standby or auto, the backup is not created superfluously
+
+                    File backup = backupDirByCopying(basedir);
+                    log.info("Persistence deferred backup, directory "+basedir+" backed up to "+backup.getAbsolutePath());
+
+                    deferredBackupNeeded = false;
+                }
+            } catch (Exception e) {
+                throw Exceptions.propagate(e);
+            }
+            doneFirstContentiousWrite.getAndSet(true);
+        }
+    }
+    
+    @Override
+    public void createSubPath(String subPath) {
+        if (!prepared) throw new IllegalStateException("Not yet prepared: "+this);
+        
+        File dir = new File(getBaseDir(), subPath);
+        if (dir.mkdir()) {
+            try {
+                FileUtil.setFilePermissionsTo700(dir);
+            } catch (IOException e) {
+                log.warn("Unable to set sub-directory permissions to 700 (continuing): "+dir);
+            }
+        } else {
+            if (!dir.exists())
+                throw new IllegalStateException("Cannot create "+dir+"; call returned false");
+        }
+        checkPersistenceDirAccessible(dir);
+    }
+
+    @Override
+    public StoreObjectAccessor newAccessor(String path) {
+        if (!prepared) throw new IllegalStateException("Not yet prepared: "+this);
+        
+        String tmpExt = ".tmp";
+        if (mgmt!=null && mgmt.getManagementNodeId()!=null) tmpExt = "."+mgmt.getManagementNodeId()+tmpExt;
+        return new FileBasedStoreObjectAccessor(new File(Os.mergePaths(getBaseDir().getAbsolutePath(), path)), tmpExt);
+    }
+
+    @Override
+    public List<String> listContentsWithSubPath(final String parentSubPath) {
+        if (!prepared) throw new IllegalStateException("Not yet prepared: "+this);
+        
+        Preconditions.checkNotNull(parentSubPath);
+        File subPathDir = new File(basedir, parentSubPath);
+
+        FileFilter fileFilter = new FileFilter() {
+            @Override public boolean accept(File file) {
+                // An inclusion filter would be safer than exclusion
+                return !file.getName().endsWith(".tmp") && !file.getName().endsWith(".swp");
+            }
+        };
+        File[] subPathDirFiles = subPathDir.listFiles(fileFilter);
+        if (subPathDirFiles==null) return ImmutableList.<String>of();
+        return FluentIterable.from(Arrays.asList(subPathDirFiles))
+                .transform(new Function<File, String>() {
+                    @Nullable
+                    @Override
+                    public String apply(@Nullable File input) {
+                        return format("%s/%s", parentSubPath, input.getName());
+                    }
+                }).toList();
+    }
+
+    @Override
+    public void close() {
+        executor.shutdown();
+        try {
+            executor.awaitTermination(SHUTDOWN_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+        } catch (InterruptedException e) {
+            throw Exceptions.propagate(e);
+        }
+    }
+
+    @Override
+    public String toString() {
+        return Objects.toStringHelper(this).add("basedir", basedir).toString();
+    }
+
+    @Override
+    public void injectManagementContext(ManagementContext mgmt) {
+        if (this.mgmt!=null && !this.mgmt.equals(mgmt))
+            throw new IllegalStateException("Cannot change mgmt context of "+this);
+        this.mgmt = mgmt;
+    }
+    
+    @Override
+    public void prepareForSharedUse(@Nullable PersistMode persistMode, HighAvailabilityMode haMode) {
+        if (mgmt==null) throw new NullPointerException("Must inject ManagementContext before preparing "+this);
+        
+        if (persistMode==null || persistMode==PersistMode.DISABLED) {
+            // TODO is this check needed? shouldn't come here now without persistence on.
+            prepared = true;
+            return;
+        }
+        
+        @SuppressWarnings("deprecation")
+        Boolean backups = mgmt.getConfig().getConfig(BrooklynServerConfig.PERSISTENCE_BACKUPS_REQUIRED);
+        if (Boolean.TRUE.equals(backups)) {
+            log.warn("Using legacy backup for "+this+"; functionality will be removed in future versions, in favor of promotion/demotion-specific backups to a configurable backup location.");
+        }
+        // default backups behaviour here changed to false, Nov 2014, because these backups are now legacy;
+        // we prefer the made when persistence is enabled, using routines in BrooklynPersistenceUtils
+        if (backups==null) backups = false; 
+
+        File dir = getBaseDir();
+        try {
+            String persistencePath = dir.getAbsolutePath();
+
+            switch (persistMode) {
+            case CLEAN:
+                if (dir.exists()) {
+                    checkPersistenceDirAccessible(dir);
+                    try {
+                        if (backups) {
+                            File old = backupDirByMoving(dir);
+                            log.info("Persistence mode CLEAN, directory "+persistencePath+" backed up to "+old.getAbsolutePath());
+                        } else {
+                            deleteCompletely();
+                            log.info("Persistence mode CLEAN, directory "+persistencePath+" deleted");
+                        }
+                    } catch (IOException e) {
+                        throw new FatalConfigurationRuntimeException("Error using existing persistence directory "+dir.getAbsolutePath(), e);
+                    }
+                } else {
+                    log.debug("Persistence mode CLEAN, directory "+persistencePath+", no previous state");
+                }
+                break;
+            case REBIND:
+                checkPersistenceDirAccessible(dir);
+                checkPersistenceDirNonEmpty(dir);
+                try {
+                    if (backups) {
+                        if (haMode==HighAvailabilityMode.MASTER) {
+                            File backup = backupDirByCopying(dir);
+                            log.info("Persistence mode REBIND, directory "+persistencePath+" backed up to "+backup.getAbsolutePath());                            
+                        } else {
+                            deferredBackupNeeded = true;
+                        }
+                    }
+                } catch (IOException e) {
+                    throw new FatalConfigurationRuntimeException("Error backing up persistence directory "+dir.getAbsolutePath(), e);
+                }
+                break;
+            case AUTO:
+                if (dir.exists()) {
+                    checkPersistenceDirAccessible(dir);
+                }
+                if (dir.exists() && !isMementoDirExistButEmpty(dir)) {
+                    try {
+                        if (backups) {
+                            if (haMode==HighAvailabilityMode.MASTER) {
+                                File backup = backupDirByCopying(dir);
+                                log.info("Persistence mode REBIND, directory "+persistencePath+" backed up to "+backup.getAbsolutePath());                            
+                            } else {
+                                deferredBackupNeeded = true;
+                            }
+                        }
+                    } catch (IOException e) {
+                        throw new FatalConfigurationRuntimeException("Error backing up persistence directory "+dir.getAbsolutePath(), e);
+                    }
+                } else {
+                    log.debug("Persistence mode AUTO, directory "+persistencePath+", no previous state");
+                }
+                break;
+            default:
+                throw new FatalConfigurationRuntimeException("Unexpected persist mode "+persistMode+"; modified during initialization?!");
+            };
+
+            if (!dir.exists()) {
+                boolean success = dir.mkdirs();
+                if (success) {
+                    FileUtil.setFilePermissionsTo700(dir);
+                } else {
+                    throw new FatalConfigurationRuntimeException("Failed to create persistence directory "+dir);
+                }
+            }
+
+        } catch (Exception e) {
+            throw Exceptions.propagate(e);
+        }
+        
+        prepared = true;        
+    }
+
+    protected File checkPersistenceDirPlausible(File dir) {
+        checkNotNull(dir, "directory");
+        if (!dir.exists()) return dir;
+        if (dir.isFile()) throw new FatalConfigurationRuntimeException("Invalid persistence directory" + dir + ": must not be a file");
+        if (!(dir.canRead() && dir.canWrite())) throw new FatalConfigurationRuntimeException("Invalid persistence directory" + dir + ": " +
+                (!dir.canRead() ? "not readable" :
+                        (!dir.canWrite() ? "not writable" : "unknown reason")));
+        return dir;
+    }
+
+    protected void checkPersistenceDirAccessible(File dir) {
+        if (!(dir.exists() && dir.isDirectory() && dir.canRead() && dir.canWrite())) {
+            FatalConfigurationRuntimeException problem = new FatalConfigurationRuntimeException("Invalid persistence directory " + dir + ": " +
+                    (!dir.exists() ? "does not exist" :
+                            (!dir.isDirectory() ? "not a directory" :
+                                    (!dir.canRead() ? "not readable" :
+                                            (!dir.canWrite() ? "not writable" : "unknown reason")))));
+            log.debug("Invalid persistence directory "+dir+" (rethrowing): "+problem, problem);
+        } else {
+            log.debug("Created dir {} for {}", dir, this);
+        }
+    }
+
+    protected void checkPersistenceDirNonEmpty(File persistenceDir) {
+        FatalConfigurationRuntimeException problem;
+        if (!persistenceDir.exists()) {
+            problem = new FatalConfigurationRuntimeException("Invalid persistence directory "+persistenceDir+" because directory does not exist");
+            log.debug("Invalid persistence directory "+persistenceDir+" (rethrowing): "+problem, problem);
+            throw problem;
+        } if (isMementoDirExistButEmpty(persistenceDir)) {
+            problem = new FatalConfigurationRuntimeException("Invalid persistence directory "+persistenceDir+" because directory is empty");
+            log.debug("Invalid persistence directory "+persistenceDir+" (rethrowing): "+problem, problem);
+            throw problem;
+        }
+    }
+
+    protected File backupDirByCopying(File dir) throws IOException, InterruptedException {
+        File parentDir = dir.getParentFile();
+        String simpleName = dir.getName();
+        String timestamp = new SimpleDateFormat("yyyyMMdd-hhmmssSSS").format(new Date());
+        File backupDir = new File(parentDir, simpleName+"."+timestamp+".bak");
+        
+        FileUtil.copyDir(dir, backupDir);
+        FileUtil.setFilePermissionsTo700(backupDir);
+        
+        return backupDir;
+    }
+
+    protected File backupDirByMoving(File dir) throws InterruptedException, IOException {
+        File parentDir = dir.getParentFile();
+        String simpleName = dir.getName();
+        String timestamp = new SimpleDateFormat("yyyyMMdd-hhmmssSSS").format(new Date());
+        File newDir = new File(parentDir, simpleName+"."+timestamp+".bak");
+
+        FileUtil.moveDir(dir, newDir);
+        return newDir;
+    }
+
+    private static boolean WARNED_ON_NON_ATOMIC_FILE_UPDATES = false; 
+    /** 
+     * Attempts an fs level atomic move then fall back to pure java rename.
+     * Assumes files are on same mount point.
+     * <p>
+     * TODO Java 7 gives an atomic Files.move() which would be preferred.
+     */
+    static void moveFile(File srcFile, File destFile) throws IOException, InterruptedException {
+        // Try rename first - it is a *much* cheaper call than invoking a system call in Java. 
+        // However, rename is not guaranteed cross platform to succeed if the destination exists,
+        // and not guaranteed to be atomic, but it usually seems to do the right thing...
+        boolean result;
+        result = srcFile.renameTo(destFile);
+        if (result) {
+            if (log.isTraceEnabled()) log.trace("java rename of {} to {} completed", srcFile, destFile);
+            return;
+        }
+        
+        if (!Os.isMicrosoftWindows()) {
+            // this command, if it succeeds, is guaranteed to be atomic, and it will usually overwrite
+            String cmd = "mv '"+srcFile.getAbsolutePath()+"' '"+destFile.getAbsolutePath()+"'";
+            
+            int exitStatus = new ProcessTool().execCommands(MutableMap.<String,String>of(), MutableList.of(cmd), null);
+            // prefer the above to the below because it wraps it in the appropriate bash
+//            Process proc = Runtime.getRuntime().exec(cmd);
+//            result = proc.waitFor();
+            
+            if (log.isTraceEnabled()) log.trace("FS move of {} to {} completed, code {}", new Object[] { srcFile, destFile, exitStatus });
+            if (exitStatus == 0) return;
+        }
+        
+        // finally try a delete - but explicitly warn this is not going to be atomic
+        // so if another node reads it might see no master
+        if (!WARNED_ON_NON_ATOMIC_FILE_UPDATES) {
+            WARNED_ON_NON_ATOMIC_FILE_UPDATES = true;
+            log.warn("Unable to perform atomic file update ("+srcFile+" to "+destFile+"); file system not recommended for production HA/DR");
+        }
+        destFile.delete();
+        result = srcFile.renameTo(destFile);
+        if (log.isTraceEnabled()) log.trace("java delete and rename of {} to {} completed, code {}", new Object[] { srcFile, destFile, result });
+        if (result) 
+            return;
+        Files.copy(srcFile, destFile);
+        srcFile.delete();
+        throw new IOException("Could not move "+destFile+" to "+srcFile);
+    }
+    
+    /**
+     * True if directory exists, but is entirely empty, or only contains empty directories.
+     */
+    static boolean isMementoDirExistButEmpty(String dir) {
+        return isMementoDirExistButEmpty(new File(dir));
+    }
+    
+    static boolean isMementoDirExistButEmpty(File dir) {
+        if (!dir.exists()) return false;
+        File[] contents = dir.listFiles();
+        if (contents == null) return false;
+        
+        for (File sub : contents) {
+            if (sub.isFile()) return false;
+            if (sub.isDirectory() && sub.listFiles().length > 0) return false;
+        }
+        return true;
+    }
+
+    @Override
+    public void deleteCompletely() {
+        deleteCompletely(getBaseDir());
+    }
+    
+    public static void deleteCompletely(File d) {
+        DeletionResult result = Os.deleteRecursively(d);
+        if (!result.wasSuccessful())
+            log.warn("Unable to delete persistence dir "+d);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/FileBasedStoreObjectAccessor.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/FileBasedStoreObjectAccessor.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/FileBasedStoreObjectAccessor.java
new file mode 100644
index 0000000..41aefc0
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/FileBasedStoreObjectAccessor.java
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Date;
+
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.io.FileUtil;
+import org.apache.brooklyn.util.text.Strings;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Charsets;
+import com.google.common.base.Objects;
+import com.google.common.base.Throwables;
+import com.google.common.io.Files;
+
+/**
+ * Reads/writes to a file. This impl does it immediately, with no synchronisation.
+ * Callers should wrap in {@link StoreObjectAccessorLocking} if multiple threads may be accessing this.
+ *
+ * @author aled
+ */
+public class FileBasedStoreObjectAccessor implements PersistenceObjectStore.StoreObjectAccessor {
+    private static final Logger LOG = LoggerFactory.getLogger(FileBasedStoreObjectAccessor.class);
+
+    public FileBasedStoreObjectAccessor(File file, String tmpExtension) {
+        this.file = file;
+        this.tmpFile = new File(file.getParentFile(), file.getName()+(Strings.isBlank(tmpExtension) ? ".tmp" : tmpExtension));
+    }
+
+    private final File file;
+    private final File tmpFile;
+    
+    @Override
+    public String get() {
+        try {
+            if (!exists()) return null;
+            return Files.asCharSource(file, Charsets.UTF_8).read();
+        } catch (IOException e) {
+            throw Throwables.propagate(e);
+        }
+    }
+
+    @Override
+    public byte[] getBytes() {
+        try {
+            if (!exists()) return null;
+            return Files.asByteSource(file).read();
+        } catch (IOException e) {
+            throw Throwables.propagate(e);
+        }
+    }
+
+    @Override
+    public boolean exists() {
+        return file.exists();
+    }
+
+    // Setting permissions to 600 reduces objectAccessor.put performance from about 5000 per second to 3000 per second
+    // in java 6. With Java 7's Files.setPosixFilePermissions, this might well improve.
+    @Override
+    public void put(String val) {
+        try {
+            if (val==null) val = "";
+            FileUtil.setFilePermissionsTo600(tmpFile);
+            Files.write(val, tmpFile, Charsets.UTF_8);
+            FileBasedObjectStore.moveFile(tmpFile, file);
+        } catch (IOException e) {
+            throw Exceptions.propagate(e);
+        } catch (InterruptedException e) {
+            throw Exceptions.propagate(e);
+        }
+    }
+
+    @Override
+    public void append(String val) {
+        try {
+            if (val==null) val = "";
+            FileUtil.setFilePermissionsTo600(file);
+            Files.append(val, file, Charsets.UTF_8);
+            
+        } catch (IOException e) {
+            throw Exceptions.propagate(e);
+        }
+    }
+
+    @Override
+    public void delete() {
+        if (!file.delete()) {
+            if (!file.exists()) {
+                LOG.debug("Unable to delete " + file.getAbsolutePath() + ". Probably did not exist.");
+            } else {
+                LOG.warn("Unable to delete " + file.getAbsolutePath() + ". Probably still locked.");
+            }
+        }
+        if (tmpFile.exists() && !tmpFile.delete()) {
+            // tmpFile is probably already deleted, so don't even log debug if it does not exist
+            LOG.warn("Unable to delete " + tmpFile.getAbsolutePath() + ". Probably still locked.");
+        }
+    }
+
+    @Override
+    public Date getLastModifiedDate() {
+        long result = file.lastModified();
+        if (result==0) return null;
+        return new Date(result);
+    }
+    
+    @Override
+    public String toString() {
+        return Objects.toStringHelper(this).add("file", file).toString();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/LocationWithObjectStore.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/LocationWithObjectStore.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/LocationWithObjectStore.java
new file mode 100644
index 0000000..9a5c693
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/LocationWithObjectStore.java
@@ -0,0 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+/** Marker interface for locations which can create a {@link PersistenceObjectStore} */
+public interface LocationWithObjectStore {
+
+    /** Creates a {@link PersistenceObjectStore} pointed at the given container/directory. */
+    public PersistenceObjectStore newPersistenceObjectStore(String container);
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/MementoSerializer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/MementoSerializer.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/MementoSerializer.java
new file mode 100644
index 0000000..1e924ec
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/MementoSerializer.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import org.apache.brooklyn.api.mgmt.ha.ManagementNodeSyncRecord;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMemento;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoPersister.LookupContext;
+
+/** Serializes the given object; it is often used with {@link BrooklynMemento} for persisting and restoring,
+ * though it can be used for any object (and is also used for the {@link ManagementNodeSyncRecord} instances) */
+public interface MementoSerializer<T> {
+    
+    public static final MementoSerializer<String> NOOP = new MementoSerializer<String>() {
+        @Override
+        public String toString(String memento) {
+            return memento;
+        }
+        @Override
+        public String fromString(String string) {
+            return string;
+        }
+        @Override
+        public void setLookupContext(LookupContext lookupContext) {
+            // no-op
+        }
+        @Override
+        public void unsetLookupContext() {
+            // no-op
+        }
+    };
+    
+    String toString(T memento);
+    T fromString(String string);
+    void setLookupContext(LookupContext lookupContext);
+    void unsetLookupContext();
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/PersistMode.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/PersistMode.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/PersistMode.java
new file mode 100644
index 0000000..fac764b
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/PersistMode.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+public enum PersistMode {
+    DISABLED,
+    AUTO,
+    REBIND,
+    CLEAN;
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/PersistenceActivityMetrics.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/PersistenceActivityMetrics.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/PersistenceActivityMetrics.java
new file mode 100644
index 0000000..14943bb
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/PersistenceActivityMetrics.java
@@ -0,0 +1,83 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.time.Duration;
+
+public class PersistenceActivityMetrics {
+    
+    final static int MAX_ERRORS = 200;
+    
+    long count=0, failureCount=0;
+    Long lastSuccessTime, lastDuration, lastFailureTime;
+    List<Map<String,Object>> errorMessages = MutableList.of();
+
+    public void noteSuccess(Duration duration) {
+        count++;
+        lastSuccessTime = System.currentTimeMillis();
+        lastDuration = duration.toMilliseconds();
+    }
+    
+    public void noteFailure(Duration duration) {
+        count++;
+        failureCount++;
+        lastFailureTime = System.currentTimeMillis();
+        lastDuration = duration!=null ? duration.toMilliseconds() : -1;
+    }
+
+    public void noteError(String error) {
+        noteErrorObject(error);
+    }
+    
+    public void noteError(List<?> error) {
+        noteErrorObject(error);
+    }
+    
+    /** error should be json-serializable; exceptions can be problematic */
+    protected synchronized void noteErrorObject(Object error) {
+        errorMessages.add(0, MutableMap.<String,Object>of("error", error, "timestamp", System.currentTimeMillis()));
+        while (errorMessages.size() > MAX_ERRORS) {
+            errorMessages.remove(errorMessages.size()-1);
+        }
+    }
+    
+    public synchronized Map<String,Object> asMap() {
+        Map<String,Object> result = MutableMap.of();
+        result.put("count", count);
+        result.put("lastSuccessTimeUtc", lastSuccessTime);
+        result.put("lastSuccessTimeMillisSince", since(lastSuccessTime));
+        result.put("lastDuration", lastDuration);
+        result.put("failureCount", failureCount);
+        result.put("lastFailureTimeUtc", lastFailureTime);
+        result.put("lastFailureTimeMillisSince", since(lastFailureTime));
+        result.put("errorMessages", MutableList.copyOf(errorMessages));
+        return result;
+    }
+
+    private Long since(Long time) {
+        if (time==null) return null;
+        return System.currentTimeMillis() - time;
+    }
+    
+}
\ No newline at end of file


[60/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/LocationPredicates.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/LocationPredicates.java b/core/src/main/java/org/apache/brooklyn/location/basic/LocationPredicates.java
deleted file mode 100644
index dc1bc11..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/LocationPredicates.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.config.ConfigKey.HasConfigKey;
-
-import com.google.common.base.Objects;
-import com.google.common.base.Predicate;
-
-public class LocationPredicates {
-
-    public static <T> Predicate<Location> idEqualTo(final T val) {
-        return new Predicate<Location>() {
-            @Override
-            public boolean apply(@Nullable Location input) {
-                return (input != null) && Objects.equal(input.getId(), val);
-            }
-        };
-    }
-    
-    public static <T> Predicate<Location> displayNameEqualTo(final T val) {
-        return new Predicate<Location>() {
-            @Override
-            public boolean apply(@Nullable Location input) {
-                return (input != null) && Objects.equal(input.getDisplayName(), val);
-            }
-        };
-    }
-    
-    public static <T> Predicate<Location> configEqualTo(final ConfigKey<T> configKey, final T val) {
-        return new Predicate<Location>() {
-            @Override
-            public boolean apply(@Nullable Location input) {
-                return (input != null) && Objects.equal(input.getConfig(configKey), val);
-            }
-        };
-    }
-
-    public static <T> Predicate<Location> configEqualTo(final HasConfigKey<T> configKey, final T val) {
-        return new Predicate<Location>() {
-            @Override
-            public boolean apply(@Nullable Location input) {
-                return (input != null) && Objects.equal(input.getConfig(configKey), val);
-            }
-        };
-    }
-
-    /**
-     * Returns a predicate that determines if a given location is a direct child of this {@code parent}.
-     */
-    public static <T> Predicate<Location> isChildOf(final Location parent) {
-        return new Predicate<Location>() {
-            @Override
-            public boolean apply(@Nullable Location input) {
-                return (input != null) && Objects.equal(input.getParent(), parent);
-            }
-        };
-    }
-
-    /**
-     * Returns a predicate that determines if a given location is a descendant of this {@code ancestor}.
-     */
-    public static <T> Predicate<Location> isDescendantOf(final Location ancestor) {
-        return new Predicate<Location>() {
-            @Override
-            public boolean apply(@Nullable Location input) {
-                // assumes impossible to have cycles in location-hierarchy
-                Location contenderAncestor = (input == null) ? input : input.getParent();
-                while (contenderAncestor != null) {
-                    if (Objects.equal(contenderAncestor, ancestor)) {
-                        return true;
-                    }
-                    contenderAncestor = contenderAncestor.getParent();
-                }
-                return false;
-            }
-        };
-    }
-
-    public static <T> Predicate<Location> managed() {
-        return new Predicate<Location>() {
-            @Override
-            public boolean apply(@Nullable Location input) {
-                return (input != null) && Locations.isManaged(input);
-            }
-        };
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/LocationPropertiesFromBrooklynProperties.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/LocationPropertiesFromBrooklynProperties.java b/core/src/main/java/org/apache/brooklyn/location/basic/LocationPropertiesFromBrooklynProperties.java
deleted file mode 100644
index 282988d..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/LocationPropertiesFromBrooklynProperties.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static com.google.common.base.Preconditions.checkArgument;
-
-import java.io.File;
-import java.util.Map;
-
-import org.apache.brooklyn.core.config.ConfigUtils;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.server.BrooklynServerConfig;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.internal.ssh.SshTool;
-import org.apache.brooklyn.util.os.Os;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Predicates;
-import com.google.common.base.Strings;
-import com.google.common.collect.Maps;
-
-/**
- * The properties to use for locations, loaded from brooklyn.properties file.
- * 
- * @author aledsage
- **/
-public class LocationPropertiesFromBrooklynProperties {
-
-    private static final Logger LOG = LoggerFactory.getLogger(LocationPropertiesFromBrooklynProperties.class);
-
-    @SuppressWarnings("deprecation")
-    protected static final Map<String, String> DEPRECATED_KEYS_MAPPING = new DeprecatedKeysMappingBuilder(LOG)
-            .camelToHyphen(LocationConfigKeys.DISPLAY_NAME)
-            .camelToHyphen(LocationConfigKeys.PRIVATE_KEY_FILE)
-            .camelToHyphen(LocationConfigKeys.PRIVATE_KEY_DATA)
-            .camelToHyphen(LocationConfigKeys.PRIVATE_KEY_PASSPHRASE)
-            .camelToHyphen(LocationConfigKeys.PUBLIC_KEY_FILE)
-            .camelToHyphen(LocationConfigKeys.PUBLIC_KEY_DATA)
-            .camelToHyphen(LocationConfigKeys.CALLER_CONTEXT)
-            .build();
-    
-    /**
-     * Finds the properties that apply to location, stripping off the prefixes.
-     * 
-     * Order of preference (in ascending order) is:
-     * <ol>
-     * <li>brooklyn.location.*
-     * <li>brooklyn.location.provider.*
-     * <li>brooklyn.location.named.namedlocation.*
-     * </ol>
-     * <p>
-     * Converts deprecated hyphenated properties to the non-deprecated camelCase format. 
-     */
-    public Map<String, Object> getLocationProperties(String provider, String namedLocation, Map<String, ?> properties) {
-        ConfigBag result = ConfigBag.newInstance();
-        
-        if (!Strings.isNullOrEmpty(provider)) 
-            result.put(LocationConfigKeys.CLOUD_PROVIDER, provider);
-        // named properties are preferred over providerOrApi properties
-        result.putAll(transformDeprecated(getGenericLocationSingleWordProperties(properties)));
-        if (!Strings.isNullOrEmpty(provider)) result.putAll(transformDeprecated(getScopedLocationProperties(provider, properties)));
-        if (!Strings.isNullOrEmpty(namedLocation)) result.putAll(transformDeprecated(getNamedLocationProperties(namedLocation, properties)));
-        
-        setLocalTempDir(properties, result);
-        
-        return result.getAllConfigRaw();
-    }
-
-    /** allow the temp dir where ssh temporary files on the brooklyn server side are placed */
-    public static void setLocalTempDir(Map<String,?> source, ConfigBag target) {
-        // TODO better would be to use BrooklynServerConfig, requiring management passed in
-        String brooklynDataDir = (String) source.get(BrooklynServerConfig.getMgmtBaseDir(source));
-        if (brooklynDataDir != null && brooklynDataDir.length() > 0) {
-            String tempDir = Os.mergePaths(brooklynDataDir, "tmp", "ssh");
-            target.putIfAbsentAndNotNull(SshTool.PROP_LOCAL_TEMP_DIR, tempDir);
-            Os.deleteOnExitEmptyParentsUpTo(new File(tempDir), new File(brooklynDataDir));
-        }
-    }
-    
-    /**
-     * Gets the named provider (e.g. if using a property like {@code brooklyn.location.named.myfavourite=localhost}, then
-     * {@code getNamedProvider("myfavourite", properties)} will return {@code "localhost"}).
-     */
-    protected String getNamedProvider(String namedLocation, Map<String, ?> properties) {
-        String key = String.format("brooklyn.location.named.%s", namedLocation);
-        return (String) properties.get(key);
-    }
-    
-    /**
-     * Returns those properties in the form "brooklyn.location.xyz", where "xyz" is any
-     * key that does not contain dots. We do this special (sub-optimal!) filtering
-     * because we want to exclude brooklyn.location.named.*, brooklyn.location.jclouds.*, etc.
-     * We only want those properties that are to be generic for all locations.
-     * 
-     * Strips off the prefix in the returned map.
-     */
-    protected Map<String, Object> getGenericLocationSingleWordProperties(Map<String, ?> properties) {
-        return getMatchingSingleWordProperties("brooklyn.location.", properties);
-    }
-
-    /**
-     * Gets all properties that start with {@code "brooklyn.location."+scopeSuffix+"."}, stripping off
-     * the prefix in the returned map.
-     */
-    protected Map<String, Object> getScopedLocationProperties(String scopeSuffix, Map<String, ?> properties) {
-        checkArgument(!scopeSuffix.startsWith("."), "scopeSuffix \"%s\" should not start with \".\"", scopeSuffix);
-        checkArgument(!scopeSuffix.endsWith("."), "scopeSuffix \"%s\" should not end with \".\"", scopeSuffix);
-        String prefix = String.format("brooklyn.location.%s.", scopeSuffix);
-        return ConfigUtils.filterForPrefixAndStrip(properties, prefix).asMapWithStringKeys();
-    }
-
-    /**
-     * Gets all properties that start with the given {@code fullPrefix}, stripping off
-     * the prefix in the returned map.
-     */
-    protected Map<String, Object> getMatchingProperties(String fullPrefix, Map<String, ?> properties) {
-        return ConfigUtils.filterForPrefixAndStrip(properties, fullPrefix).asMapWithStringKeys();
-    }
-
-    /**
-     * Gets all properties that start with either of the given prefixes. The {@code fullPreferredPrefix} 
-     * properties will override any duplicates in {@code fullDeprecatedPrefix}. If there are any
-     * properties that match the {@code fullDeprecatedPrefix}, then a warning will be logged.
-     * 
-     * @see #getMatchingProperties(String, Map)
-     */
-    protected Map<String, Object> getMatchingProperties(String fullPreferredPrefix, String fullDeprecatedPrefix, Map<String, ?> properties) {
-        Map<String, Object> deprecatedResults = getMatchingProperties(fullDeprecatedPrefix, properties);
-        Map<String, Object> results = getMatchingProperties(fullPreferredPrefix, properties);
-        
-        if (deprecatedResults.size() > 0) {
-            LOG.warn("Deprecated use of properties prefix "+fullDeprecatedPrefix+"; instead use "+fullPreferredPrefix);
-            return MutableMap.<String, Object>builder()
-                    .putAll(deprecatedResults)
-                    .putAll(results)
-                    .build();
-        } else {
-            return results;
-        }
-    }
-
-    /**
-     * Gets all properties that start with the given {@code fullPrefix}, stripping off
-     * the prefix in the returned map.
-     * 
-     * Returns only those properties whose key suffix is a single word (i.e. contains no dots).
-     * We do this special (sub-optimal!) filtering because we want sub-scoped things 
-     * (e.g. could want brooklyn.location.privateKeyFile, but not brooklyn.location.named.*). 
-     */
-    protected Map<String, Object> getMatchingSingleWordProperties(String fullPrefix, Map<String, ?> properties) {
-        BrooklynProperties filteredProperties = ConfigUtils.filterForPrefixAndStrip(properties, fullPrefix);
-        return ConfigUtils.filterFor(filteredProperties, Predicates.not(Predicates.containsPattern("\\."))).asMapWithStringKeys();
-    }
-
-    /**
-     * Gets all single-word properties that start with either of the given prefixes. The {@code fullPreferredPrefix} 
-     * properties will override any duplicates in {@code fullDeprecatedPrefix}. If there are any
-     * properties that match the {@code fullDeprecatedPrefix}, then a warning will be logged.
-     * 
-     * @see #getMatchingSingleWordProperties(String, Map)
-     */
-    protected Map<String, Object> getMatchingSingleWordProperties(String fullPreferredPrefix, String fullDeprecatedPrefix, Map<String, ?> properties) {
-        Map<String, Object> deprecatedResults = getMatchingSingleWordProperties(fullDeprecatedPrefix, properties);
-        Map<String, Object> results = getMatchingSingleWordProperties(fullPreferredPrefix, properties);
-        
-        if (deprecatedResults.size() > 0) {
-            LOG.warn("Deprecated use of properties prefix "+fullDeprecatedPrefix+"; instead use "+fullPreferredPrefix);
-            return MutableMap.<String, Object>builder()
-                    .putAll(deprecatedResults)
-                    .putAll(results)
-                    .build();
-        } else {
-            return results;
-        }
-    }
-
-    protected Map<String, Object> getNamedLocationProperties(String locationName, Map<String, ?> properties) {
-        checkArgument(!Strings.isNullOrEmpty(locationName), "locationName should not be blank");
-        String prefix = String.format("brooklyn.location.named.%s.", locationName);
-        return ConfigUtils.filterForPrefixAndStrip(properties, prefix).asMapWithStringKeys();
-    }
-
-    protected Map<String, Object> transformDeprecated(Map<String, ?> properties) {
-        Map<String,Object> result = Maps.newLinkedHashMap();
-        Map<String, String> deprecatedKeysMapping = getDeprecatedKeysMapping();
-        
-        for (Map.Entry<String,?> entry : properties.entrySet()) {
-            String key = entry.getKey();
-            Object value = entry.getValue();
-            if (deprecatedKeysMapping.containsKey(key)) {
-                String transformedKey = deprecatedKeysMapping.get(key);
-                LOG.warn("Deprecated key {}, transformed to {}; will not be supported in future versions", new Object[] {key, transformedKey});
-                result.put(transformedKey, value);
-            } else {
-                result.put(key, value);
-            }
-        }
-        
-        return result;
-    }
-    
-    protected Map<String,String> getDeprecatedKeysMapping() {
-        return DEPRECATED_KEYS_MAPPING;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/LocationTypeSnapshot.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/LocationTypeSnapshot.java b/core/src/main/java/org/apache/brooklyn/location/basic/LocationTypeSnapshot.java
deleted file mode 100644
index 68fca81..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/LocationTypeSnapshot.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.sensor.EnricherType;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.objs.BrooklynTypeSnapshot;
-
-public class LocationTypeSnapshot extends BrooklynTypeSnapshot implements EnricherType {
-    
-    private static final long serialVersionUID = 9150132836104748237L;
-
-    LocationTypeSnapshot(String name, Map<String, ConfigKey<?>> configKeys) {
-        super(name, configKeys);
-    }
-
-    @Override
-    public boolean equals(Object obj) {
-        if (this == obj) return true;
-        return (obj instanceof LocationTypeSnapshot) && super.equals(obj);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/Locations.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/Locations.java b/core/src/main/java/org/apache/brooklyn/location/basic/Locations.java
deleted file mode 100644
index 0e84d64..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/Locations.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.mgmt.LocationManager;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.yaml.Yamls;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.ImmutableList;
-
-public class Locations {
-
-    private static final Logger log = LoggerFactory.getLogger(Locations.class);
-
-    public static final LocationsFilter USE_FIRST_LOCATION = new LocationsFilter() {
-        private static final long serialVersionUID = 3100091615409115890L;
-
-        @Override
-        public List<Location> filterForContext(List<Location> locations, Object context) {
-            if (locations.size()<=1) return locations;
-            return ImmutableList.of(locations.get(0));
-        }
-    };
-
-    public interface LocationsFilter extends Serializable {
-        public List<Location> filterForContext(List<Location> locations, Object context);
-    }
-    
-    /** as {@link Machines#findUniqueMachineLocation(Iterable)} */
-    public static Maybe<MachineLocation> findUniqueMachineLocation(Iterable<? extends Location> locations) {
-        return Machines.findUniqueMachineLocation(locations);
-    }
-    
-    /** as {@link Machines#findUniqueSshMachineLocation(Iterable)} */
-    public static Maybe<SshMachineLocation> findUniqueSshMachineLocation(Iterable<? extends Location> locations) {
-        return Machines.findUniqueSshMachineLocation(locations);
-    }
-
-    /** if no locations are supplied, returns locations on the entity, or in the ancestors, until it finds a non-empty set,
-     * or ultimately the empty set if no locations are anywhere */ 
-    public static Collection<? extends Location> getLocationsCheckingAncestors(Collection<? extends Location> locations, Entity entity) {
-        // look in ancestors if location not set here
-        Entity ancestor = entity;
-        while ((locations==null || locations.isEmpty()) && ancestor!=null) {
-            locations = ancestor.getLocations();
-            ancestor = ancestor.getParent();
-        }
-        return locations;
-    }
-    
-    public static boolean isManaged(Location loc) {
-        ManagementContext mgmt = ((LocationInternal)loc).getManagementContext();
-        return (mgmt != null) && mgmt.isRunning() && mgmt.getLocationManager().isManaged(loc);
-    }
-
-    public static void unmanage(Location loc) {
-        if (isManaged(loc)) {
-            ManagementContext mgmt = ((LocationInternal)loc).getManagementContext();
-            mgmt.getLocationManager().unmanage(loc);
-        }
-    }
-    
-    /**
-     * Registers the given location (and all its children) with the management context. 
-     * @throws IllegalStateException if the parent location is not already managed
-     * 
-     * @since 0.6.0 (added only for backwards compatibility, where locations are being created directly; previously in {@link Entities}).
-     * @deprecated in 0.6.0; use {@link LocationManager#createLocation(LocationSpec)} instead.
-     */
-    public static void manage(Location loc, ManagementContext managementContext) {
-        if (!managementContext.getLocationManager().isManaged(loc)) {
-            log.warn("Deprecated use of unmanaged location ("+loc+"); will be managed automatically now but not supported in future versions");
-            // FIXME this occurs MOST OF THE TIME e.g. including BrooklynLauncher.location(locationString)
-            // not sure what is the recommend way to convert from locationString to locationSpec, or the API we want to expose;
-            // deprecating some of the LocationRegistry methods seems sensible?
-            log.debug("Stack trace for location of: Deprecated use of unmanaged location; will be managed automatically now but not supported in future versions", new Exception("TRACE for: Deprecated use of unmanaged location"));
-            managementContext.getLocationManager().manage(loc);
-        }
-    }
-
-    public static Location coerce(ManagementContext mgmt, Object rawO) {
-        if (rawO==null)
-            return null;
-        if (rawO instanceof Location)
-            return (Location)rawO;
-        
-        Object raw = rawO;
-        if (raw instanceof String)
-            raw = Yamls.parseAll((String)raw).iterator().next();
-        
-        String name;
-        Map<?, ?> flags = null;
-        if (raw instanceof Map) {
-            // for yaml, take the key, and merge with locationFlags
-            Map<?,?> tm = ((Map<?,?>)raw);
-            if (tm.size()!=1) {
-                throw new IllegalArgumentException("Location "+rawO+" is invalid; maps must have only one key, being the location spec string");
-            }
-            name = (String) tm.keySet().iterator().next();
-            flags = (Map<?, ?>) tm.values().iterator().next();
-            
-        } else if (raw instanceof String) {
-            name = (String)raw;
-            
-        } else {
-            throw new IllegalArgumentException("Location "+rawO+" is invalid; can only parse strings or maps");
-        }
-        return mgmt.getLocationRegistry().resolve(name, flags);
-    }
-    
-    public static Collection<? extends Location> coerceToCollection(ManagementContext mgmt, Object rawO) {
-        if (rawO==null) return null;
-        Object raw = rawO;
-        if (raw instanceof Collection) {
-            List<Location> result = MutableList.<Location>of();
-            for (Object o: (Collection<?>)raw)
-                result.add(coerce(mgmt, o));
-            return result;
-        }
-        if (raw instanceof String) {
-            raw = Yamls.parseAll((String)raw).iterator().next();
-            if (raw instanceof Collection)
-                return coerceToCollection(mgmt, raw);
-        }
-        return Collections.singletonList( coerce(mgmt, raw) );
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/Machines.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/Machines.java b/core/src/main/java/org/apache/brooklyn/location/basic/Machines.java
deleted file mode 100644
index ae81e22..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/Machines.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.net.InetAddress;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Iterables;
-
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.net.HasNetworkAddresses;
-
-/** utilities for working with MachineLocations */
-public class Machines {
-
-    private static final Logger log = LoggerFactory.getLogger(Machines.class);
-    
-    public static Maybe<String> getSubnetHostname(Location where) {
-        // TODO Should we look at HasNetworkAddresses? But that's not a hostname.
-        String hostname = null;
-        if (where instanceof HasSubnetHostname) {
-            hostname = ((HasSubnetHostname) where).getSubnetHostname();
-        }
-        if (hostname == null && where instanceof MachineLocation) {
-            InetAddress addr = ((MachineLocation) where).getAddress();
-            if (addr != null) hostname = addr.getHostAddress();
-        }
-        log.debug("computed subnet hostname {} for {}", hostname, where);
-        // TODO if Maybe.absent(message) appears, could/should use that
-        // TODO If no machine available, should we throw new IllegalStateException("Cannot find hostname for "+where);
-        return Maybe.fromNullable(hostname);
-    }
-
-    public static Maybe<String> getSubnetIp(Location where) {
-        // TODO Too much duplication between the ip and hostname methods
-        String result = null;
-        if (where instanceof HasSubnetHostname) {
-            result = ((HasSubnetHostname) where).getSubnetIp();
-        }
-        if (where instanceof HasNetworkAddresses) {
-            Set<String> privateAddrs = ((HasNetworkAddresses) where).getPrivateAddresses();
-            if (privateAddrs.size() > 0) {
-                result = Iterables.get(privateAddrs, 0);
-            }
-        }
-        if (result == null && where instanceof MachineLocation) {
-            InetAddress addr = ((MachineLocation) where).getAddress();
-            if (addr != null) result = addr.getHostAddress();
-        }
-        log.debug("computed subnet host ip {} for {}", result, where);
-        return Maybe.fromNullable(result);
-    }
-
-    @SuppressWarnings("unchecked")
-    public static <T> Maybe<T> findUniqueElement(Iterable<?> items, Class<T> type) {
-        if (items==null) return null;
-        Iterator<?> i = items.iterator();
-        T result = null;
-        while (i.hasNext()) {
-            Object candidate = i.next();
-            if (type.isInstance(candidate)) {
-                if (result==null) result = (T)candidate;
-                else {
-                    if (log.isTraceEnabled())
-                        log.trace("Multiple instances of "+type+" in "+items+"; ignoring");
-                    return Maybe.absent(new IllegalStateException("Multiple instances of "+type+" in "+items+"; expected a single one"));
-                }
-            }
-        }
-        if (result==null) 
-            return Maybe.absent(new IllegalStateException("No instances of "+type+" available (in "+items+")"));
-        return Maybe.of(result);
-    }
-    
-    public static Maybe<MachineLocation> findUniqueMachineLocation(Iterable<? extends Location> locations) {
-        return findUniqueElement(locations, MachineLocation.class);
-    }
-
-    public static Maybe<SshMachineLocation> findUniqueSshMachineLocation(Iterable<? extends Location> locations) {
-        return findUniqueElement(locations, SshMachineLocation.class);
-    }
-
-    public static Maybe<WinRmMachineLocation> findUniqueWinRmMachineLocation(Iterable<? extends Location> locations) {
-        return findUniqueElement(locations, WinRmMachineLocation.class);
-    }
-
-    public static Maybe<String> findSubnetHostname(Iterable<? extends Location> ll) {
-        Maybe<MachineLocation> l = findUniqueMachineLocation(ll);
-        if (!l.isPresent()) {
-            return Maybe.absent();
-//            throw new IllegalStateException("Cannot find hostname for among "+ll);
-        }
-        return Machines.getSubnetHostname(l.get());
-    }
-
-    public static Maybe<String> findSubnetHostname(Entity entity) {
-        String sh = entity.getAttribute(Attributes.SUBNET_HOSTNAME);
-        if (sh!=null) return Maybe.of(sh);
-        return findSubnetHostname(entity.getLocations());
-    }
-    
-    public static Maybe<String> findSubnetOrPublicHostname(Entity entity) {
-        String hn = entity.getAttribute(Attributes.HOSTNAME);
-        if (hn!=null) {
-            // attributes already set, see if there was a SUBNET_HOSTNAME set
-            // note we rely on (public) hostname being set _after_ subnet_hostname,
-            // to prevent tiny possibility of races resulting in hostname being returned
-            // becasue subnet is still being looked up -- see MachineLifecycleEffectorTasks
-            Maybe<String> sn = findSubnetHostname(entity);
-            if (sn.isPresent()) return sn;
-            // short-circuit discovery if attributes have been set already
-            return Maybe.of(hn);
-        }
-        
-        Maybe<MachineLocation> l = findUniqueMachineLocation(entity.getLocations());
-        if (!l.isPresent()) return Maybe.absent();
-        InetAddress addr = l.get().getAddress();
-        if (addr==null) return Maybe.absent();
-        return Maybe.fromNullable(addr.getHostName());
-    }
-
-    public static Maybe<String> findSubnetOrPrivateIp(Entity entity) {
-        // see comments in findSubnetOrPrivateHostname
-        String hn = entity.getAttribute(Attributes.ADDRESS);
-        if (hn!=null) {
-            Maybe<String> sn = findSubnetIp(entity);
-            if (sn.isPresent()) return sn;
-            return Maybe.of(hn);
-        }
-        
-        Maybe<MachineLocation> l = findUniqueMachineLocation(entity.getLocations());
-        if (!l.isPresent()) return Maybe.absent();
-        InetAddress addr = l.get().getAddress();
-        if (addr==null) return Maybe.absent();
-        return Maybe.fromNullable(addr.getHostAddress());
-    }
-
-    public static Maybe<String> findSubnetIp(Entity entity) {
-        String sh = entity.getAttribute(Attributes.SUBNET_ADDRESS);
-        if (sh!=null) return Maybe.of(sh);
-        return findSubnetIp(entity.getLocations());
-    }
-    
-    public static Maybe<String> findSubnetIp(Iterable<? extends Location> ll) {
-        // TODO Or if can't find MachineLocation, should we throw new IllegalStateException("Cannot find hostname for among "+ll);
-        Maybe<MachineLocation> l = findUniqueMachineLocation(ll);
-        return (l.isPresent()) ? Machines.getSubnetIp(l.get()) : Maybe.<String>absent();
-    }
-
-    /** returns whether it is localhost (and has warned) */
-    public static boolean warnIfLocalhost(Collection<? extends Location> locations, String message) {
-        if (locations.size()==1) {
-            Location l = locations.iterator().next();
-            if (l instanceof LocalhostMachineProvisioningLocation || l instanceof LocalhostMachine) {
-                log.warn(message);
-                return true;
-            }
-        }
-        return false;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/MultiLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/MultiLocation.java b/core/src/main/java/org/apache/brooklyn/location/basic/MultiLocation.java
deleted file mode 100644
index adb44de..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/MultiLocation.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import static com.google.common.base.Preconditions.checkState;
-
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.location.cloud.AbstractAvailabilityZoneExtension;
-import org.apache.brooklyn.location.cloud.AvailabilityZoneExtension;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.apache.brooklyn.util.exceptions.CompoundRuntimeException;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.text.Strings;
-
-import com.google.common.base.Predicate;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Maps;
-import com.google.common.reflect.TypeToken;
-
-/** A location which consists of multiple locations stitched together to form availability zones.
- * The first location will be used by default, but if an {@link AvailabilityZoneExtension}-aware entity
- * is used, it may stripe across each of the locations.  See notes at {@link AvailabilityZoneExtension}. */
-public class MultiLocation<T extends MachineLocation> extends AbstractLocation implements MachineProvisioningLocation<T> {
-
-    private static final long serialVersionUID = 7993091317970457862L;
-    
-    @SuppressWarnings("serial")
-    @SetFromFlag("subLocations")
-    public static final ConfigKey<List<MachineProvisioningLocation<?>>> SUB_LOCATIONS = ConfigKeys.newConfigKey(
-            new TypeToken<List<MachineProvisioningLocation<?>>>() {},
-            "subLocations", 
-            "The sub-machines that this location can delegate to");
-    
-    @Override
-    public void init() {
-        super.init();
-        List<MachineProvisioningLocation<?>> subLocs = getSubLocations();
-        checkState(subLocs.size() >= 1, "sub-locations must not be empty");
-        AvailabilityZoneExtension azExtension = new AvailabilityZoneExtensionImpl(getManagementContext(), subLocs);
-        addExtension(AvailabilityZoneExtension.class, azExtension);
-    }
-
-    public T obtain() throws NoMachinesAvailableException {
-        return obtain(MutableMap.of());
-    }
-    
-    /** finds (creates) and returns a {@link MachineLocation}; 
-     * this always tries the first sub-location, moving on the second and subsequent if the first throws {@link NoMachinesAvailableException}.
-     * (if you want striping across locations, see notes in {@link AvailabilityZoneExtension}.) */
-    @SuppressWarnings("unchecked")
-    @Override
-    public T obtain(Map<?, ?> flags) throws NoMachinesAvailableException {
-        List<MachineProvisioningLocation<?>> sublocsList = getSubLocations();
-        Iterator<MachineProvisioningLocation<?>> sublocs = sublocsList.iterator();
-        List<NoMachinesAvailableException> errors = MutableList.of();
-        while (sublocs.hasNext()) {
-            try {
-                return (T) sublocs.next().obtain(flags);
-            } catch (NoMachinesAvailableException e) {
-                errors.add(e);
-            }
-        }
-        Exception wrapped;
-        String msg;
-        if (errors.size()>1) {
-            wrapped = new CompoundRuntimeException(errors.size()+" sublocation exceptions, including: "+
-                Exceptions.collapseText(errors.get(0)), errors);
-            msg = Exceptions.collapseText(wrapped);
-        } else if (errors.size()==1) {
-            wrapped = errors.get(0);
-            msg = wrapped.getMessage();
-            if (Strings.isBlank(msg)) msg = wrapped.toString();
-        } else {
-            msg = "no sub-locations set for this multi-location";
-            wrapped = null;
-        }
-        throw new NoMachinesAvailableException("No machines available in any of the "+sublocsList.size()+" location"+Strings.s(sublocsList.size())+
-            " configured here: "+msg, wrapped);
-    }
-
-    public List<MachineProvisioningLocation<?>> getSubLocations() {
-        return getRequiredConfig(SUB_LOCATIONS);
-    }
-
-    @SuppressWarnings("unchecked")
-    @Override
-    public MachineProvisioningLocation<T> newSubLocation(Map<?, ?> newFlags) {
-        // TODO shouldn't have to copy config bag as it should be inherited (but currently it is not used inherited everywhere; just most places)
-        return getManagementContext().getLocationManager().createLocation(LocationSpec.create(getClass())
-                .parent(this)
-                .configure(config().getLocalBag().getAllConfig())  // FIXME Should this just be inherited?
-                .configure(newFlags));
-    }
-
-    @SuppressWarnings("unchecked")
-    @Override
-    public void release(T machine) {
-        ((MachineProvisioningLocation<T>)machine.getParent()).release(machine);
-    }
-
-    @Override
-    public Map<String, Object> getProvisioningFlags(Collection<String> tags) {
-        return Maps.<String,Object>newLinkedHashMap();
-    }
-
-    @SuppressWarnings("unchecked")
-    protected MachineProvisioningLocation<T> firstSubLoc() {
-        return (MachineProvisioningLocation<T>) Iterables.get(getSubLocations(), 0);
-    }
-
-    protected <K> K getRequiredConfig(ConfigKey<K> key) {
-        return checkNotNull(getConfig(key), key.getName());
-    }
-
-    public static class AvailabilityZoneExtensionImpl extends AbstractAvailabilityZoneExtension implements AvailabilityZoneExtension {
-
-        private final List<MachineProvisioningLocation<?>> subLocations;
-        
-        public AvailabilityZoneExtensionImpl(ManagementContext managementContext, List<MachineProvisioningLocation<?>> subLocations) {
-            super(managementContext);
-            this.subLocations = ImmutableList.copyOf(subLocations);
-        }
-        
-        @Override
-        protected List<Location> doGetAllSubLocations() {
-            return ImmutableList.<Location>copyOf(subLocations);
-        }
-        
-        @Override
-        protected boolean isNameMatch(Location loc, Predicate<? super String> namePredicate) {
-            return namePredicate.apply(loc.getDisplayName());
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/MultiLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/MultiLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/basic/MultiLocationResolver.java
deleted file mode 100644
index d5f063f..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/MultiLocationResolver.java
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationRegistry;
-import org.apache.brooklyn.api.location.LocationResolver;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.text.KeyValueParser;
-import org.apache.brooklyn.util.text.StringEscapes.JavaStringEscapes;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Lists;
-
-public class MultiLocationResolver implements LocationResolver {
-
-    private static final Logger LOG = LoggerFactory.getLogger(MultiLocationResolver.class);
-
-    private static final String MULTI = "multi";
-    
-    private static final Pattern PATTERN = Pattern.compile("(" + MULTI + "|" + MULTI.toUpperCase() + ")" + ":" + "\\((.*)\\)$");
-    
-    private volatile ManagementContext managementContext;
-
-    @Override
-    public void init(ManagementContext managementContext) {
-        this.managementContext = checkNotNull(managementContext, "managementContext");
-    }
-
-    @Override
-    public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
-        // FIXME pass all flags into the location
-        
-        Map globalProperties = registry.getProperties();
-        Map<String,?> locationArgs;
-        if (spec.equalsIgnoreCase(MULTI)) {
-            locationArgs = MutableMap.copyOf(locationFlags);
-        } else {
-            Matcher matcher = PATTERN.matcher(spec);
-            if (!matcher.matches()) {
-                throw new IllegalArgumentException("Invalid location '" + spec + "'; must specify something like multi(targets=named:foo)");
-            }
-            String args = matcher.group(2);
-            // TODO we are ignoring locationFlags after this (apart from named), looking only at these args
-            locationArgs = KeyValueParser.parseMap(args);
-        }
-        String namedLocation = (String) locationFlags.get("named");
-
-        Map<String, Object> filteredProperties = new LocationPropertiesFromBrooklynProperties().getLocationProperties(null, namedLocation, globalProperties);
-        MutableMap<String, Object> flags = MutableMap.<String, Object>builder()
-                .putAll(filteredProperties)
-                .putAll(locationFlags)
-                .removeAll("named")
-                .putAll(locationArgs).build();
-        
-        if (locationArgs.get("targets") == null) {
-            throw new IllegalArgumentException("target must be specified in single-machine spec");
-        }
-        
-        // TODO do we need to pass location flags etc into the children to ensure they are inherited?
-        List<Location> targets = Lists.newArrayList();
-        Object targetSpecs = locationArgs.remove("targets");
-        try {
-            if (targetSpecs instanceof String) {
-                for (String targetSpec : JavaStringEscapes.unwrapJsonishListIfPossible((String)targetSpecs)) {
-                    targets.add(managementContext.getLocationRegistry().resolve(targetSpec));
-                }
-            } else if (targetSpecs instanceof Iterable) {
-                for (Object targetSpec: (Iterable<?>)targetSpecs) {
-                    if (targetSpec instanceof String) {
-                        targets.add(managementContext.getLocationRegistry().resolve((String)targetSpec));
-                    } else {
-                        Set<?> keys = ((Map<?,?>)targetSpec).keySet();
-                        if (keys.size()!=1) 
-                            throw new IllegalArgumentException("targets supplied to MultiLocation must be a list of single-entry maps (got map of size "+keys.size()+": "+targetSpec+")");
-                        Object key = keys.iterator().next();
-                        Object flagsS = ((Map<?,?>)targetSpec).get(key);
-                        targets.add(managementContext.getLocationRegistry().resolve((String)key, (Map<?,?>)flagsS));
-                    }
-                }
-            } else throw new IllegalArgumentException("targets must be supplied to MultiLocation, either as string spec or list of single-entry maps each being a location spec");
-            
-            MultiLocation result = managementContext.getLocationManager().createLocation(LocationSpec.create(MultiLocation.class)
-                    .configure(flags)
-                    .configure("subLocations", targets)
-                    .configure(LocationConfigUtils.finalAndOriginalSpecs(spec, locationFlags, globalProperties, namedLocation)));
-
-            // TODO Important workaround for BasicLocationRegistry.resolveForPeeking.
-            // That creates a location (from the resolver) and immediately unmanages it.
-            // The unmanage *must* remove all the targets created here; otherwise we have a leak.
-            // Adding the targets as children achieves this.
-            for (Location target : targets) {
-                target.setParent(result);
-            }
-            return result;
-
-        } catch (Exception e) {
-            // Must clean up after ourselves: don't leak sub-locations on error
-            if (LOG.isDebugEnabled()) LOG.debug("Problem resolving MultiLocation; cleaning up any sub-locations and rethrowing: "+e);
-            for (Location target : targets) {
-                Locations.unmanage(target);
-            }
-            throw Exceptions.propagate(e);
-        }
-    }
-
-    @Override
-    public String getPrefix() {
-        return MULTI;
-    }
-
-    @Override
-    public boolean accepts(String spec, LocationRegistry registry) {
-        return BasicLocationRegistry.isResolverPrefixForSpec(this, spec, true);
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/NamedLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/NamedLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/basic/NamedLocationResolver.java
deleted file mode 100644
index 9855cd1..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/NamedLocationResolver.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.Map;
-import java.util.NoSuchElementException;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationDefinition;
-import org.apache.brooklyn.api.location.LocationRegistry;
-import org.apache.brooklyn.api.location.LocationResolver;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.text.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Allows you to say, in your brooklyn.properties:
- * 
- * brooklyn.location.named.foo=localhost
- * brooklyn.location.named.foo.user=bob
- * brooklyn.location.named.foo.privateKeyFile=~/.ssh/custom-key-for-bob
- * brooklyn.location.named.foo.privateKeyPassphrase=WithAPassphrase
- * <p>
- * or
- * <p>
- * brooklyn.location.named.bob-aws-east=jclouds:aws-ec2:us-east-1
- * brooklyn.location.named.bob-aws-east.identity=BobId
- * brooklyn.location.named.bob-aws-east.credential=BobCred
- * <p>
- * then you can simply refer to:   foo   or   named:foo   (or bob-aws-east or named:bob-aws-east)   in any location spec
- */
-public class NamedLocationResolver implements LocationResolver {
-
-    public static final Logger log = LoggerFactory.getLogger(NamedLocationResolver.class);
-
-    public static final String NAMED = "named";
-    
-    @SuppressWarnings("unused")
-    private ManagementContext managementContext;
-
-    @Override
-    public void init(ManagementContext managementContext) {
-        this.managementContext = checkNotNull(managementContext, "managementContext");
-    }
-    
-    @Override
-    @SuppressWarnings({ "rawtypes" })
-    public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
-        String name = spec;
-        ConfigBag lfBag = ConfigBag.newInstance(locationFlags).putIfAbsent(LocationInternal.ORIGINAL_SPEC, name);
-        name = Strings.removeFromStart(spec, getPrefix()+":");
-        if (name.toLowerCase().startsWith(NAMED+":")) {
-            // since 0.7.0
-            log.warn("Deprecated use of 'named:' prefix with wrong case ("+spec+"); support may be removed in future versions");
-            name = spec.substring( (NAMED+":").length() );
-        }
-        
-        LocationDefinition ld = registry.getDefinedLocationByName(name);
-        if (ld==null) throw new NoSuchElementException("No named location defined matching '"+name+"'");
-        return ((BasicLocationRegistry)registry).resolveLocationDefinition(ld, lfBag.getAllConfig(), name);
-    }
-
-    @Override
-    public String getPrefix() {
-        return NAMED;
-    }
-    
-    /** accepts anything starting  named:xxx  or  xxx where xxx is a defined location name */
-    @Override
-    public boolean accepts(String spec, LocationRegistry registry) {
-        if (BasicLocationRegistry.isResolverPrefixForSpec(this, spec, false)) return true;
-        if (registry.getDefinedLocationByName(spec)!=null) return true;
-        return false;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/PortRanges.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/PortRanges.java b/core/src/main/java/org/apache/brooklyn/location/basic/PortRanges.java
deleted file mode 100644
index 105cfd9..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/PortRanges.java
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static com.google.common.base.Preconditions.checkArgument;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.NoSuchElementException;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.apache.brooklyn.api.location.PortRange;
-import org.apache.brooklyn.util.core.flags.TypeCoercions;
-
-import com.google.common.base.Function;
-import com.google.common.base.Objects;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-
-public class PortRanges {
-
-    public static final int MAX_PORT = 65535;
-    public static final PortRange ANY_HIGH_PORT = new LinearPortRange(1024, MAX_PORT);
-    
-    public static class SinglePort implements PortRange, Serializable {
-        private static final long serialVersionUID = 7446781416534230401L;
-        
-        final int port;
-        private SinglePort(int port) { this.port = port; }
-        
-        @Override
-        public Iterator<Integer> iterator() {
-            return Collections.singletonList(port).iterator();
-        }
-        @Override
-        public boolean isEmpty() {
-            return false;
-        }
-        @Override
-        public boolean asBoolean() {
-            return true;
-        }
-        @Override
-        public String toString() {
-            return //getClass().getName()+"["+
-                    ""+port; //+"]";
-        }
-        public int hashCode() {
-            return Objects.hashCode(port);
-        }
-        @Override
-        public boolean equals(Object obj) {
-            return (obj instanceof SinglePort) && port == ((SinglePort)obj).port;
-        }
-    }
-
-    public static class LinearPortRange implements PortRange, Serializable {
-        private static final long serialVersionUID = -9165280509363743508L;
-        
-        final int start, end, delta;
-        private LinearPortRange(int start, int end, int delta) {
-            this.start = start;
-            this.end = end;
-            this.delta = delta;
-            checkArgument(start > 0 && start <= MAX_PORT, "start port %s out of range", start);
-            checkArgument(end > 0 && end <= MAX_PORT, "end port %s out of range", end);
-            checkArgument(delta > 0 ? start <= end : start >= end, "start and end out of order: %s to %s, delta %s", start, end, delta);
-            checkArgument(delta != 0, "delta must be non-zero");
-        }
-        public LinearPortRange(int start, int end) {
-            this(start, end, (start<=end?1:-1));
-        }
-        
-        @Override
-        public Iterator<Integer> iterator() {
-            return new Iterator<Integer>() {
-                int next = start;
-                boolean hasNext = true;
-                
-                @Override
-                public boolean hasNext() {
-                    return hasNext;
-                }
-
-                @Override
-                public Integer next() {
-                    if (!hasNext)
-                        throw new NoSuchElementException("Exhausted available ports");
-                    int result = next;
-                    next += delta;
-                    if ((delta>0 && next>end) || (delta<0 && next<end)) hasNext = false;
-                    return result;
-                }
-                
-                @Override
-                public void remove() {
-                    throw new UnsupportedOperationException();
-                }
-            };
-        }
-        
-        @Override
-        public boolean isEmpty() {
-            return false;
-        }
-        @Override
-        public boolean asBoolean() {
-            return true;
-        }
-        @Override
-        public String toString() {
-            return //getClass().getName()+"["+
-                    start+"-"+end; //+"]";
-        }
-        @Override
-        public int hashCode() {
-            return Objects.hashCode(start, end, delta);
-        }
-        @Override
-        public boolean equals(Object obj) {
-            if (!(obj instanceof LinearPortRange)) return false;
-            LinearPortRange o = (LinearPortRange) obj;
-            return start == o.start && end == o.end && delta == o.delta;
-        }
-    }
-    
-    public static class AggregatePortRange implements PortRange, Serializable {
-        private static final long serialVersionUID = 7332682500816739660L;
-        
-        final List<PortRange> ranges;
-        private AggregatePortRange(List<PortRange> ranges) {
-            this.ranges = ImmutableList.copyOf(ranges);
-        }
-        @Override
-        public Iterator<Integer> iterator() {
-            return Iterables.concat(ranges).iterator();
-        }
-        @Override
-        public boolean isEmpty() {
-            for (PortRange r: ranges)
-                if (!r.isEmpty()) return false;
-            return true;
-        }
-        @Override
-        public boolean asBoolean() {
-            return !isEmpty();
-        }
-        @Override
-        public String toString() {
-            String s = "";
-            for (PortRange r: ranges) {
-                if (s.length()>0) s+=",";
-                s += r;
-            }
-            return //getClass().getName()+"["+
-                s; //+"]";
-        }
-        public int hashCode() {
-            return Objects.hashCode(ranges);
-        }
-        @Override
-        public boolean equals(Object obj) {
-            return (obj instanceof AggregatePortRange) && ranges.equals(((AggregatePortRange)obj).ranges);
-        }
-    }
-
-    public static PortRange fromInteger(int x) {
-        return new SinglePort(x);
-    }
-    
-    public static PortRange fromCollection(Collection<?> c) {
-        List<PortRange> l = new ArrayList<PortRange>();
-        for (Object o: c) {
-            if (o instanceof Integer) l.add(fromInteger((Integer)o));
-            else if (o instanceof String) l.add(fromString((String)o));
-            else if (o instanceof Collection) l.add(fromCollection((Collection<?>)o));
-            else l.add(TypeCoercions.coerce(o, PortRange.class));
-        }
-        return new AggregatePortRange(l);
-    }
-
-    /** parses a string representation of ports, as "80,8080,8000,8080-8099" */
-    public static PortRange fromString(String s) {
-        List<PortRange> l = new ArrayList<PortRange>();
-        for (String si: s.split(",")) {
-            si = si.trim();
-            int start, end;
-            if (si.endsWith("+")) {
-                String si2 = si.substring(0, si.length()-1).trim();
-                start = Integer.parseInt(si2);
-                end = MAX_PORT;
-            } else if (si.indexOf('-')>0) {
-                int v = si.indexOf('-');
-                start = Integer.parseInt(si.substring(0, v).trim());
-                end = Integer.parseInt(si.substring(v+1).trim());
-            } else if (si.length()==0) {
-                //nothing, ie empty range, just continue
-                continue;
-            } else {
-                //should be number on its own
-                l.add(new SinglePort(Integer.parseInt(si)));
-                continue;
-            }
-            l.add(new LinearPortRange(start, end));
-        }
-        if (l.size() == 1) {
-            return l.get(0);
-        } else {
-            return new AggregatePortRange(l);
-        }
-    }
-
-    private static AtomicBoolean initialized = new AtomicBoolean(false); 
-    /** performs the language extensions required for this project */
-    @SuppressWarnings("rawtypes")
-    public static void init() {
-        if (initialized.get()) return;
-        synchronized (initialized) {
-            if (initialized.get()) return;
-            TypeCoercions.registerAdapter(Integer.class, PortRange.class, new Function<Integer,PortRange>() {
-                public PortRange apply(Integer x) { return fromInteger(x); }
-            });
-            TypeCoercions.registerAdapter(String.class, PortRange.class, new Function<String,PortRange>() {
-                public PortRange apply(String x) { return fromString(x); }
-            });
-            TypeCoercions.registerAdapter(Collection.class, PortRange.class, new Function<Collection,PortRange>() {
-                public PortRange apply(Collection x) { return fromCollection(x); }
-            });
-            initialized.set(true);
-        }
-    }
-    
-    static {
-        init();
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/RegistryLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/RegistryLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/basic/RegistryLocationResolver.java
deleted file mode 100644
index a6b82ee..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/RegistryLocationResolver.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationRegistry;
-import org.apache.brooklyn.api.location.LocationResolver;
-
-/**
- * Extension to LocationResolver which can take a registry.
- * 
- * @deprecated since 0.6; the LocationResolver always takes the LocationRegistry now
- */
-@Deprecated
-public interface RegistryLocationResolver extends LocationResolver {
-
-    @Override
-    @SuppressWarnings("rawtypes")
-    Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry);
-
-    @Override
-    boolean accepts(String spec, LocationRegistry registry);
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/SingleMachineLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/SingleMachineLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/basic/SingleMachineLocationResolver.java
deleted file mode 100644
index 4099578..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/SingleMachineLocationResolver.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationRegistry;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.guava.Maybe.Absent;
-
-public class SingleMachineLocationResolver extends AbstractLocationResolver {
-    
-    private static final String SINGLE = "single";
-    
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    @Override
-    public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
-        ConfigBag config = extractConfig(locationFlags, spec, registry);
-        Map globalProperties = registry.getProperties();
-        String namedLocation = (String) locationFlags.get(LocationInternal.NAMED_SPEC_NAME.getName());
-        
-        if (registry != null) {
-            LocationPropertiesFromBrooklynProperties.setLocalTempDir(globalProperties, config);
-        }
-
-        if (config.getStringKey("target") == null) {
-            throw new IllegalArgumentException("target must be specified in single-machine spec");
-        }
-        String target = config.getStringKey("target").toString();
-        config.remove("target");
-        Maybe<Location> testResolve = managementContext.getLocationRegistry().resolve(target, false, null);
-        if (!testResolve.isPresent()) {
-            throw new IllegalArgumentException("Invalid target location '" + target + "' for location '"+SINGLE+"': "+
-                Exceptions.collapseText( ((Absent<?>)testResolve).getException() ));
-        }
-        
-        return managementContext.getLocationManager().createLocation(LocationSpec.create(SingleMachineProvisioningLocation.class)
-                .configure("location", target)
-                .configure("locationFlags", config.getAllConfig())
-                .configure(LocationConfigUtils.finalAndOriginalSpecs(spec, locationFlags, globalProperties, namedLocation)));
-    }
-    
-    @Override
-    public String getPrefix() {
-        return SINGLE;
-    }
-    
-    @Override
-    protected Class<? extends Location> getLocationType() {
-        return SingleMachineProvisioningLocation.class;
-    }
-
-    @Override
-    protected SpecParser getSpecParser() {
-        return new SpecParser(getPrefix()).setExampleUsage("\"single(target=jclouds:aws-ec2:us-east-1)\"");
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/SingleMachineProvisioningLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/SingleMachineProvisioningLocation.java b/core/src/main/java/org/apache/brooklyn/location/basic/SingleMachineProvisioningLocation.java
deleted file mode 100644
index 9cc98c7..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/SingleMachineProvisioningLocation.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.ImmutableMap;
-
-public class SingleMachineProvisioningLocation<T extends MachineLocation> extends FixedListMachineProvisioningLocation<T> {
-    private static final long serialVersionUID = -4216528515792151062L;
-
-    private static final Logger log = LoggerFactory.getLogger(SingleMachineProvisioningLocation.class);
-    
-    @SetFromFlag(nullable=false)
-    private String location;
-    
-    @SetFromFlag(nullable=false)
-    private Map<?,?> locationFlags;
-    
-    private T singleLocation;
-    private int referenceCount;
-    private MachineProvisioningLocation<T> provisioningLocation;
-
-
-    public SingleMachineProvisioningLocation() {
-    }
-
-    @SuppressWarnings("rawtypes")
-    public SingleMachineProvisioningLocation(String location, Map locationFlags) {
-        this.locationFlags = locationFlags;
-        this.location = location;
-    }
-
-    @SuppressWarnings("rawtypes")
-    @Override
-    public synchronized T obtain(Map flags) throws NoMachinesAvailableException {
-        log.info("Flags {} passed to newLocationFromString will be ignored, using {}", flags, locationFlags);
-        return obtain();
-    }
-
-    @Override
-    @SuppressWarnings({ "unchecked", "rawtypes" })
-    public synchronized T obtain() throws NoMachinesAvailableException {
-        if (singleLocation == null) {
-            if (provisioningLocation == null) {
-                provisioningLocation = (MachineProvisioningLocation) getManagementContext().getLocationRegistry().resolve(
-                    location, locationFlags);
-            }
-            singleLocation = provisioningLocation.obtain(ImmutableMap.of());
-            inUse.add(singleLocation);
-        }
-        referenceCount++;
-        return singleLocation;
-    }
-
-    @Override
-    public synchronized void release(T machine) {
-        if (!machine.equals(singleLocation)) {
-            throw new IllegalArgumentException("Invalid machine " + machine + " passed to release, expecting: " + singleLocation);
-        }
-        if (--referenceCount == 0) {
-            provisioningLocation.release(machine);
-            singleLocation = null;
-        }
-        inUse.remove(machine);
-    };
-
-}


[23/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineAttributes.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineAttributes.java b/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineAttributes.java
new file mode 100644
index 0000000..a9c2d22
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineAttributes.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.machine;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.core.config.render.RendererHints;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.util.guava.Functionals;
+import org.apache.brooklyn.util.math.MathFunctions;
+import org.apache.brooklyn.util.text.ByteSizeStrings;
+import org.apache.brooklyn.util.time.Duration;
+
+import com.google.common.base.Function;
+
+public class MachineAttributes {
+
+    /**
+     * Do not instantiate.
+     */
+    private MachineAttributes() {}
+
+    /*
+     * Sensor attributes for machines.
+     */
+
+    public static final AttributeSensor<Duration> UPTIME = Sensors.newSensor(Duration.class, "machine.uptime", "Current uptime");
+    public static final AttributeSensor<Double> LOAD_AVERAGE = Sensors.newDoubleSensor("machine.loadAverage", "Current load average");
+
+    public static final AttributeSensor<Double> CPU_USAGE = Sensors.newDoubleSensor("machine.cpu", "Current CPU usage");
+    public static final AttributeSensor<Double> AVERAGE_CPU_USAGE = Sensors.newDoubleSensor("cpu.average", "Average CPU usage across the cluster");
+
+    public static final AttributeSensor<Long> FREE_MEMORY = Sensors.newLongSensor("machine.memory.free", "Current free memory");
+    public static final AttributeSensor<Long> TOTAL_MEMORY = Sensors.newLongSensor("machine.memory.total", "Total memory");
+    public static final AttributeSensor<Long> USED_MEMORY = Sensors.newLongSensor("machine.memory.used", "Current memory usage");
+    public static final AttributeSensor<Double> USED_MEMORY_DELTA_PER_SECOND_LAST = Sensors.newDoubleSensor("memory.used.delta", "Change in memory usage per second");
+    public static final AttributeSensor<Double> USED_MEMORY_DELTA_PER_SECOND_IN_WINDOW = Sensors.newDoubleSensor("memory.used.windowed", "Average change in memory usage over 30s");
+
+    private static AtomicBoolean initialized = new AtomicBoolean(false);
+
+    /**
+     * Setup renderer hints.
+     */
+    public static void init() {
+        if (initialized.getAndSet(true)) return;
+
+        final Function<Double, Long> longValue = new Function<Double, Long>() {
+            @Override
+            public Long apply(@Nullable Double input) {
+                if (input == null) return null;
+                return input.longValue();
+            }
+        };
+
+        RendererHints.register(CPU_USAGE, RendererHints.displayValue(MathFunctions.percent(2)));
+        RendererHints.register(AVERAGE_CPU_USAGE, RendererHints.displayValue(MathFunctions.percent(2)));
+
+        RendererHints.register(FREE_MEMORY, RendererHints.displayValue(Functionals.chain(MathFunctions.times(1000L), ByteSizeStrings.metric())));
+        RendererHints.register(TOTAL_MEMORY, RendererHints.displayValue(Functionals.chain(MathFunctions.times(1000L), ByteSizeStrings.metric())));
+        RendererHints.register(USED_MEMORY, RendererHints.displayValue(Functionals.chain(MathFunctions.times(1000L), ByteSizeStrings.metric())));
+        RendererHints.register(USED_MEMORY_DELTA_PER_SECOND_LAST, RendererHints.displayValue(Functionals.chain(longValue, ByteSizeStrings.metric())));
+        RendererHints.register(USED_MEMORY_DELTA_PER_SECOND_IN_WINDOW, RendererHints.displayValue(Functionals.chain(longValue, ByteSizeStrings.metric())));
+    }
+
+    static {
+        init();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineEntity.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineEntity.java b/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineEntity.java
new file mode 100644
index 0000000..e24222a
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineEntity.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.machine;
+
+import org.apache.brooklyn.api.catalog.Catalog;
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.effector.core.MethodEffector;
+import org.apache.brooklyn.entity.annotation.Effector;
+import org.apache.brooklyn.entity.annotation.EffectorParam;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
+import org.apache.brooklyn.util.time.Duration;
+
+@Catalog(name="Machine Entity", description="Represents a machine, providing metrics about it (e.g. obtained from ssh)")
+@ImplementedBy(MachineEntityImpl.class)
+public interface MachineEntity extends EmptySoftwareProcess {
+
+    AttributeSensor<Duration> UPTIME = MachineAttributes.UPTIME;
+    AttributeSensor<Double> LOAD_AVERAGE = MachineAttributes.LOAD_AVERAGE;
+    AttributeSensor<Double> CPU_USAGE = MachineAttributes.CPU_USAGE;
+    AttributeSensor<Long> FREE_MEMORY = MachineAttributes.FREE_MEMORY;
+    AttributeSensor<Long> TOTAL_MEMORY = MachineAttributes.TOTAL_MEMORY;
+    AttributeSensor<Long> USED_MEMORY = MachineAttributes.USED_MEMORY;
+
+    MethodEffector<String> EXEC_COMMAND = new MethodEffector<String>(MachineEntity.class, "execCommand");
+    MethodEffector<String> EXEC_COMMAND_TIMEOUT = new MethodEffector<String>(MachineEntity.class, "execCommandTimeout");
+
+    /**
+     * Execute a command and return the output.
+     */
+    @Effector(description = "Execute a command and return the output")
+    String execCommand(
+            @EffectorParam(name = "command", description = "Command") String command);
+
+    /**
+     * Execute a command and return the output, or throw an exception after a timeout.
+     */
+    @Effector(description = "Execute a command and return the output")
+    String execCommandTimeout(
+            @EffectorParam(name = "command", description = "Command") String command,
+            @EffectorParam(name = "timeout", description = "Timeout") Duration timeout);
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineEntityImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineEntityImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineEntityImpl.java
new file mode 100644
index 0000000..d656102
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineEntityImpl.java
@@ -0,0 +1,182 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.machine;
+
+import java.util.List;
+import java.util.concurrent.TimeoutException;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcessImpl;
+import org.apache.brooklyn.location.basic.Machines;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.sensor.feed.ssh.SshFeed;
+import org.apache.brooklyn.sensor.feed.ssh.SshPollConfig;
+import org.apache.brooklyn.sensor.feed.ssh.SshPollValue;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.time.Duration;
+
+import com.google.common.base.Function;
+import com.google.common.base.Functions;
+import com.google.common.base.Splitter;
+
+public class MachineEntityImpl extends EmptySoftwareProcessImpl implements MachineEntity {
+
+    private static final Logger LOG = LoggerFactory.getLogger(MachineEntityImpl.class);
+
+    static {
+        MachineAttributes.init();
+    }
+
+    private transient SshFeed sensorFeed;
+
+    @Override
+    public void init() {
+        LOG.info("Starting server pool machine with id {}", getId());
+        super.init();
+    }
+
+    @Override
+    protected void connectSensors() {
+        super.connectSensors();
+
+        // Sensors linux-specific
+        if (!getMachine().getMachineDetails().getOsDetails().isLinux()) return;
+
+        sensorFeed = SshFeed.builder()
+                .entity(this)
+                .period(Duration.THIRTY_SECONDS)
+                .poll(new SshPollConfig<Duration>(UPTIME)
+                        .command("cat /proc/uptime")
+                        .onFailureOrException(Functions.<Duration>constant(null))
+                        .onSuccess(new Function<SshPollValue, Duration>() {
+                            @Override
+                            public Duration apply(SshPollValue input) {
+                                return Duration.seconds( Double.valueOf( Strings.getFirstWord(input.getStdout()) ) );
+                            }
+                        }))
+                .poll(new SshPollConfig<Double>(LOAD_AVERAGE)
+                        .command("uptime")
+                        .onFailureOrException(Functions.constant(-1d))
+                        .onSuccess(new Function<SshPollValue, Double>() {
+                            @Override
+                            public Double apply(SshPollValue input) {
+                                String loadAverage = Strings.getFirstWordAfter(input.getStdout(), "load average:").replace(",", "");
+                                return Double.valueOf(loadAverage);
+                            }
+                        }))
+                .poll(new SshPollConfig<Double>(CPU_USAGE)
+                        .command("cat /proc/stat")
+                        .onFailureOrException(Functions.constant(-1d))
+                        .onSuccess(new Function<SshPollValue, Double>() {
+                            @Override
+                            public Double apply(SshPollValue input) {
+                                List<String> cpuData = Splitter.on(" ").omitEmptyStrings().splitToList(Strings.getFirstLine(input.getStdout()));
+                                Integer system = Integer.parseInt(cpuData.get(1));
+                                Integer user = Integer.parseInt(cpuData.get(3));
+                                Integer idle = Integer.parseInt(cpuData.get(4));
+                                return (double) (system + user) / (double) (system + user + idle);
+                            }
+                        }))
+                .poll(new SshPollConfig<Long>(USED_MEMORY)
+                        .command("free | grep Mem:")
+                        .onFailureOrException(Functions.constant(-1L))
+                        .onSuccess(new Function<SshPollValue, Long>() {
+                            @Override
+                            public Long apply(SshPollValue input) {
+                                List<String> memoryData = Splitter.on(" ").omitEmptyStrings().splitToList(Strings.getFirstLine(input.getStdout()));
+                                return Long.parseLong(memoryData.get(2));
+                            }
+                        }))
+                .poll(new SshPollConfig<Long>(FREE_MEMORY)
+                        .command("free | grep Mem:")
+                        .onFailureOrException(Functions.constant(-1L))
+                        .onSuccess(new Function<SshPollValue, Long>() {
+                            @Override
+                            public Long apply(SshPollValue input) {
+                                List<String> memoryData = Splitter.on(" ").omitEmptyStrings().splitToList(Strings.getFirstLine(input.getStdout()));
+                                return Long.parseLong(memoryData.get(3));
+                            }
+                        }))
+                .poll(new SshPollConfig<Long>(TOTAL_MEMORY)
+                        .command("free | grep Mem:")
+                        .onFailureOrException(Functions.constant(-1L))
+                        .onSuccess(new Function<SshPollValue, Long>() {
+                            @Override
+                            public Long apply(SshPollValue input) {
+                                List<String> memoryData = Splitter.on(" ").omitEmptyStrings().splitToList(Strings.getFirstLine(input.getStdout()));
+                                return Long.parseLong(memoryData.get(1));
+                            }
+                        }))
+                .build();
+
+    }
+
+    @Override
+    public void disconnectSensors() {
+        if (sensorFeed != null) sensorFeed.stop();
+        super.disconnectSensors();
+    }
+
+    @Override
+    public Class<?> getDriverInterface() {
+        return EmptySoftwareProcessDriver.class;
+    }
+
+    public SshMachineLocation getMachine() {
+        return Machines.findUniqueSshMachineLocation(getLocations()).get();
+    }
+
+    @Override
+    public String execCommand(String command) {
+        return execCommandTimeout(command, Duration.ONE_MINUTE);
+    }
+
+    @Override
+    public String execCommandTimeout(String command, Duration timeout) {
+        ProcessTaskWrapper<String> task = SshEffectorTasks.ssh(command)
+                .environmentVariables(((AbstractSoftwareProcessSshDriver) getDriver()).getShellEnvironment())
+                .requiringZeroAndReturningStdout()
+                .machine(getMachine())
+                .summary(command)
+                .newTask();
+
+        try {
+            String result = DynamicTasks.queueIfPossible(task)
+                    .executionContext(this)
+                    .orSubmitAsync()
+                    .asTask()
+                    .get(timeout);
+            return result;
+        } catch (TimeoutException te) {
+            throw new IllegalStateException("Timed out running command: " + command);
+        } catch (Exception e) {
+            Integer exitCode = task.getExitCode();
+            LOG.warn("Command failed, return code {}: {}", exitCode == null ? -1 : exitCode, task.getStderr());
+            throw Exceptions.propagate(e);
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineInitTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineInitTasks.java b/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineInitTasks.java
new file mode 100644
index 0000000..91b0411
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/machine/MachineInitTasks.java
@@ -0,0 +1,172 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.machine;
+
+import java.util.List;
+import java.util.concurrent.Callable;
+
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.annotations.Beta;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.core.task.ssh.SshTasks;
+import org.apache.brooklyn.util.net.Protocol;
+import org.apache.brooklyn.util.ssh.BashCommands;
+import org.apache.brooklyn.util.ssh.IptablesCommands;
+import org.apache.brooklyn.util.ssh.IptablesCommands.Chain;
+import org.apache.brooklyn.util.ssh.IptablesCommands.Policy;
+import org.apache.brooklyn.util.text.Strings;
+
+/**
+ * 
+ */
+@Beta
+public class MachineInitTasks {
+
+    // TODO Move somewhere so code can also be called by JcloudsLocation!
+    
+    private static final Logger log = LoggerFactory.getLogger(MachineInitTasks.class);
+
+    protected EntityInternal entity() {
+        return (EntityInternal) BrooklynTaskTags.getTargetOrContextEntity(Tasks.current());
+    }
+
+    /**
+     * Returns a queued {@link Task} which opens the given ports in iptables on the given machine.
+     */
+    public Task<Void> openIptablesAsync(final Iterable<Integer> inboundPorts, final SshMachineLocation machine) {
+        return DynamicTasks.queue("open iptables "+toTruncatedString(inboundPorts, 6), new Callable<Void>() {
+            public Void call() {
+                openIptablesImpl(inboundPorts, machine);
+                return null;
+            }
+        });
+    }
+
+    /**
+     * Returns a queued {@link Task} which stops iptables on the given machine.
+     */
+    public Task<Void> stopIptablesAsync(final SshMachineLocation machine) {
+        return DynamicTasks.queue("stop iptables", new Callable<Void>() {
+            public Void call() {
+                stopIptablesImpl(machine);
+                return null;
+            }
+        });
+    }
+
+    /**
+     * See docs in {@link BashCommands#dontRequireTtyForSudo()}
+     */
+    public Task<Boolean> dontRequireTtyForSudoAsync(final SshMachineLocation machine) {
+        return DynamicTasks.queue(SshTasks.dontRequireTtyForSudo(machine, true).newTask().asTask());
+    }
+
+    protected void openIptablesImpl(Iterable<Integer> inboundPorts, SshMachineLocation machine) {
+        if (inboundPorts == null || Iterables.isEmpty(inboundPorts)) {
+            log.info("No ports to open in iptables (no inbound ports) for {} at {}", machine, this);
+        } else {
+            log.info("Opening ports in iptables for {} at {}", entity(), machine);
+
+            List<String> iptablesRules = Lists.newArrayList();
+
+            if (isLocationFirewalldEnabled(machine)) {
+                for (Integer port : inboundPorts) {
+                    iptablesRules.add(IptablesCommands.addFirewalldRule(Chain.INPUT, Protocol.TCP, port, Policy.ACCEPT));
+                 }
+            } else {
+                iptablesRules = createIptablesRulesForNetworkInterface(inboundPorts);
+                iptablesRules.add(IptablesCommands.saveIptablesRules());
+            }
+            List<String> batch = Lists.newArrayList();
+            // Some entities, such as Riak (erlang based) have a huge range of ports, which leads to a script that
+            // is too large to run (fails with a broken pipe). Batch the rules into batches of 50
+            for (String rule : iptablesRules) {
+                batch.add(rule);
+                if (batch.size() == 50) {
+                    machine.execCommands("Inserting iptables rules, 50 command batch", batch);
+                    batch.clear();
+                }
+            }
+            if (batch.size() > 0) {
+                machine.execCommands("Inserting iptables rules", batch);
+            }
+            machine.execCommands("List iptables rules", ImmutableList.of(IptablesCommands.listIptablesRule()));
+        }
+    }
+
+    protected void stopIptablesImpl(SshMachineLocation machine) {
+        log.info("Stopping iptables for {} at {}", entity(), machine);
+
+        List<String> cmds = ImmutableList.<String>of();
+        if (isLocationFirewalldEnabled(machine)) {
+            cmds = ImmutableList.of(IptablesCommands.firewalldServiceStop(), IptablesCommands.firewalldServiceStatus());
+        } else {
+            cmds = ImmutableList.of(IptablesCommands.iptablesServiceStop(), IptablesCommands.iptablesServiceStatus());
+        }
+        machine.execCommands("Stopping iptables", cmds);
+    }
+    
+    private List<String> createIptablesRulesForNetworkInterface(Iterable<Integer> ports) {
+        List<String> iptablesRules = Lists.newArrayList();
+        for (Integer port : ports) {
+           iptablesRules.add(IptablesCommands.insertIptablesRule(Chain.INPUT, Protocol.TCP, port, Policy.ACCEPT));
+        }
+        return iptablesRules;
+     }
+
+    public boolean isLocationFirewalldEnabled(SshMachineLocation location) {
+        int result = location.execCommands("checking if firewalld is active", 
+                ImmutableList.of(IptablesCommands.firewalldServiceIsActive()));
+        if (result == 0) {
+            return true;
+        }
+        
+        return false;
+    }
+    
+    protected String toTruncatedString(Iterable<?> vals, int maxShown) {
+        StringBuilder result = new StringBuilder("[");
+        int shown = 0;
+        for (Object val : (vals == null ? ImmutableList.of() : vals)) {
+            if (shown != 0) {
+                result.append(", ");
+            }
+            if (shown < maxShown) {
+                result.append(Strings.toString(val));
+                shown++;
+            } else {
+                result.append("...");
+                break;
+            }
+        }
+        result.append("]");
+        return result.toString();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/machine/ProvidesProvisioningFlags.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/machine/ProvidesProvisioningFlags.java b/software/base/src/main/java/org/apache/brooklyn/entity/machine/ProvidesProvisioningFlags.java
new file mode 100644
index 0000000..cad449a
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/machine/ProvidesProvisioningFlags.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.machine;
+
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.entity.software.base.lifecycle.MachineLifecycleEffectorTasks;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+
+import com.google.common.annotations.Beta;
+
+/** Marker interface for an entity which supplies custom machine provisioning flags;
+ * used e.g. in {@link MachineLifecycleEffectorTasks}.
+ * @since 0.6.0 */
+@Beta
+public interface ProvidesProvisioningFlags {
+
+    public ConfigBag obtainProvisioningFlags(MachineProvisioningLocation<?> location);
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPool.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPool.java b/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPool.java
new file mode 100644
index 0000000..548242f
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPool.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.machine.pool;
+
+import java.util.Collection;
+import java.util.Map;
+
+import com.google.common.annotations.Beta;
+
+import org.apache.brooklyn.api.catalog.Catalog;
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.effector.core.MethodEffector;
+import org.apache.brooklyn.entity.annotation.Effector;
+import org.apache.brooklyn.entity.annotation.EffectorParam;
+import org.apache.brooklyn.entity.group.DynamicCluster;
+import org.apache.brooklyn.entity.machine.MachineEntity;
+import org.apache.brooklyn.location.cloud.CloudLocationConfig;
+import org.apache.brooklyn.location.dynamic.LocationOwner;
+import org.apache.brooklyn.sensor.core.Sensors;
+
+/**
+ * A preallocated server pool is an entity that other applications can deploy to.
+ * Behaving as a cluster, the machines it creates for its members are reused.
+ * <p/>
+ * Notes:
+ * <ul>
+ *     <li>
+ *         The pool does not configure ports appropriately for applications subsequently
+ *         deployed. If an entity that is to be run in the pool requires any ports open
+ *         other than port 22 then thoses port should be configured with the
+ *         {@link CloudLocationConfig#INBOUND_PORTS INBOUND_PORTS}
+ *         config key as part of the pool's
+ *         {@link org.apache.brooklyn.entity.software.base.SoftwareProcess#PROVISIONING_PROPERTIES PROVISIONING_PROPERTIES}.
+ *         For example, in YAML:
+ *         <pre>
+ *     - type: brooklyn.entity.pool.ServerPool
+ *       brooklyn.config:
+ *         # Suitable for TomcatServers
+ *         provisioning.properties:
+ *         inboundPorts: [22, 31880, 8443, 8080, 31001, 1099]
+ *         </pre>
+ *         This is a limitation of Brooklyn that will be addressed in a future release.
+ *     </li>
+ * </ul>
+ */
+@Catalog(name="Server Pool", description="Creates a pre-allocated server pool, which other applications can deploy to")
+@ImplementedBy(ServerPoolImpl.class)
+@Beta
+public interface ServerPool extends DynamicCluster, LocationOwner<ServerPoolLocation, ServerPool> {
+
+    ConfigKey<Integer> INITIAL_SIZE = ConfigKeys.newConfigKeyWithDefault(DynamicCluster.INITIAL_SIZE, 2);
+
+    AttributeSensor<Integer> AVAILABLE_COUNT = Sensors.newIntegerSensor(
+            "pool.available", "The number of locations in the pool that are unused");
+
+    AttributeSensor<Integer> CLAIMED_COUNT = Sensors.newIntegerSensor(
+            "pool.claimed", "The number of locations in the pool that are in use");
+
+    ConfigKey<EntitySpec<?>> MEMBER_SPEC = ConfigKeys.newConfigKeyWithDefault(DynamicCluster.MEMBER_SPEC,
+            EntitySpec.create(MachineEntity.class));
+
+    MethodEffector<Collection<Entity>> ADD_MACHINES_FROM_SPEC = new MethodEffector<Collection<Entity>>(ServerPool.class, "addExistingMachinesFromSpec");
+
+    public MachineLocation claimMachine(Map<?, ?> flags) throws NoMachinesAvailableException;
+
+    public void releaseMachine(MachineLocation machine);
+
+    /**
+     * Sets the pool to use an existing {@link MachineLocation} as a member. Existing locations
+     * will count towards the capacity of the pool but will not be terminated when the pool is
+     * stopped.
+     * @param machine An existing machine.
+     * @return the new member of the pool, created with the configured {@link #MEMBER_SPEC}.
+     */
+    public Entity addExistingMachine(MachineLocation machine);
+
+    /**
+     * Adds additional machines to the pool by resolving the given spec.
+     * @param spec
+     *          A location spec, e.g. <code>byon:(hosts="user@10.9.1.1,user@10.9.1.2,user@10.9.1.3")</code>
+     * @return the new members of the pool, created with the configured {@link #MEMBER_SPEC}.
+     */
+    @Effector(description = "Adds additional machines to the pool by resolving the given spec.")
+    public Collection<Entity> addExistingMachinesFromSpec(
+            @EffectorParam(name = "spec", description = "Spec") String spec);
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolImpl.java
new file mode 100644
index 0000000..d1d4bee
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolImpl.java
@@ -0,0 +1,432 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.machine.pool;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationDefinition;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.api.mgmt.LocationManager;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.api.policy.PolicySpec;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.apache.brooklyn.entity.group.AbstractMembershipTrackingPolicy;
+import org.apache.brooklyn.entity.group.DynamicClusterImpl;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.trait.Startable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.location.basic.BasicLocationDefinition;
+import org.apache.brooklyn.location.basic.Machines;
+import org.apache.brooklyn.location.dynamic.DynamicLocation;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.guava.Maybe;
+
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
+import com.google.common.base.Optional;
+import com.google.common.base.Predicate;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.reflect.TypeToken;
+
+public class ServerPoolImpl extends DynamicClusterImpl implements ServerPool {
+
+    private static final Logger LOG = LoggerFactory.getLogger(ServerPoolImpl.class);
+
+    private static enum MachinePoolMemberStatus {
+        /** The server is available for use */
+        AVAILABLE,
+        /** The server has been leased to another application */
+        CLAIMED,
+        /**
+         * The server will not be leased to other applications. It will be the first
+         * candidate to release when the pool is shrunk.
+         */
+        UNUSABLE
+    }
+
+    private static final AttributeSensor<MachinePoolMemberStatus> SERVER_STATUS = Sensors.newSensor(MachinePoolMemberStatus.class,
+            "pool.serverStatus", "The status of an entity in the pool");
+
+    // The sensors here would be better as private fields but there's not really a
+    // good way to manage their state when rebinding.
+
+    /** Accesses must be synchronised by mutex */
+    // Would use BiMap but persisting them tends to throw ConcurrentModificationExceptions.
+    @SuppressWarnings("serial")
+    public static final AttributeSensor<Map<Entity, MachineLocation>> ENTITY_MACHINE = Sensors.newSensor(new TypeToken<Map<Entity, MachineLocation>>() {},
+            "pool.entityMachineMap", "A mapping of entities and their machine locations");
+
+    @SuppressWarnings("serial")
+    public static final AttributeSensor<Map<MachineLocation, Entity>> MACHINE_ENTITY = Sensors.newSensor(new TypeToken<Map<MachineLocation, Entity>>() {},
+            "pool.machineEntityMap", "A mapping of machine locations and their entities");
+
+    public static final AttributeSensor<LocationDefinition> DYNAMIC_LOCATION_DEFINITION = Sensors.newSensor(LocationDefinition.class,
+            "pool.locationDefinition", "The location definition used to create the pool's dynamic location");
+
+    public static final ConfigKey<Boolean> REMOVABLE = ConfigKeys.newBooleanConfigKey(
+            "pool.member.removable", "Whether a pool member is removable from the cluster. Used to denote additional " +
+                    "existing machines that were manually added to the pool", true);
+
+    @SuppressWarnings("unused")
+    private MemberTrackingPolicy membershipTracker;
+
+    @Override
+    public void init() {
+        super.init();
+        setAttribute(AVAILABLE_COUNT, 0);
+        setAttribute(CLAIMED_COUNT, 0);
+        setAttribute(ENTITY_MACHINE, Maps.<Entity, MachineLocation>newHashMap());
+        setAttribute(MACHINE_ENTITY, Maps.<MachineLocation, Entity>newHashMap());
+    }
+
+    @Override
+    public void start(Collection<? extends Location> locations) {
+        // super.start must happen before the policy is added else the initial
+        // members wont be up (and thus have a MachineLocation) when onEntityAdded
+        // is called.
+        super.start(locations);
+        createLocation();
+        addMembershipTrackerPolicy();
+    }
+
+    @Override
+    public void rebind() {
+        super.rebind();
+        addMembershipTrackerPolicy();
+        createLocation();
+    }
+
+    @Override
+    public void stop() {
+        super.stop();
+        deleteLocation();
+        synchronized (mutex) {
+            setAttribute(AVAILABLE_COUNT, 0);
+            setAttribute(CLAIMED_COUNT, 0);
+            getAttribute(ENTITY_MACHINE).clear();
+            getAttribute(MACHINE_ENTITY).clear();
+        }
+    }
+
+    private void addMembershipTrackerPolicy() {
+        membershipTracker = addPolicy(PolicySpec.create(MemberTrackingPolicy.class)
+                .displayName(getDisplayName() + " membership tracker")
+                .configure("group", this));
+    }
+
+    @Override
+    public ServerPoolLocation getDynamicLocation() {
+        return (ServerPoolLocation) getAttribute(DYNAMIC_LOCATION);
+    }
+
+    protected ServerPoolLocation createLocation() {
+        return createLocation(MutableMap.<String, Object>builder()
+                .putAll(getConfig(LOCATION_FLAGS))
+                .put(DynamicLocation.OWNER.getName(), this)
+                .build());
+    }
+
+    @Override
+    public ServerPoolLocation createLocation(Map<String, ?> flags) {
+        String locationName = getConfig(LOCATION_NAME);
+        if (locationName == null) {
+            String prefix = getConfig(LOCATION_NAME_PREFIX);
+            String suffix = getConfig(LOCATION_NAME_SUFFIX);
+            locationName = Joiner.on("-").skipNulls().join(prefix, getId(), suffix);
+        }
+
+        String locationSpec = String.format(ServerPoolLocationResolver.POOL_SPEC, getId()) + String.format(":(name=\"%s\")", locationName);
+        LocationDefinition definition = new BasicLocationDefinition(locationName, locationSpec, flags);
+        getManagementContext().getLocationRegistry().updateDefinedLocation(definition);
+        Location location = getManagementContext().getLocationRegistry().resolve(definition);
+        LOG.info("Resolved and registered dynamic location {}: {}", locationName, location);
+
+        setAttribute(LOCATION_SPEC, locationSpec);
+        setAttribute(DYNAMIC_LOCATION, location);
+        setAttribute(LOCATION_NAME, location.getId());
+        setAttribute(DYNAMIC_LOCATION_DEFINITION, definition);
+
+        return (ServerPoolLocation) location;
+    }
+
+    @Override
+    public void deleteLocation() {
+        LocationManager mgr = getManagementContext().getLocationManager();
+        ServerPoolLocation location = getDynamicLocation();
+        if (mgr.isManaged(location)) {
+            LOG.debug("{} deleting and unmanaging location {}", this, location);
+            mgr.unmanage(location);
+        }
+        // definition will only be null if deleteLocation has already been called, e.g. by two calls to stop().
+        LocationDefinition definition = getAttribute(DYNAMIC_LOCATION_DEFINITION);
+        if (definition != null) {
+            LOG.debug("{} unregistering dynamic location {}", this, definition);
+            getManagementContext().getLocationRegistry().removeDefinedLocation(definition.getId());
+        }
+        setAttribute(LOCATION_SPEC, null);
+        setAttribute(DYNAMIC_LOCATION, null);
+        setAttribute(LOCATION_NAME, null);
+        setAttribute(DYNAMIC_LOCATION_DEFINITION, null);
+    }
+
+    @Override
+    public boolean isLocationAvailable() {
+        // FIXME: What do true/false mean to callers?
+        // Is it valid to return false if availableMachines is empty?
+        return getDynamicLocation() != null;
+    }
+
+    @Override
+    public MachineLocation claimMachine(Map<?, ?> flags) throws NoMachinesAvailableException {
+        LOG.info("Obtaining machine with flags: {}", Joiner.on(", ").withKeyValueSeparator("=").join(flags));
+        synchronized (mutex) {
+            Optional<Entity> claimed = getMemberWithStatus(MachinePoolMemberStatus.AVAILABLE);
+            if (claimed.isPresent()) {
+                setEntityStatus(claimed.get(), MachinePoolMemberStatus.CLAIMED);
+                updateCountSensors();
+                LOG.debug("{} has been claimed in {}", claimed, this);
+                return getEntityMachineMap().get(claimed.get());
+            } else {
+                throw new NoMachinesAvailableException("No machines available in " + this);
+            }
+        }
+    }
+
+    @Override
+    public void releaseMachine(MachineLocation machine) {
+        synchronized (mutex) {
+            Entity entity = getMachineEntityMap().get(machine);
+            if (entity == null) {
+                LOG.warn("{} releasing machine {} but its owning entity is not known!", this, machine);
+            } else {
+                setEntityStatus(entity, MachinePoolMemberStatus.AVAILABLE);
+                updateCountSensors();
+                LOG.debug("{} has been released in {}", machine, this);
+            }
+        }
+    }
+
+    @Override
+    public Entity addExistingMachine(MachineLocation machine) {
+        LOG.info("Adding additional machine to {}: {}", this, machine);
+        Entity added = addNode(machine, MutableMap.of(REMOVABLE, false));
+        Map<String, ?> args = ImmutableMap.of("locations", ImmutableList.of(machine));
+        Task<Void> task = Effectors.invocation(added, Startable.START, args).asTask();
+        DynamicTasks.queueIfPossible(task).orSubmitAsync(this);
+        return added;
+    }
+
+    @Override
+    public Collection<Entity> addExistingMachinesFromSpec(String spec) {
+        Location location = getManagementContext().getLocationRegistry().resolve(spec, true, null).orNull();
+        List<Entity> additions = Lists.newLinkedList();
+        if (location == null) {
+            LOG.warn("Spec was unresolvable: {}", spec);
+        } else {
+            Iterable<MachineLocation> machines = FluentIterable.from(location.getChildren())
+                    .filter(MachineLocation.class);
+            LOG.info("{} adding additional machines: {}", this, machines);
+            // Doesn't need to be synchronised on mutex: it will be claimed per-machine
+            // as the new members are handled by the membership tracking policy.
+            for (MachineLocation machine : machines) {
+                additions.add(addExistingMachine(machine));
+            }
+            LOG.debug("{} added additional machines", this);
+        }
+        return additions;
+    }
+
+    /**
+     * Overrides to restrict delta to the number of machines that can be <em>safely</em>
+     * removed (i.e. those that are {@link MachinePoolMemberStatus#UNUSABLE unusable} or
+     * {@link MachinePoolMemberStatus#AVAILABLE available}).
+     * <p/>
+     * Does not modify delta if the pool is stopping.
+     * @param delta Requested number of members to remove
+     * @return The entities that were removed
+     */
+    @Override
+    protected Collection<Entity> shrink(int delta) {
+        if (Lifecycle.STOPPING.equals(getAttribute(Attributes.SERVICE_STATE_ACTUAL))) {
+            return super.shrink(delta);
+        }
+
+        synchronized (mutex) {
+            int removable = 0;
+            for (Entity entity : getMembers()) {
+                // Skip machine marked not for removal and machines that are claimed
+                if (!Boolean.FALSE.equals(entity.getConfig(REMOVABLE)) &&
+                        !MachinePoolMemberStatus.CLAIMED.equals(entity.getAttribute(SERVER_STATUS))) {
+                    removable -= 1;
+                }
+            }
+
+            if (delta < removable) {
+                LOG.warn("Too few removable machines in {} to shrink by delta {}. Altered delta to {}",
+                        new Object[]{this, delta, removable});
+                delta = removable;
+            }
+
+            Collection<Entity> removed = super.shrink(delta);
+            updateCountSensors();
+            return removed;
+        }
+    }
+    
+    private Map<Entity, MachineLocation> getEntityMachineMap() {
+        return getAttribute(ENTITY_MACHINE);
+    }
+
+    private Map<MachineLocation, Entity> getMachineEntityMap() {
+        return getAttribute(MACHINE_ENTITY);
+    }
+
+    @Override
+    public Function<Collection<Entity>, Entity> getRemovalStrategy() {
+        return UNCLAIMED_REMOVAL_STRATEGY;
+    }
+
+    private final Function<Collection<Entity>, Entity> UNCLAIMED_REMOVAL_STRATEGY = new Function<Collection<Entity>, Entity>() {
+        // Semantics of superclass mean that mutex should already be held when apply is called
+        @Override
+        public Entity apply(Collection<Entity> members) {
+            synchronized (mutex) {
+                Optional<Entity> choice;
+                if (Lifecycle.STOPPING.equals(getAttribute(Attributes.SERVICE_STATE_ACTUAL))) {
+                    choice = Optional.of(members.iterator().next());
+                } else {
+                    // Otherwise should only choose between removable + unusable or available
+                    choice = getMemberWithStatusExcludingUnremovable(members, MachinePoolMemberStatus.UNUSABLE)
+                            .or(getMemberWithStatusExcludingUnremovable(members, MachinePoolMemberStatus.AVAILABLE));
+                }
+                if (!choice.isPresent()) {
+                    LOG.warn("{} has no machines available to remove!", this);
+                    return null;
+                } else {
+                    LOG.info("{} selected entity to remove from pool: {}", this, choice.get());
+                    choice.get().getAttribute(SERVER_STATUS);
+                    setEntityStatus(choice.get(), null);
+                }
+                MachineLocation entityLocation = getEntityMachineMap().remove(choice.get());
+                if (entityLocation != null) {
+                    getMachineEntityMap().remove(entityLocation);
+                }
+                return choice.get();
+            }
+        }
+    };
+
+    private void serverAdded(Entity member) {
+        Maybe<MachineLocation> machine = Machines.findUniqueMachineLocation(member.getLocations());
+        if (member.getAttribute(SERVER_STATUS) != null) {
+            LOG.debug("Skipped addition of machine already in the pool: {}", member);
+        } else if (machine.isPresentAndNonNull()) {
+            MachineLocation m = machine.get();
+            LOG.info("New machine in {}: {}", this, m);
+            setEntityStatus(member, MachinePoolMemberStatus.AVAILABLE);
+            synchronized (mutex) {
+                getEntityMachineMap().put(member, m);
+                getMachineEntityMap().put(m, member);
+                updateCountSensors();
+            }
+        } else {
+            LOG.warn("Member added to {} that does not have a machine location; it will not be used by the pool: {}",
+                    ServerPoolImpl.this, member);
+            setEntityStatus(member, MachinePoolMemberStatus.UNUSABLE);
+        }
+    }
+
+    private void setEntityStatus(Entity entity, MachinePoolMemberStatus status) {
+        ((EntityInternal) entity).setAttribute(SERVER_STATUS, status);
+    }
+
+    private Optional<Entity> getMemberWithStatus(MachinePoolMemberStatus status) {
+        return getMemberWithStatus0(getMembers(), status, true);
+    }
+
+    private Optional<Entity> getMemberWithStatusExcludingUnremovable(Collection<Entity> entities, MachinePoolMemberStatus status) {
+        return getMemberWithStatus0(entities, status, false);
+    }
+
+    private Optional<Entity> getMemberWithStatus0(Collection<Entity> entities, final MachinePoolMemberStatus status, final boolean includeUnremovableMachines) {
+        return Iterables.tryFind(entities,
+                new Predicate<Entity>() {
+                    @Override
+                    public boolean apply(Entity input) {
+                        return (includeUnremovableMachines || isRemovable(input)) &&
+                                status.equals(input.getAttribute(SERVER_STATUS));
+                    }
+                });
+    }
+
+    /** @return true if the entity has {@link #REMOVABLE} set to null or true. */
+    private boolean isRemovable(Entity entity) {
+        return !Boolean.FALSE.equals(entity.getConfig(REMOVABLE));
+    }
+
+    private void updateCountSensors() {
+        synchronized (mutex) {
+            int available = 0, claimed = 0;
+            for (Entity member : getMembers()) {
+                MachinePoolMemberStatus status = member.getAttribute(SERVER_STATUS);
+                if (MachinePoolMemberStatus.AVAILABLE.equals(status)) {
+                    available++;
+                } else if (MachinePoolMemberStatus.CLAIMED.equals(status)) {
+                    claimed++;
+                }
+            }
+            setAttribute(AVAILABLE_COUNT, available);
+            setAttribute(CLAIMED_COUNT, claimed);
+        }
+    }
+
+    public static class MemberTrackingPolicy extends AbstractMembershipTrackingPolicy {
+        @Override
+        protected void onEntityEvent(EventType type, Entity member) {
+            Boolean isUp = member.getAttribute(Attributes.SERVICE_UP);
+            LOG.info("{} in {}: {} service up is {}", new Object[]{type.name(), entity, member, isUp});
+            if (type.equals(EventType.ENTITY_ADDED) || type.equals(EventType.ENTITY_CHANGE)) {
+                if (Boolean.TRUE.equals(isUp)) {
+                    ((ServerPoolImpl) entity).serverAdded(member);
+                } else if (LOG.isDebugEnabled()) {
+                    LOG.debug("{} observed event {} but {} is not up (yet) and will not be used by the pool",
+                            new Object[]{entity, type.name(), member});
+                }
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocation.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocation.java b/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocation.java
new file mode 100644
index 0000000..6c50f94
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocation.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.machine.pool;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.util.Collection;
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Maps;
+
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.location.basic.AbstractLocation;
+import org.apache.brooklyn.location.dynamic.DynamicLocation;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+
+public class ServerPoolLocation extends AbstractLocation implements MachineProvisioningLocation<MachineLocation>,
+        DynamicLocation<ServerPool, ServerPoolLocation> {
+
+    private static final long serialVersionUID = -6771844611899475409L;
+
+    private static final Logger LOG = LoggerFactory.getLogger(ServerPoolLocation.class);
+
+    @SetFromFlag("owner")
+    public static final ConfigKey<ServerPool> OWNER = ConfigKeys.newConfigKey(
+            ServerPool.class, "pool.location.owner");
+
+    @Override
+    public void init() {
+        LOG.debug("Initialising. Owner is: {}", checkNotNull(getConfig(OWNER), OWNER.getName()));
+        super.init();
+    }
+
+    @Override
+    public ServerPool getOwner() {
+        return getConfig(OWNER);
+    }
+
+    @Override
+    public MachineLocation obtain(Map<?, ?> flags) throws NoMachinesAvailableException {
+        // Call server pool and try to obtain one of its machines
+        return getOwner().claimMachine(flags);
+    }
+
+    @Override
+    public MachineProvisioningLocation<MachineLocation> newSubLocation(Map<?, ?> newFlags) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void release(MachineLocation machine) {
+        getOwner().releaseMachine(machine);
+    }
+
+    @Override
+    public Map<String, Object> getProvisioningFlags(Collection<String> tags) {
+        return Maps.newLinkedHashMap();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolver.java b/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolver.java
new file mode 100644
index 0000000..4bcb1a3
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolver.java
@@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.machine.pool;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationRegistry;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.LocationResolver.EnableableLocationResolver;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
+
+import org.apache.brooklyn.location.basic.BasicLocationRegistry;
+import org.apache.brooklyn.location.basic.LocationInternal;
+import org.apache.brooklyn.location.basic.LocationPropertiesFromBrooklynProperties;
+import org.apache.brooklyn.location.dynamic.DynamicLocation;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.text.KeyValueParser;
+import org.apache.brooklyn.util.text.Strings;
+
+public class ServerPoolLocationResolver implements EnableableLocationResolver {
+
+    private static final Logger LOG = LoggerFactory.getLogger(ServerPoolLocationResolver.class);
+    private static final String PREFIX = "pool";
+    public static final String POOL_SPEC = PREFIX + ":%s";
+    private static final Pattern PATTERN = Pattern.compile("("+PREFIX+"|"+PREFIX.toUpperCase()+")" +
+            ":([a-zA-Z0-9]+)" + // pool Id
+            "(:\\((.*)\\))?$"); // arguments, e.g. displayName
+
+    private static final Set<String> ACCEPTABLE_ARGS = ImmutableSet.of("name", "displayName");
+
+    private ManagementContext managementContext;
+
+    @Override
+    public boolean isEnabled() {
+        return true;
+    }
+
+    @Override
+    public void init(ManagementContext managementContext) {
+        this.managementContext = checkNotNull(managementContext, "managementContext");
+    }
+
+    @Override
+    public String getPrefix() {
+        return PREFIX;
+    }
+
+    @Override
+    public boolean accepts(String spec, LocationRegistry registry) {
+        return BasicLocationRegistry.isResolverPrefixForSpec(this, spec, true);
+    }
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @Override
+    public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Resolving location '" + spec + "' with flags " + Joiner.on(",").withKeyValueSeparator("=").join(locationFlags));
+        }
+        String namedLocation = (String) locationFlags.get(LocationInternal.NAMED_SPEC_NAME.getName());
+
+        Matcher matcher = PATTERN.matcher(spec);
+        if (!matcher.matches()) {
+            String m = String.format("Invalid location '%s'; must specify either %s:entityId or %s:entityId:(key=argument)",
+                    spec, PREFIX, PREFIX);
+            throw new IllegalArgumentException(m);
+        }
+
+        String argsPart = matcher.group(4);
+        Map<String, String> argsMap = (argsPart != null) ? KeyValueParser.parseMap(argsPart) : Collections.<String,String>emptyMap();
+        String displayNamePart = argsMap.get("displayName");
+        String namePart = argsMap.get("name");
+
+        if (!ACCEPTABLE_ARGS.containsAll(argsMap.keySet())) {
+            Set<String> illegalArgs = Sets.difference(argsMap.keySet(), ACCEPTABLE_ARGS);
+            throw new IllegalArgumentException("Invalid location '"+spec+"'; illegal args "+illegalArgs+"; acceptable args are "+ACCEPTABLE_ARGS);
+        }
+        if (argsMap.containsKey("displayName") && Strings.isEmpty(displayNamePart)) {
+            throw new IllegalArgumentException("Invalid location '"+spec+"'; if displayName supplied then value must be non-empty");
+        }
+        if (argsMap.containsKey("name") && Strings.isEmpty(namePart)) {
+            throw new IllegalArgumentException("Invalid location '"+spec+"'; if name supplied then value must be non-empty");
+        }
+
+        Map<String, Object> filteredProperties = new LocationPropertiesFromBrooklynProperties()
+                .getLocationProperties(PREFIX, namedLocation, registry.getProperties());
+        MutableMap<String, Object> flags = MutableMap.<String, Object>builder()
+                .putAll(filteredProperties)
+                .putAll(locationFlags)
+                .build();
+
+        String poolId = matcher.group(2);
+        if (Strings.isBlank(poolId)) {
+            throw new IllegalArgumentException("Invalid location '"+spec+"'; pool's entity id must be non-empty");
+        }
+
+        final String displayName = displayNamePart != null ? displayNamePart : "Server Pool " + poolId;
+        final String locationName = namePart != null ? namePart : "serverpool-" + poolId;
+
+        Entity pool = managementContext.getEntityManager().getEntity(poolId);
+        LocationSpec<ServerPoolLocation> locationSpec = LocationSpec.create(ServerPoolLocation.class)
+                .configure(flags)
+                .configure(DynamicLocation.OWNER, pool)
+                .configure(LocationInternal.NAMED_SPEC_NAME, locationName)
+                .displayName(displayName);
+        return managementContext.getLocationManager().createLocation(locationSpec);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessDriver.java
new file mode 100644
index 0000000..5efd7c2
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessDriver.java
@@ -0,0 +1,516 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.apache.brooklyn.util.JavaGroovyEquivalents.elvis;
+
+import java.io.File;
+import java.io.InputStream;
+import java.io.Reader;
+import java.io.StringReader;
+import java.util.Map;
+
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.ResourceUtils;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.core.text.TemplateProcessor;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.stream.ReaderInputStream;
+import org.apache.brooklyn.util.text.Strings;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableMap;
+
+/**
+ * An abstract implementation of the {@link SoftwareProcessDriver}.
+ */
+public abstract class AbstractSoftwareProcessDriver implements SoftwareProcessDriver {
+
+    private static final Logger log = LoggerFactory.getLogger(AbstractSoftwareProcessDriver.class);
+
+    protected final EntityLocal entity;
+    protected final ResourceUtils resource;
+    protected final Location location;
+
+    public AbstractSoftwareProcessDriver(EntityLocal entity, Location location) {
+        this.entity = checkNotNull(entity, "entity");
+        this.location = checkNotNull(location, "location");
+        this.resource = ResourceUtils.create(entity);
+    }
+
+    /*
+     * (non-Javadoc)
+     * @see brooklyn.entity.basic.SoftwareProcessDriver#rebind()
+     */
+    @Override
+    public void rebind() {
+        // no-op
+    }
+
+    /**
+     * Start the entity.
+     * <p>
+     * This installs, configures and launches the application process. However,
+     * users can also call the {@link #install()}, {@link #customize()} and
+     * {@link #launch()} steps independently. The {@link #postLaunch()} will
+     * be called after the {@link #launch()} metheod is executed, but the
+     * process may not be completely initialised at this stage, so care is
+     * required when implementing these stages.
+     * <p>
+     * The {@link BrooklynConfigKeys#ENTITY_RUNNING} key can be set on the location
+     * or the entity to skip the startup process if the entity is already running,
+     * according to the {@link #isRunning()} method. To force the startup to be
+     * skipped, {@link BrooklynConfigKeys#SKIP_ENTITY_START} can be set on the entity.
+     * The {@link BrooklynConfigKeys#SKIP_ENTITY_INSTALLATION} key can also be used to
+     * skip the {@link #setup()}, {@link #copyInstallResources()} and
+     * {@link #install()} methods if set on the entity or location. 
+     *
+     * @see #stop()
+     */
+    @Override
+    public void start() {
+        boolean skipStart = false;
+        Optional<Boolean> locationRunning = Optional.fromNullable(getLocation().getConfig(BrooklynConfigKeys.SKIP_ENTITY_START_IF_RUNNING));
+        Optional<Boolean> entityRunning = Optional.fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_START_IF_RUNNING));
+        Optional<Boolean> entityStarted = Optional.fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_START));
+        if (locationRunning.or(entityRunning).or(false)) {
+            skipStart = isRunning();
+        } else {
+            skipStart = entityStarted.or(false);
+        }
+        if (!skipStart) {
+            DynamicTasks.queue("copy-pre-install-resources", new Runnable() { public void run() {
+                waitForConfigKey(BrooklynConfigKeys.PRE_INSTALL_RESOURCES_LATCH);
+                copyPreInstallResources();
+            }});
+
+            DynamicTasks.queue("pre-install", new Runnable() { public void run() {
+                preInstall();
+            }});
+
+            if (Strings.isNonBlank(entity.getConfig(BrooklynConfigKeys.PRE_INSTALL_COMMAND))) {
+                DynamicTasks.queue("pre-install-command", new Runnable() { public void run() {
+                    runPreInstallCommand(entity.getConfig(BrooklynConfigKeys.PRE_INSTALL_COMMAND));
+                }});
+            };
+
+            Optional<Boolean> locationInstalled = Optional.fromNullable(getLocation().getConfig(BrooklynConfigKeys.SKIP_ENTITY_INSTALLATION));
+            Optional<Boolean> entityInstalled = Optional.fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_INSTALLATION));
+            boolean skipInstall = locationInstalled.or(entityInstalled).or(false);
+            if (!skipInstall) {
+                DynamicTasks.queue("setup", new Runnable() { public void run() {
+                    waitForConfigKey(BrooklynConfigKeys.SETUP_LATCH);
+                    setup();
+                }});
+
+                DynamicTasks.queue("copy-install-resources", new Runnable() { public void run() {
+                    waitForConfigKey(BrooklynConfigKeys.INSTALL_RESOURCES_LATCH);
+                    copyInstallResources();
+                }});
+
+                DynamicTasks.queue("install", new Runnable() { public void run() {
+                    waitForConfigKey(BrooklynConfigKeys.INSTALL_LATCH);
+                    install();
+                }});
+            }
+
+            if (Strings.isNonBlank(entity.getConfig(BrooklynConfigKeys.POST_INSTALL_COMMAND))) {
+                DynamicTasks.queue("post-install-command", new Runnable() { public void run() {
+                    runPostInstallCommand(entity.getConfig(BrooklynConfigKeys.POST_INSTALL_COMMAND));
+                }});
+            }
+
+            DynamicTasks.queue("customize", new Runnable() { public void run() {
+                waitForConfigKey(BrooklynConfigKeys.CUSTOMIZE_LATCH);
+                customize();
+            }});
+
+            DynamicTasks.queue("copy-runtime-resources", new Runnable() { public void run() {
+                waitForConfigKey(BrooklynConfigKeys.RUNTIME_RESOURCES_LATCH);
+                copyRuntimeResources();
+            }});
+
+            if (Strings.isNonBlank(entity.getConfig(BrooklynConfigKeys.PRE_LAUNCH_COMMAND))) {
+                DynamicTasks.queue("pre-launch-command", new Runnable() { public void run() {
+                    runPreLaunchCommand(entity.getConfig(BrooklynConfigKeys.PRE_LAUNCH_COMMAND));
+                }});
+            };
+
+            DynamicTasks.queue("launch", new Runnable() { public void run() {
+                waitForConfigKey(BrooklynConfigKeys.LAUNCH_LATCH);
+                launch();
+            }});
+
+            if (Strings.isNonBlank(entity.getConfig(BrooklynConfigKeys.POST_LAUNCH_COMMAND))) {
+                DynamicTasks.queue("post-launch-command", new Runnable() { public void run() {
+                    runPostLaunchCommand(entity.getConfig(BrooklynConfigKeys.POST_LAUNCH_COMMAND));
+                }});
+            };
+        }
+
+        DynamicTasks.queue("post-launch", new Runnable() { public void run() {
+            postLaunch();
+        }});
+    }
+
+    @Override
+    public abstract void stop();
+
+    /**
+     * Implement this method in child classes to add some pre-install behavior
+     */
+    public void preInstall() {}
+
+    public abstract void runPreInstallCommand(String command);
+    public abstract void setup();
+    public abstract void install();
+    public abstract void runPostInstallCommand(String command);
+    public abstract void customize();
+    public abstract void runPreLaunchCommand(String command);
+    public abstract void launch();
+    public abstract void runPostLaunchCommand(String command);
+
+    @Override
+    public void kill() {
+        stop();
+    }
+
+    /**
+     * Implement this method in child classes to add some post-launch behavior
+     */
+    public void postLaunch() {}
+
+    @Override
+    public void restart() {
+        DynamicTasks.queue("stop (best effort)", new Runnable() {
+            public void run() {
+                DynamicTasks.markInessential();
+                boolean previouslyRunning = isRunning();
+                try {
+                    ServiceStateLogic.setExpectedState(getEntity(), Lifecycle.STOPPING);
+                    stop();
+                } catch (Exception e) {
+                    // queue a failed task so that there is visual indication that this task had a failure,
+                    // without interrupting the parent
+                    if (previouslyRunning) {
+                        log.warn(getEntity() + " restart: stop failed, when was previously running (ignoring)", e);
+                        DynamicTasks.queue(Tasks.fail("Primary job failure (when previously running)", e));
+                    } else {
+                        log.debug(getEntity() + " restart: stop failed (but was not previously running, so not a surprise)", e);
+                        DynamicTasks.queue(Tasks.fail("Primary job failure (when not previously running)", e));
+                    }
+                    // the above queued tasks will cause this task to be indicated as failed, with an indication of severity
+                }
+            }
+        });
+
+        if (doFullStartOnRestart()) {
+            DynamicTasks.waitForLast();
+            ServiceStateLogic.setExpectedState(getEntity(), Lifecycle.STARTING);
+            start();
+        } else {
+            DynamicTasks.queue("launch", new Runnable() { public void run() {
+                ServiceStateLogic.setExpectedState(getEntity(), Lifecycle.STARTING);
+                launch();
+            }});
+            DynamicTasks.queue("post-launch", new Runnable() { public void run() {
+                postLaunch();
+            }});
+        }
+    }
+
+    @Beta
+    /** ideally restart() would take options, e.g. whether to do full start, skip installs, etc;
+     * however in the absence here is a toggle - not sure how well it works;
+     * default is false which is similar to previous behaviour (with some seemingly-obvious tidies),
+     * meaning install and configure will NOT be done on restart. */
+    protected boolean doFullStartOnRestart() {
+        return false;
+    }
+
+    @Override
+    public EntityLocal getEntity() { return entity; }
+
+    @Override
+    public Location getLocation() { return location; }
+
+    public InputStream getResource(String url) {
+        return resource.getResourceFromUrl(url);
+    }
+
+    /**
+     * Files and templates to be copied to the server <em>before</em> pre-install. This allows the {@link #preInstall()}
+     * process to have access to all required resources.
+     * <p>
+     * Will be prefixed with the entity's {@link #getInstallDir() install directory} if relative.
+     *
+     * @see SoftwareProcess#PRE_INSTALL_FILES
+     * @see SoftwareProcess#PRE_INSTALL_TEMPLATES
+     * @see #copyRuntimeResources()
+     */
+    public void copyPreInstallResources() {
+        copyResources(entity.getConfig(SoftwareProcess.PRE_INSTALL_FILES), entity.getConfig(SoftwareProcess.PRE_INSTALL_TEMPLATES));
+    }
+
+    /**
+     * Files and templates to be copied to the server <em>before</em> installation. This allows the {@link #install()}
+     * process to have access to all required resources.
+     * <p>
+     * Will be prefixed with the entity's {@link #getInstallDir() install directory} if relative.
+     *
+     * @see SoftwareProcess#INSTALL_FILES
+     * @see SoftwareProcess#INSTALL_TEMPLATES
+     * @see #copyRuntimeResources()
+     */
+    public void copyInstallResources() {
+        copyResources(entity.getConfig(SoftwareProcess.INSTALL_FILES), entity.getConfig(SoftwareProcess.INSTALL_TEMPLATES));
+    }
+
+    private void copyResources(Map<String, String> files, Map<String, String> templates) {
+        // Ensure environment variables are not looked up here, otherwise sub-classes might
+        // lookup port numbers and fail with ugly error if port is not set; better to wait
+        // until in Entity's code (e.g. customize) where such checks are done explicitly.
+
+        boolean hasAnythingToCopy = ((files != null && files.size() > 0) || (templates != null && templates.size() > 0));
+        if (hasAnythingToCopy) {
+            createDirectory(getInstallDir(), "create install directory");
+    
+            // TODO see comment in copyResource, that should be queued as a task like the above
+            // (better reporting in activities console)
+    
+            if (files != null && files.size() > 0) {
+                for (String source : files.keySet()) {
+                    String target = files.get(source);
+                    String destination = Os.isAbsolutish(target) ? target : Os.mergePathsUnix(getInstallDir(), target);
+                    copyResource(source, destination, true);
+                }
+            }
+    
+            if (templates != null && templates.size() > 0) {
+                for (String source : templates.keySet()) {
+                    String target = templates.get(source);
+                    String destination = Os.isAbsolutish(target) ? target : Os.mergePathsUnix(getInstallDir(), target);
+                    copyTemplate(source, destination, true, MutableMap.<String, Object>of());
+                }
+            }
+        }
+    }
+
+    protected abstract void createDirectory(String directoryName, String summaryForLogging);
+
+    /**
+     * Files and templates to be copied to the server <em>after</em> customisation. This allows overwriting of
+     * existing files such as entity configuration which may be copied from the installation directory
+     * during the {@link #customize()} process.
+     * <p>
+     * Will be prefixed with the entity's {@link #getRunDir() run directory} if relative.
+     *
+     * @see SoftwareProcess#RUNTIME_FILES
+     * @see SoftwareProcess#RUNTIME_TEMPLATES
+     * @see #copyInstallResources()
+     */
+    public void copyRuntimeResources() {
+        try {
+            createDirectory(getRunDir(), "create run directory");
+
+            Map<String, String> runtimeFiles = entity.getConfig(SoftwareProcess.RUNTIME_FILES);
+            if (runtimeFiles != null && runtimeFiles.size() > 0) {
+                for (String source : runtimeFiles.keySet()) {
+                    String target = runtimeFiles.get(source);
+                    String destination = Os.isAbsolutish(target) ? target : Os.mergePathsUnix(getRunDir(), target);
+                    copyResource(source, destination, true);
+                }
+            }
+
+            Map<String, String> runtimeTemplates = entity.getConfig(SoftwareProcess.RUNTIME_TEMPLATES);
+            if (runtimeTemplates != null && runtimeTemplates.size() > 0) {
+                for (String source : runtimeTemplates.keySet()) {
+                    String target = runtimeTemplates.get(source);
+                    String destination = Os.isAbsolutish(target) ? target : Os.mergePathsUnix(getRunDir(), target);
+                    copyTemplate(source, destination, true, MutableMap.<String, Object>of());
+                }
+            }
+        } catch (Exception e) {
+            log.warn("Error copying runtime resources", e);
+            throw Exceptions.propagate(e);
+        }
+    }
+
+    /**
+     * @param template File to template and copy.
+     * @param target Destination on server.
+     * @return The exit code the SSH command run.
+     */
+    public int copyTemplate(File template, String target) {
+        return copyTemplate(template.toURI().toASCIIString(), target);
+    }
+
+    /**
+     * @param template URI of file to template and copy, e.g. file://.., http://.., classpath://..
+     * @param target Destination on server.
+     * @return The exit code of the SSH command run.
+     */
+    public int copyTemplate(String template, String target) {
+        return copyTemplate(template, target, false, ImmutableMap.<String, String>of());
+    }
+
+    /**
+     * @param template URI of file to template and copy, e.g. file://.., http://.., classpath://..
+     * @param target Destination on server.
+     * @param extraSubstitutions Extra substitutions for the templater to use, for example
+     *               "foo" -> "bar", and in a template ${foo}.
+     * @return The exit code of the SSH command run.
+     */
+    public int copyTemplate(String template, String target, boolean createParent, Map<String, ?> extraSubstitutions) {
+        String data = processTemplate(template, extraSubstitutions);
+        return copyResource(MutableMap.<Object,Object>of(), new StringReader(data), target, createParent);
+    }
+
+    public abstract int copyResource(Map<Object,Object> sshFlags, String source, String target, boolean createParentDir);
+
+    public abstract int copyResource(Map<Object,Object> sshFlags, InputStream source, String target, boolean createParentDir);
+
+    /**
+     * @param file File to copy.
+     * @param target Destination on server.
+     * @return The exit code the SSH command run.
+     */
+    public int copyResource(File file, String target) {
+        return copyResource(file.toURI().toASCIIString(), target);
+    }
+
+    /**
+     * @param resource URI of file to copy, e.g. file://.., http://.., classpath://..
+     * @param target Destination on server.
+     * @return The exit code of the SSH command run
+     */
+    public int copyResource(String resource, String target) {
+        return copyResource(MutableMap.of(), resource, target);
+    }
+
+    public int copyResource(String resource, String target, boolean createParentDir) {
+        return copyResource(MutableMap.of(), resource, target, createParentDir);
+    }
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    public int copyResource(Map sshFlags, String source, String target) {
+        return copyResource(sshFlags, source, target, false);
+    }
+
+    /**
+     * @see #copyResource(Map, InputStream, String, boolean)
+     */
+    public int copyResource(Reader source, String target) {
+        return copyResource(MutableMap.of(), source, target, false);
+    }
+
+    /**
+     * @see #copyResource(Map, InputStream, String, boolean)
+     */
+    public int copyResource(Map<Object,Object> sshFlags, Reader source, String target, boolean createParent) {
+        return copyResource(sshFlags, new ReaderInputStream(source), target, createParent);
+    }
+
+    /**
+     * @see #copyResource(Map, InputStream, String, boolean)
+     */
+    public int copyResource(InputStream source, String target) {
+        return copyResource(MutableMap.of(), source, target, false);
+    }
+
+    public String getResourceAsString(String url) {
+        return resource.getResourceAsString(url);
+    }
+
+    public String processTemplate(File templateConfigFile, Map<String,Object> extraSubstitutions) {
+        return processTemplate(templateConfigFile.toURI().toASCIIString(), extraSubstitutions);
+    }
+
+    public String processTemplate(File templateConfigFile) {
+        return processTemplate(templateConfigFile.toURI().toASCIIString());
+    }
+
+    /** Takes the contents of a template file from the given URL (often a classpath://com/myco/myprod/myfile.conf or .sh)
+     * and replaces "${entity.xxx}" with the result of entity.getXxx() and similar for other driver, location;
+     * as well as replacing config keys on the management context
+     * <p>
+     * uses Freemarker templates under the covers
+     **/
+    public String processTemplate(String templateConfigUrl) {
+        return processTemplate(templateConfigUrl, ImmutableMap.<String,String>of());
+    }
+
+    public String processTemplate(String templateConfigUrl, Map<String,? extends Object> extraSubstitutions) {
+        return processTemplateContents(getResourceAsString(templateConfigUrl), extraSubstitutions);
+    }
+
+    public String processTemplateContents(String templateContents) {
+        return processTemplateContents(templateContents, ImmutableMap.<String,String>of());
+    }
+
+    public String processTemplateContents(String templateContents, Map<String,? extends Object> extraSubstitutions) {
+        return TemplateProcessor.processTemplateContents(templateContents, this, extraSubstitutions);
+    }
+
+    protected void waitForConfigKey(ConfigKey<?> configKey) {
+        Object val = entity.getConfig(configKey);
+        if (val != null) log.debug("{} finished waiting for {} (value {}); continuing...", new Object[] {this, configKey, val});
+    }
+
+    /**
+     * @deprecated since 0.5.0; instead rely on {@link org.apache.brooklyn.api.entity.drivers.downloads.DownloadResolverManager} to include local-repo, such as:
+     *
+     * <pre>
+     * {@code
+     * DownloadResolver resolver = Entities.newDownloader(this);
+     * List<String> urls = resolver.getTargets();
+     * }
+     * </pre>
+     */
+    protected String getEntityVersionLabel() {
+        return getEntityVersionLabel("_");
+    }
+
+    /**
+     * @deprecated since 0.5.0; instead rely on {@link org.apache.brooklyn.api.entity.drivers.downloads.DownloadResolverManager} to include local-repo
+     */
+    protected String getEntityVersionLabel(String separator) {
+        return elvis(entity.getEntityType().getSimpleName(),
+                entity.getClass().getName())+(getVersion() != null ? separator+getVersion() : "");
+    }
+
+    public String getVersion() {
+        return getEntity().getConfig(SoftwareProcess.SUGGESTED_VERSION);
+    }
+
+    public abstract String getRunDir();
+    public abstract String getInstallDir();
+}


[47/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/AggregatingMachineProvisioningLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/AggregatingMachineProvisioningLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/core/AggregatingMachineProvisioningLocationTest.java
new file mode 100644
index 0000000..be85699
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/AggregatingMachineProvisioningLocationTest.java
@@ -0,0 +1,117 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.fail;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.core.AggregatingMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation.LocalhostMachine;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+public class AggregatingMachineProvisioningLocationTest {
+
+    
+    private LocalManagementContext managementContext;
+    private AggregatingMachineProvisioningLocation<LocalhostMachine> aggregator;
+    private LocalhostMachine machine1a;
+    private LocalhostMachine machine1b;
+    private LocalhostMachine machine2a;
+    private LocalhostMachine machine2b;
+    private MachineProvisioningLocation<LocalhostMachine> provisioner1;
+    private MachineProvisioningLocation<LocalhostMachine> provisioner2;
+    
+    @BeforeMethod(alwaysRun=true)
+    @SuppressWarnings("unchecked")
+    public void setUp() {
+        managementContext = new LocalManagementContextForTests();
+        machine1a = newLocation(LocalhostMachine.class, "1a");
+        machine1b = newLocation(LocalhostMachine.class, "1b");
+        machine2a = newLocation(LocalhostMachine.class, "2a");
+        machine2b = newLocation(LocalhostMachine.class, "2b");
+        provisioner1 = newLocation(FixedListMachineProvisioningLocation.class, ImmutableMap.of("machines", ImmutableList.of(machine1a, machine1b)));
+        provisioner2 = newLocation(FixedListMachineProvisioningLocation.class, ImmutableMap.of("machines", ImmutableList.of(machine2a, machine2b)));
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() {
+        if (managementContext != null) Entities.destroyAll(managementContext);
+    }
+
+    @Test
+    @SuppressWarnings("unchecked")
+    public void testObtainAndRelease() throws Exception {
+        aggregator = newLocation(AggregatingMachineProvisioningLocation.class, ImmutableMap.of("provisioners", ImmutableList.of(provisioner1, provisioner2)));
+        assertEquals(aggregator.obtain(), machine1a);
+        assertEquals(aggregator.obtain(), machine2a);
+        assertEquals(aggregator.obtain(), machine1b);
+        assertEquals(aggregator.obtain(), machine2b);
+        
+        try {
+            aggregator.obtain();
+            fail();
+        } catch (NoMachinesAvailableException e) {
+            // success
+        }
+        
+        aggregator.release(machine2b);
+        assertEquals(aggregator.obtain(), machine2b);
+    }
+
+    @Test
+    @SuppressWarnings("unchecked")
+    public void testReleaseWhenNotHeldThrows() throws Exception {
+        aggregator = newLocation(AggregatingMachineProvisioningLocation.class, ImmutableMap.of("provisioners", ImmutableList.of(provisioner1, provisioner2)));
+        try {
+            aggregator.release(machine1a);
+            fail();
+        } catch (IllegalStateException e) {
+            if (!e.toString().contains("machine is not currently allocated")) throw e;
+        }
+    }
+
+    private <T extends Location> T newLocation(Class<T> clazz, String displayName) {
+        return newLocation(clazz, displayName, ImmutableMap.of());
+    }
+
+    private <T extends Location> T newLocation(Class<T> clazz, Map<?,?> config) {
+        return newLocation(clazz, "mydisplayname", config);
+    }
+    
+    private <T extends Location> T newLocation(Class<T> clazz, String displayName, Map<?,?> config) {
+        return managementContext.getLocationManager().createLocation(LocationSpec.create(clazz)
+                .displayName(displayName)
+                .configure(config));
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/LegacyAbstractLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/LegacyAbstractLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/core/LegacyAbstractLocationTest.java
new file mode 100644
index 0000000..d5d5ae7
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/LegacyAbstractLocationTest.java
@@ -0,0 +1,151 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.util.Collections;
+import java.util.Map;
+
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+
+public class LegacyAbstractLocationTest {
+
+    private static class ConcreteLocation extends AbstractLocation {
+        @SetFromFlag(defaultVal="mydefault")
+        String myfield;
+
+        public ConcreteLocation() {
+            super();
+        }
+
+        public ConcreteLocation(Map properties) {
+            super(properties);
+        }
+    }
+
+    @AfterMethod(alwaysRun = true)
+    public void tearDown(){
+        // nothing to tear down; did not create a management context
+    }
+
+    @Test
+    public void testEquals() {
+        AbstractLocation l1 = new ConcreteLocation(MutableMap.of("id", "1", "name", "bob"));
+        AbstractLocation l2 = new ConcreteLocation(MutableMap.of("id", "1", "name", "frank"));
+        AbstractLocation l3 = new ConcreteLocation(MutableMap.of("id", "2", "name", "frank"));
+        assertEquals(l1, l2);
+        assertNotEquals(l2, l3);
+    }
+
+    @Test
+    public void nullNameAndParentLocationIsAcceptable() {
+        AbstractLocation location = new ConcreteLocation(MutableMap.of("name", null, "parentLocation", null));
+        assertEquals(location.getDisplayName(), null);
+        assertEquals(location.getParent(), null);
+    }
+
+    @Test
+    public void testSettingParentLocation() {
+        AbstractLocation location = new ConcreteLocation();
+        AbstractLocation locationSub = new ConcreteLocation();
+        locationSub.setParent(location);
+        
+        assertEquals(ImmutableList.copyOf(location.getChildren()), ImmutableList.of(locationSub));
+        assertEquals(locationSub.getParent(), location);
+    }
+
+    @Test
+    public void testClearingParentLocation() {
+        AbstractLocation location = new ConcreteLocation();
+        AbstractLocation locationSub = new ConcreteLocation();
+        locationSub.setParent(location);
+        
+        locationSub.setParent(null);
+        assertEquals(ImmutableList.copyOf(location.getChildren()), Collections.emptyList());
+        assertEquals(locationSub.getParent(), null);
+    }
+    
+    @Test
+    public void testContainsLocation() {
+        AbstractLocation location = new ConcreteLocation();
+        AbstractLocation locationSub = new ConcreteLocation();
+        locationSub.setParent(location);
+        
+        assertTrue(location.containsLocation(location));
+        assertTrue(location.containsLocation(locationSub));
+        assertFalse(locationSub.containsLocation(location));
+    }
+
+
+    @Test
+    public void queryingNameReturnsNameGivenInConstructor() {
+        String name = "Outer Mongolia";
+        AbstractLocation location = new ConcreteLocation(MutableMap.of("name", "Outer Mongolia"));
+        assertEquals(location.getDisplayName(), name);;
+    }
+
+    @Test
+    public void constructorParentLocationReturnsExpectedLocation() {
+        AbstractLocation parent = new ConcreteLocation(MutableMap.of("name", "Middle Earth"));
+        AbstractLocation child = new ConcreteLocation(MutableMap.of("name", "The Shire", "parentLocation", parent));
+        assertEquals(child.getParent(), parent);
+        assertEquals(ImmutableList.copyOf(parent.getChildren()), ImmutableList.of(child));
+    }
+
+    @Test
+    public void setParentLocationReturnsExpectedLocation() {
+        AbstractLocation parent = new ConcreteLocation(MutableMap.of("name", "Middle Earth"));
+        AbstractLocation child = new ConcreteLocation(MutableMap.of("name", "The Shire"));
+        child.setParent(parent);
+        assertEquals(child.getParent(), parent);
+        assertEquals(ImmutableList.copyOf(parent.getChildren()), ImmutableList.of(child));
+    }
+    
+    @Test
+    public void testAddChildToParentLocationReturnsExpectedLocation() {
+        AbstractLocation parent = new ConcreteLocation(MutableMap.of("id", "1"));
+        AbstractLocation child = new ConcreteLocation(MutableMap.of("id", "2"));
+        parent.addChild(child);
+        assertEquals(child.getParent(), parent);
+        assertEquals(ImmutableList.copyOf(parent.getChildren()), ImmutableList.of(child));
+    }
+
+    @Test
+    public void testFieldSetFromFlag() {
+        ConcreteLocation loc = new ConcreteLocation(MutableMap.of("myfield", "myval"));
+        assertEquals(loc.myfield, "myval");
+    }
+    
+    @Test
+    public void testFieldSetFromFlagUsesDefault() {
+        ConcreteLocation loc = new ConcreteLocation();
+        assertEquals(loc.myfield, "mydefault");
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/LocationConfigTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/LocationConfigTest.java b/core/src/test/java/org/apache/brooklyn/location/core/LocationConfigTest.java
new file mode 100644
index 0000000..3a953f7
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/LocationConfigTest.java
@@ -0,0 +1,204 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static org.testng.Assert.assertEquals;
+
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableMap;
+
+public class LocationConfigTest {
+
+    // TODO Duplication of LocationConfigTest, but with locations instead of entities
+    
+    private ManagementContext managementContext;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        managementContext = LocalManagementContextForTests.newInstance();
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() {
+        if (managementContext != null) Entities.destroyAll(managementContext);
+    }
+
+    @Test
+    public void testConfigBagContainsMatchesForConfigKeyName() throws Exception {
+        LocationInternal loc = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class)
+                .configure("mylocation.myconfig", "myval1")
+                .configure("mylocation.myconfigwithflagname", "myval2"));
+        
+        assertEquals(loc.config().getBag().getAllConfig(), ImmutableMap.of("mylocation.myconfig", "myval1", "mylocation.myconfigwithflagname", "myval2"));
+        assertEquals(loc.config().getLocalBag().getAllConfig(), ImmutableMap.of("mylocation.myconfig", "myval1", "mylocation.myconfigwithflagname", "myval2"));
+        Assert.assertEquals(loc.getAllConfig(true), ImmutableMap.of("mylocation.myconfig", "myval1", "mylocation.myconfigwithflagname", "myval2"));
+        Assert.assertEquals(loc.getAllConfig(false), ImmutableMap.of("mylocation.myconfig", "myval1", "mylocation.myconfigwithflagname", "myval2"));
+    }
+
+    // TODO Note difference compared to Location, where both flag-name + config-key-name are in the ConfigBag
+    @Test
+    public void testConfigBagContainsMatchesForFlagName() throws Exception {
+        // Prefers flag-name, over config-key's name
+        LocationInternal loc = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class)
+                .configure("myconfigflagname", "myval"));
+        
+        assertEquals(loc.config().getBag().getAllConfig(), ImmutableMap.of("mylocation.myconfigwithflagname", "myval", "myconfigflagname", "myval"));
+        assertEquals(loc.config().getLocalBag().getAllConfig(), ImmutableMap.of("mylocation.myconfigwithflagname", "myval", "myconfigflagname", "myval"));
+        Assert.assertEquals(loc.getAllConfig(true), ImmutableMap.of("mylocation.myconfigwithflagname", "myval", "myconfigflagname", "myval"));
+        Assert.assertEquals(loc.getAllConfig(false), ImmutableMap.of("mylocation.myconfigwithflagname", "myval", "myconfigflagname", "myval"));
+    }
+
+    @Test
+    public void testConfigBagContainsUnmatched() throws Exception {
+        LocationInternal loc = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class)
+                .configure("notThere", "notThereVal"));
+        
+        assertEquals(loc.config().getBag().getAllConfig(), ImmutableMap.of("notThere", "notThereVal"));
+        assertEquals(loc.config().getLocalBag().getAllConfig(), ImmutableMap.of("notThere", "notThereVal"));
+        Assert.assertEquals(loc.getAllConfig(true), ImmutableMap.of("notThere", "notThereVal"));
+        Assert.assertEquals(loc.getAllConfig(false), ImmutableMap.of("notThere", "notThereVal"));
+    }
+    
+    // TODO Note difference from entity: child's bag contains both the flag-name and the config-key-name
+    @Test
+    public void testChildConfigBagInheritsUnmatchedAtParent() throws Exception {
+        LocationInternal loc = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class)
+                .configure("mychildlocation.myconfig", "myval1")
+                .configure("notThere", "notThereVal"));
+
+        LocationInternal child = managementContext.getLocationManager().createLocation(LocationSpec.create(MyChildLocation.class)
+                .parent(loc));
+
+        assertEquals(child.config().getBag().getAllConfig(), ImmutableMap.of("mychildlocation.myconfig", "myval1", "notThere", "notThereVal"));
+        assertEquals(child.config().getLocalBag().getAllConfig(), ImmutableMap.of());
+        Assert.assertEquals(child.getAllConfig(true), ImmutableMap.of("mychildlocation.myconfig", "myval1", "notThere", "notThereVal"));
+        Assert.assertEquals(child.getAllConfig(false), ImmutableMap.of());
+    }
+    
+    // TODO Fails for location, but passes for entity; not worth fixing here; locations will soon be entities!
+    @Test(groups="WIP")
+    public void testChildConfigBagInheritsFlagNameFromParentSetsOwnConfigKey() throws Exception {
+        LocationInternal loc = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class)
+                .configure("mychildconfigflagname", "myval"));
+
+        LocationInternal child = managementContext.getLocationManager().createLocation(LocationSpec.create(MyChildLocation.class)
+                .parent(loc));
+
+        assertEquals(child.config().getBag().getAllConfig(), ImmutableMap.of("mychildlocation.myconfigwithflagname", "myval"));
+        assertEquals(child.config().getLocalBag().getAllConfig(), ImmutableMap.of());
+        Assert.assertEquals(child.getAllConfig(true), ImmutableMap.of("mychildlocation.myconfigwithflagname", "myval"));
+        Assert.assertEquals(child.getAllConfig(false), ImmutableMap.of());
+    }
+    
+    @Test
+    public void testChildInheritsFromParent() throws Exception {
+        LocationInternal loc = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class)
+                .configure("mylocation.myconfig", "myval1"));
+
+        LocationInternal child = managementContext.getLocationManager().createLocation(LocationSpec.create(MyChildLocation.class)
+                .parent(loc));
+
+        assertEquals(child.config().getBag().getAllConfig(), ImmutableMap.of("mylocation.myconfig", "myval1"));
+        assertEquals(child.config().getLocalBag().getAllConfig(), ImmutableMap.of());
+        Assert.assertEquals(child.getAllConfig(true), ImmutableMap.of("mylocation.myconfig", "myval1"));
+        Assert.assertEquals(child.getAllConfig(false), ImmutableMap.of());
+    }
+    
+    @Test
+    public void testChildCanOverrideConfigUsingKeyName() throws Exception {
+        LocationInternal location = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class)
+                .configure("mychildlocation.myconfigwithflagname", "myval")
+                .configure("notThere", "notThereVal"));
+
+        LocationInternal child = managementContext.getLocationManager().createLocation(LocationSpec.create(MyChildLocation.class)
+                .parent(location)
+                .configure("mychildlocation.myconfigwithflagname", "overrideMyval")
+                .configure("notThere", "overrideNotThereVal"));
+
+        assertEquals(child.config().getBag().getAllConfig(), ImmutableMap.of("mychildlocation.myconfigwithflagname", "overrideMyval", "notThere", "overrideNotThereVal"));
+        assertEquals(child.config().getLocalBag().getAllConfig(), ImmutableMap.of("mychildlocation.myconfigwithflagname", "overrideMyval", "notThere", "overrideNotThereVal"));
+        Assert.assertEquals(child.getAllConfig(true), ImmutableMap.of("mychildlocation.myconfigwithflagname", "overrideMyval", "notThere", "overrideNotThereVal"));
+        Assert.assertEquals(child.getAllConfig(false), ImmutableMap.of("mychildlocation.myconfigwithflagname", "overrideMyval", "notThere", "overrideNotThereVal"));
+    }
+    
+    // TODO Note difference compared to Location, where both flag-name + config-key-name are in the ConfigBag
+    @Test
+    public void testChildCanOverrideConfigUsingFlagName() throws Exception {
+        LocationInternal loc = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class)
+                .configure("mychildlocation.myconfigwithflagname", "myval"));
+
+        LocationInternal child = managementContext.getLocationManager().createLocation(LocationSpec.create(MyChildLocation.class)
+                .parent(loc)
+                .configure("mychildconfigflagname", "overrideMyval"));
+
+        assertEquals(child.config().getBag().getAllConfig(), ImmutableMap.of("mychildlocation.myconfigwithflagname", "overrideMyval", "mychildconfigflagname", "overrideMyval"));
+        assertEquals(child.config().getLocalBag().getAllConfig(), ImmutableMap.of("mychildlocation.myconfigwithflagname", "overrideMyval", "mychildconfigflagname", "overrideMyval"));
+        Assert.assertEquals(child.getAllConfig(true), ImmutableMap.of("mychildlocation.myconfigwithflagname", "overrideMyval", "mychildconfigflagname", "overrideMyval"));
+        Assert.assertEquals(child.getAllConfig(false), ImmutableMap.of("mychildlocation.myconfigwithflagname", "overrideMyval", "mychildconfigflagname", "overrideMyval"));
+    }
+    
+    @Test
+    public void testLocationCanOverrideConfigDefaultValue() throws Exception {
+        LocationInternal loc = managementContext.getLocationManager().createLocation(LocationSpec.create(MyLocation.class));
+        LocationInternal subloc = managementContext.getLocationManager().createLocation(LocationSpec.create(MySubLocation.class));
+
+        Assert.assertEquals(loc.getConfig(MyLocation.MY_CONFIG_WITH_DEFAULT), "mydefault");
+        Assert.assertEquals(loc.getConfig(ConfigKeys.newStringConfigKey("mylocation.myconfigwithdefault", "", "differentdefault")), "mydefault");
+        
+        Assert.assertEquals(subloc.getConfig(MySubLocation.MY_CONFIG_WITH_DEFAULT), "mysubdefault");
+        Assert.assertEquals(subloc.getConfig(MyLocation.MY_CONFIG_WITH_DEFAULT), "mysubdefault");
+    }
+    
+    @SuppressWarnings("serial")
+    public static class MyLocation extends AbstractLocation {
+        public static final ConfigKey<String> MY_CONFIG = ConfigKeys.newStringConfigKey("mylocation.myconfig");
+
+        @SetFromFlag("myconfigflagname")
+        public static final ConfigKey<String> MY_CONFIG_WITH_FLAGNAME = ConfigKeys.newStringConfigKey("mylocation.myconfigwithflagname");
+        
+        public static final ConfigKey<String> MY_CONFIG_WITH_DEFAULT = ConfigKeys.newStringConfigKey("mylocation.myconfigwithdefault", "", "mydefault");
+    }
+    
+    @SuppressWarnings("serial")
+    public static class MyChildLocation extends AbstractLocation {
+        public static final ConfigKey<String> MY_CHILD_CONFIG = ConfigKeys.newStringConfigKey("mychildlocation.myconfig");
+
+        @SetFromFlag("mychildconfigflagname")
+        public static final ConfigKey<String> MY_CHILD_CONFIG_WITH_FLAGNAME = ConfigKeys.newStringConfigKey("mychildlocation.myconfigwithflagname");
+    }
+    
+    @SuppressWarnings("serial")
+    public static class MySubLocation extends MyLocation {
+        public static final ConfigKey<String> MY_CONFIG_WITH_DEFAULT = ConfigKeys.newConfigKeyWithDefault(MyLocation.MY_CONFIG_WITH_DEFAULT, "mysubdefault");
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/LocationConfigUtilsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/LocationConfigUtilsTest.java b/core/src/test/java/org/apache/brooklyn/location/core/LocationConfigUtilsTest.java
new file mode 100644
index 0000000..e22ae12
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/LocationConfigUtilsTest.java
@@ -0,0 +1,156 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.io.File;
+
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.apache.brooklyn.location.core.LocationConfigUtils;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+@Test
+public class LocationConfigUtilsTest {
+
+    // set these system properties differently if needed to fix your tests
+    public static final String SSH_PRIVATE_KEY_FILE_WITH_TILDE = System.getProperty("sshPrivateKey", "~/.ssh/id_rsa");
+    public static final String SSH_PUBLIC_KEY_FILE_WITH_TILDE = System.getProperty("sshPublicKey", "~/.ssh/id_rsa.pub");
+    // these should work as they are on classpath
+    public static final String SSH_PRIVATE_KEY_FILE_WITH_PASSPHRASE = System.getProperty("sshPrivateKeyWithPassphrase", "/brooklyn/util/crypto/sample_rsa_passphrase.pem");
+    public static final String SSH_PRIVATE_KEY_FILE = System.getProperty("sshPrivateKeySample", "/org/apache/brooklyn/location/basic/sample_id_rsa");
+    public static final String SSH_PUBLIC_KEY_FILE = System.getProperty("sshPublicKeySample", "/org/apache/brooklyn/location/basic/sample_id_rsa.pub");
+    
+    public void testPreferPrivateKeyDataOverFile() throws Exception {
+        ConfigBag config = ConfigBag.newInstance();
+        config.put(LocationConfigKeys.PRIVATE_KEY_DATA, "mydata");
+        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE);
+        
+        LocationConfigUtils.OsCredential creds = LocationConfigUtils.getOsCredential(config).doKeyValidation(false);
+        Assert.assertTrue(creds.hasKey());
+        // warnings, as it is malformed
+        Assert.assertFalse(creds.getWarningMessages().isEmpty());
+
+        String data = creds.getPrivateKeyData();
+        assertEquals(data, "mydata");
+    }
+
+    @Test(expectedExceptions=IllegalStateException.class)
+    public void testInvalidKeyData() throws Exception {
+        ConfigBag config = ConfigBag.newInstance();
+        config.put(LocationConfigKeys.PRIVATE_KEY_DATA, "mydata");
+        
+        LocationConfigUtils.OsCredential creds = LocationConfigUtils.getOsCredential(config).doKeyValidation(false);
+        Assert.assertTrue(creds.hasKey());
+        Assert.assertFalse(creds.getWarningMessages().isEmpty());
+        
+        creds.checkNoErrors();
+    }
+
+    public void testPreferPublicKeyDataOverFileAndNoPrivateKeyRequired() throws Exception {
+        ConfigBag config = ConfigBag.newInstance();
+        config.put(LocationConfigKeys.PUBLIC_KEY_DATA, "mydata");
+        config.put(LocationConfigKeys.PUBLIC_KEY_FILE, SSH_PUBLIC_KEY_FILE);
+        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, "");
+        
+        LocationConfigUtils.OsCredential creds = LocationConfigUtils.getOsCredential(config);
+        String data = creds.getPublicKeyData();
+        assertEquals(data, "mydata");
+        Assert.assertNull(creds.getPreferredCredential());
+        Assert.assertFalse(creds.hasPassword());
+        Assert.assertFalse(creds.hasKey());
+        // and not even any warnings here
+        Assert.assertTrue(creds.getWarningMessages().isEmpty());
+    }
+    
+    @Test(groups="Integration")  // requires ~/.ssh/id_rsa
+    public void testReadsPrivateKeyFileWithTildePath() throws Exception {
+        ConfigBag config = ConfigBag.newInstance();
+        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE_WITH_TILDE);
+
+        // don't mind if it has a passphrase
+        String data = LocationConfigUtils.getOsCredential(config).doKeyValidation(false).getPreferredCredential();
+        assertTrue(data != null && data.length() > 0);
+    }
+    
+    @Test(groups="Integration")
+    public void testReadsPrivateKeyFileWithPassphrase() throws Exception {
+        ConfigBag config = ConfigBag.newInstance();
+        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE_WITH_PASSPHRASE);
+
+        LocationConfigUtils.OsCredential cred = LocationConfigUtils.getOsCredential(config).doKeyValidation(false);
+        String data = cred.getPreferredCredential();
+        assertTrue(data != null && data.length() > 0);
+        Assert.assertFalse(data.isEmpty());
+        
+        cred.doKeyValidation(true);
+        try {
+            cred.checkNoErrors();
+            Assert.fail("check should fail as passphrase needed");
+        } catch (IllegalStateException exception) {
+        }
+
+        config.put(LocationConfigKeys.PRIVATE_KEY_PASSPHRASE, "passphrase");
+        cred.checkNoErrors();
+        
+        config.put(LocationConfigKeys.PRIVATE_KEY_PASSPHRASE, "wrong_passphrase");
+        try {
+            cred.checkNoErrors();
+            Assert.fail("check should fail as passphrase needed");
+        } catch (IllegalStateException exception) {
+        }
+    }
+    
+    public void testReadsPrivateKeyFileWithMultipleColonSeparatedFilesWithGoodLast() throws Exception {
+        ConfigBag config = ConfigBag.newInstance();
+        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, "/path/does/not/exist"+File.pathSeparator+SSH_PRIVATE_KEY_FILE);
+        
+        String data = LocationConfigUtils.getOsCredential(config).getPreferredCredential();
+        assertTrue(data != null && data.length() > 0);
+    }
+    
+    public void testReadsPrivateKeyFileWithMultipleColonSeparatedFilesWithGoodFirst() throws Exception {
+        ConfigBag config = ConfigBag.newInstance();
+        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE+File.pathSeparator+"/path/does/not/exist");
+
+        String data = LocationConfigUtils.getOsCredential(config).getPreferredCredential();
+        assertTrue(data != null && data.length() > 0);
+    }
+    
+    @Test(groups="Integration")  // requires ~/.ssh/id_rsa
+    public void testReadsPublicKeyFileWithTildePath() throws Exception {
+        ConfigBag config = ConfigBag.newInstance();
+        config.put(LocationConfigKeys.PUBLIC_KEY_FILE, SSH_PUBLIC_KEY_FILE_WITH_TILDE);
+        
+        // don't mind if it has a passphrase
+        String data = LocationConfigUtils.getOsCredential(config).doKeyValidation(false).getPublicKeyData();
+        assertTrue(data != null && data.length() > 0);
+    }
+    
+    public void testInfersPublicKeyFileFromPrivateKeyFile() throws Exception {
+        ConfigBag config = ConfigBag.newInstance();
+        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE);
+        
+        String data = LocationConfigUtils.getOsCredential(config).getPublicKeyData();
+        assertTrue(data != null && data.length() > 0);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/LocationExtensionsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/LocationExtensionsTest.java b/core/src/test/java/org/apache/brooklyn/location/core/LocationExtensionsTest.java
new file mode 100644
index 0000000..3b784e2
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/LocationExtensionsTest.java
@@ -0,0 +1,187 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class LocationExtensionsTest {
+
+    public static class ConcreteLocation extends AbstractLocation {
+        private static final long serialVersionUID = 2407231019435442876L;
+
+        public ConcreteLocation() {
+            super();
+        }
+    }
+
+    public interface MyExtension {
+    }
+    
+    public static class MyExtensionImpl implements MyExtension {
+    }
+    
+    private ManagementContext mgmt;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        mgmt = new LocalManagementContextForTests();
+    }
+    
+    @AfterMethod(alwaysRun = true)
+    public void tearDown(){
+        if (mgmt!=null) Entities.destroyAll(mgmt);
+    }
+
+    private ConcreteLocation createConcrete() {
+        return mgmt.getLocationManager().createLocation(LocationSpec.create(ConcreteLocation.class));
+    }
+    
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    private ConcreteLocation createConcrete(Class<?> extensionType, Object extension) {
+        // this cast is needed to make IntelliJ happy
+        return (ConcreteLocation) mgmt.getLocationManager().createLocation(LocationSpec.create(ConcreteLocation.class).extension((Class)extensionType, extension));
+    }
+    
+    @Test
+    public void testHasExtensionWhenMissing() {
+        Location loc = createConcrete();
+        assertFalse(loc.hasExtension(MyExtension.class));
+    }
+
+    @Test
+    public void testWhenExtensionPresent() {
+        MyExtension extension = new MyExtensionImpl();
+        ConcreteLocation loc = createConcrete();
+        loc.addExtension(MyExtension.class, extension);
+        
+        assertTrue(loc.hasExtension(MyExtension.class));
+        assertEquals(loc.getExtension(MyExtension.class), extension);
+    }
+
+    @Test
+    public void testAddExtensionThroughLocationSpec() {
+        MyExtension extension = new MyExtensionImpl();
+        Location loc = createConcrete(MyExtension.class, extension);
+        
+        assertTrue(loc.hasExtension(MyExtension.class));
+        assertEquals(loc.getExtension(MyExtension.class), extension);
+    }
+
+    @Test
+    public void testGetExtensionWhenMissing() {
+        Location loc = createConcrete();
+
+        try {
+            loc.getExtension(MyExtension.class);
+            fail();
+        } catch (IllegalArgumentException e) {
+            // success
+        }
+        
+        try {
+            loc.getExtension(null);
+            fail();
+        } catch (NullPointerException e) {
+            // success
+        }
+    }
+
+    @Test
+    public void testWhenExtensionDifferent() {
+        MyExtension extension = new MyExtensionImpl();
+        ConcreteLocation loc = createConcrete();
+        loc.addExtension(MyExtension.class, extension);
+        
+        assertFalse(loc.hasExtension(Object.class));
+        
+        try {
+            loc.getExtension(Object.class);
+            fail();
+        } catch (IllegalArgumentException e) {
+            // success
+        }
+    }
+
+    @Test
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public void testAddExtensionIllegally() {
+        MyExtension extension = new MyExtensionImpl();
+        ConcreteLocation loc = createConcrete();
+        
+        try {
+            loc.addExtension((Class)MyExtension.class, "not an extension");
+            fail();
+        } catch (IllegalArgumentException e) {
+            // success
+        }
+        
+        try {
+            loc.addExtension(MyExtension.class, null);
+            fail();
+        } catch (NullPointerException e) {
+            // success
+        }
+        
+        try {
+            loc.addExtension(null, extension);
+            fail();
+        } catch (NullPointerException e) {
+            // success
+        }
+    }
+
+    @Test
+    public void testAddExtensionThroughLocationSpecIllegally() {
+        MyExtension extension = new MyExtensionImpl();
+        
+        try {
+            Location loc = createConcrete(MyExtension.class, "not an extension");
+            fail("loc="+loc);
+        } catch (IllegalArgumentException e) {
+            // success
+        }
+        
+        try {
+            Location loc = createConcrete(MyExtension.class, null);
+            fail("loc="+loc);
+        } catch (NullPointerException e) {
+            // success
+        }
+        
+        try {
+            Location loc = createConcrete(null, extension);
+            fail("loc="+loc);
+        } catch (NullPointerException e) {
+            // success
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/LocationManagementTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/LocationManagementTest.java b/core/src/test/java/org/apache/brooklyn/location/core/LocationManagementTest.java
new file mode 100644
index 0000000..78a8cfc
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/LocationManagementTest.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertSame;
+import static org.testng.Assert.assertTrue;
+
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.mgmt.LocationManager;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+
+public class LocationManagementTest extends BrooklynAppUnitTestSupport {
+
+    private LocationManager locationManager;
+
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        locationManager = mgmt.getLocationManager();
+    }
+    
+    @Test
+    public void testCreateLocationUsingSpec() {
+        SshMachineLocation loc = locationManager.createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure("address", "1.2.3.4"));
+        
+        assertEquals(loc.getAddress().getHostAddress(), "1.2.3.4");
+        assertSame(locationManager.getLocation(loc.getId()), loc);
+    }
+    
+    @Test
+    public void testCreateLocationUsingResolver() {
+        String spec = "byon:(hosts=\"1.1.1.1\")";
+        FixedListMachineProvisioningLocation<SshMachineLocation> loc = (FixedListMachineProvisioningLocation<SshMachineLocation>) mgmt.getLocationRegistry().resolve(spec);
+        SshMachineLocation machine = Iterables.getOnlyElement(loc.getAllMachines());
+        
+        assertSame(locationManager.getLocation(loc.getId()), loc);
+        assertSame(locationManager.getLocation(machine.getId()), machine);
+    }
+    
+    @Test
+    public void testChildrenOfManagedLocationAutoManaged() {
+        String spec = "byon:(hosts=\"1.1.1.1\")";
+        FixedListMachineProvisioningLocation<SshMachineLocation> loc = (FixedListMachineProvisioningLocation<SshMachineLocation>) mgmt.getLocationRegistry().resolve(spec);
+        SshMachineLocation machine = new SshMachineLocation(ImmutableMap.of("address", "1.2.3.4"));
+
+        loc.addChild(machine);
+        assertSame(locationManager.getLocation(machine.getId()), machine);
+        assertTrue(machine.isManaged());
+        
+        loc.removeChild(machine);
+        assertNull(locationManager.getLocation(machine.getId()));
+        assertFalse(machine.isManaged());
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/LocationPredicatesTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/LocationPredicatesTest.java b/core/src/test/java/org/apache/brooklyn/location/core/LocationPredicatesTest.java
new file mode 100644
index 0000000..d63aaac
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/LocationPredicatesTest.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.core.LocationPredicates;
+import org.apache.brooklyn.location.core.Locations;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class LocationPredicatesTest {
+
+    private LocalManagementContext managementContext;
+    private LocalhostMachineProvisioningLocation loc;
+    private SshMachineLocation childLoc;
+    private Location grandchildLoc;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        managementContext = LocalManagementContextForTests.newInstance();
+        loc = (LocalhostMachineProvisioningLocation) managementContext.getLocationRegistry().resolve("localhost:(name=mydisplayname)");
+        childLoc = loc.obtain();
+        grandchildLoc = managementContext.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class).parent(childLoc));
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (managementContext != null) Entities.destroyAll(managementContext);
+    }
+    
+    @Test
+    public void testIdEqualTo() throws Exception {
+        assertTrue(LocationPredicates.idEqualTo(loc.getId()).apply(loc));
+        assertFalse(LocationPredicates.idEqualTo("wrongid").apply(loc));
+    }
+    
+    @Test
+    public void testConfigEqualTo() throws Exception {
+        loc.setConfig(TestEntity.CONF_NAME, "myname");
+        assertTrue(LocationPredicates.configEqualTo(TestEntity.CONF_NAME, "myname").apply(loc));
+        assertFalse(LocationPredicates.configEqualTo(TestEntity.CONF_NAME, "wrongname").apply(loc));
+    }
+    
+    @Test
+    public void testDisplayNameEqualTo() throws Exception {
+        assertTrue(LocationPredicates.displayNameEqualTo("mydisplayname").apply(loc));
+        assertFalse(LocationPredicates.displayNameEqualTo("wrongname").apply(loc));
+    }
+    
+    @Test
+    public void testIsChildOf() throws Exception {
+        assertTrue(LocationPredicates.isChildOf(loc).apply(childLoc));
+        assertFalse(LocationPredicates.isChildOf(loc).apply(loc));
+        assertFalse(LocationPredicates.isChildOf(childLoc).apply(loc));
+    }
+    
+    @Test
+    public void testIsDescendantOf() throws Exception {
+        assertTrue(LocationPredicates.isDescendantOf(loc).apply(grandchildLoc));
+        assertTrue(LocationPredicates.isDescendantOf(loc).apply(childLoc));
+        assertFalse(LocationPredicates.isDescendantOf(loc).apply(loc));
+        assertFalse(LocationPredicates.isDescendantOf(childLoc).apply(loc));
+    }
+    
+    @Test
+    public void testManaged() throws Exception {
+        // TODO get exception in LocalhostMachineProvisioningLocation.removeChild because childLoc is "in use";
+        // this happens from the call to unmanage(loc), which first unmanaged the children.
+        loc.release(childLoc);
+        
+        assertTrue(LocationPredicates.managed().apply(loc));
+        Locations.unmanage(loc);
+        assertFalse(LocationPredicates.managed().apply(loc));
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/LocationPropertiesFromBrooklynPropertiesTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/LocationPropertiesFromBrooklynPropertiesTest.java b/core/src/test/java/org/apache/brooklyn/location/core/LocationPropertiesFromBrooklynPropertiesTest.java
new file mode 100644
index 0000000..f9e12ab
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/LocationPropertiesFromBrooklynPropertiesTest.java
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static org.testng.Assert.assertEquals;
+
+import java.util.Map;
+
+import org.apache.brooklyn.location.core.LocationPropertiesFromBrooklynProperties;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.Maps;
+
+public class LocationPropertiesFromBrooklynPropertiesTest {
+
+    private LocationPropertiesFromBrooklynProperties parser;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        parser = new LocationPropertiesFromBrooklynProperties();
+    }
+    
+    @Test
+    public void testExtractProviderProperties() throws Exception {
+        String provider = "myprovider";
+        String namedLocation = null;
+        
+        Map<String, String> properties = Maps.newLinkedHashMap();
+        
+        // prefer those in "named" over everything else
+        properties.put("brooklyn.location.myprovider.privateKeyFile", "privateKeyFile-inProviderSpecific");
+        properties.put("brooklyn.location.privateKeyFile", "privateKeyFile-inLocationGeneric");
+
+        // prefer location-generic if nothing else
+        properties.put("brooklyn.location.publicKeyFile", "publicKeyFile-inLocationGeneric");
+        
+        Map<String, Object> conf = parser.getLocationProperties(provider, namedLocation, properties);
+        assertEquals(conf.get("privateKeyFile"), "privateKeyFile-inProviderSpecific");
+        assertEquals(conf.get("publicKeyFile"), "publicKeyFile-inLocationGeneric");
+    }
+
+    @Test
+    public void testExtractNamedLocationProperties() throws Exception {
+        String provider = "myprovider";
+        String namedLocation = "mynamed";
+        
+        Map<String, String> properties = Maps.newLinkedHashMap();
+        
+        properties.put("brooklyn.location.named.mynamed", "myprovider");
+        
+        // prefer those in "named" over everything else
+        properties.put("brooklyn.location.named.mynamed.privateKeyFile", "privateKeyFile-inNamed");
+        properties.put("brooklyn.location.myprovider.privateKeyFile", "privateKeyFile-inProviderSpecific");
+        properties.put("brooklyn.location.privateKeyFile", "privateKeyFile-inGeneric");
+
+        // prefer those in provider-specific over generic
+        properties.put("brooklyn.location.myprovider.publicKeyFile", "publicKeyFile-inProviderSpecific");
+        properties.put("brooklyn.location.publicKeyFile", "publicKeyFile-inGeneric");
+
+        // prefer location-generic if nothing else
+        properties.put("brooklyn.location.privateKeyData", "privateKeyData-inGeneric");
+
+        Map<String, Object> conf = parser.getLocationProperties(provider, namedLocation, properties);
+        assertEquals(conf.get("privateKeyFile"), "privateKeyFile-inNamed");
+        assertEquals(conf.get("publicKeyFile"), "publicKeyFile-inProviderSpecific");
+        assertEquals(conf.get("privateKeyData"), "privateKeyData-inGeneric");
+    }
+
+    @Test
+    public void testConvertsDeprecatedFormats() throws Exception {
+        String provider = "myprovider";
+        String namedLocation = "mynamed";
+        
+        Map<String, String> properties = Maps.newLinkedHashMap();
+        
+        properties.put("brooklyn.location.named.mynamed", "myprovider");
+        
+        // prefer those in "named" over everything else
+        properties.put("brooklyn.location.named.mynamed.private-key-file", "privateKeyFile-inNamed");
+        properties.put("brooklyn.location.myprovider.public-key-file", "publicKeyFile-inProviderSpecific");
+        properties.put("brooklyn.location.private-key-data", "privateKeyData-inGeneric");
+
+        Map<String, Object> conf = parser.getLocationProperties(provider, namedLocation, properties);
+        assertEquals(conf.get("privateKeyFile"), "privateKeyFile-inNamed");
+        assertEquals(conf.get("publicKeyFile"), "publicKeyFile-inProviderSpecific");
+        assertEquals(conf.get("privateKeyData"), "privateKeyData-inGeneric");
+    }
+    
+
+    @Test
+    public void testThrowsIfProviderDoesNotMatchNamed() throws Exception {
+        String provider = "myprovider";
+        String namedLocation = "mynamed";
+        
+        Map<String, String> properties = Maps.newLinkedHashMap();
+        
+        properties.put("brooklyn.location.named.mynamed", "completelydifferent");
+
+        try {
+            Map<String, Object> conf = parser.getLocationProperties(provider, namedLocation, properties);
+        } catch (IllegalStateException e) {
+            if (!e.toString().contains("Conflicting configuration")) throw e;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/LocationRegistryTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/LocationRegistryTest.java b/core/src/test/java/org/apache/brooklyn/location/core/LocationRegistryTest.java
new file mode 100644
index 0000000..8520403
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/LocationRegistryTest.java
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationDefinition;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.core.BasicLocationRegistry;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.Test;
+
+public class LocationRegistryTest {
+    
+    private static final Logger log = LoggerFactory.getLogger(LocationRegistryTest.class);
+    
+    private LocalManagementContext mgmt;
+    private LocationDefinition locdef;
+
+    @AfterMethod(alwaysRun = true)
+    public void tearDown(){
+        if (mgmt != null) Entities.destroyAll(mgmt);
+    }
+
+    @Test
+    public void testNamedLocationsPropertyDefinedLocations() {
+        BrooklynProperties properties = BrooklynProperties.Factory.newEmpty();
+        properties.put("brooklyn.location.named.foo", "byon:(hosts=\"root@192.168.1.{1,2,3,4}\")");
+        properties.put("brooklyn.location.named.foo.privateKeyFile", "~/.ssh/foo.id_rsa");
+        mgmt = LocalManagementContextForTests.newInstance(properties);
+        log.info("foo properties gave defined locations: "+mgmt.getLocationRegistry().getDefinedLocations());
+        locdef = mgmt.getLocationRegistry().getDefinedLocationByName("foo");
+        Assert.assertNotNull(locdef, "Expected 'foo' location; but had "+mgmt.getLocationRegistry().getDefinedLocations());
+        Assert.assertEquals(locdef.getConfig().get("privateKeyFile"), "~/.ssh/foo.id_rsa");
+    }
+    
+    @Test(dependsOnMethods="testNamedLocationsPropertyDefinedLocations")
+    public void testResolvesByNamedAndId() {
+        BrooklynProperties properties = BrooklynProperties.Factory.newEmpty();
+        properties.put("brooklyn.location.named.foo", "byon:(hosts=\"root@192.168.1.{1,2,3,4}\")");
+        properties.put("brooklyn.location.named.foo.privateKeyFile", "~/.ssh/foo.id_rsa");
+        mgmt = LocalManagementContextForTests.newInstance(properties);
+
+        locdef = mgmt.getLocationRegistry().getDefinedLocationByName("foo");
+        log.info("testResovlesBy has defined locations: "+mgmt.getLocationRegistry().getDefinedLocations());
+        
+        Location l = mgmt.getLocationRegistry().resolve("named:foo");
+        Assert.assertNotNull(l);
+        Assert.assertEquals(l.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE), "~/.ssh/foo.id_rsa");
+        
+        l = mgmt.getLocationRegistry().resolve("foo");
+        Assert.assertNotNull(l);
+        Assert.assertEquals(l.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE), "~/.ssh/foo.id_rsa");
+        
+        l = mgmt.getLocationRegistry().resolve("id:"+locdef.getId());
+        Assert.assertNotNull(l);
+        Assert.assertEquals(l.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE), "~/.ssh/foo.id_rsa");
+        
+        l = mgmt.getLocationRegistry().resolve(locdef.getId());
+        Assert.assertNotNull(l);
+        Assert.assertEquals(l.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE), "~/.ssh/foo.id_rsa");
+    }
+
+    @Test
+    public void testLocationGetsDisplayName() {
+        BrooklynProperties properties = BrooklynProperties.Factory.newEmpty();
+        properties.put("brooklyn.location.named.foo", "byon:(hosts=\"root@192.168.1.{1,2,3,4}\")");
+        properties.put("brooklyn.location.named.foo.displayName", "My Foo");
+        mgmt = LocalManagementContextForTests.newInstance(properties);
+        Location l = mgmt.getLocationRegistry().resolve("foo");
+        Assert.assertEquals(l.getDisplayName(), "My Foo");
+    }
+    
+    @Test
+    public void testLocationGetsDefaultDisplayName() {
+        BrooklynProperties properties = BrooklynProperties.Factory.newEmpty();
+        properties.put("brooklyn.location.named.foo", "byon:(hosts=\"root@192.168.1.{1,2,3,4}\")");
+        mgmt = LocalManagementContextForTests.newInstance(properties);
+        Location l = mgmt.getLocationRegistry().resolve("foo");
+        Assert.assertNotNull(l.getDisplayName());
+        Assert.assertTrue(l.getDisplayName().startsWith(FixedListMachineProvisioningLocation.class.getSimpleName()), "name="+l.getDisplayName());
+        // TODO currently it gives default name; it would be nice to use 'foo', 
+        // or at least to have access to the spec (and use it e.g. in places such as DynamicFabric)
+        // Assert.assertEquals(l.getDisplayName(), "foo");
+    }
+    
+    @Test
+    public void testSetupForTesting() {
+        mgmt = LocalManagementContextForTests.newInstance();
+        BasicLocationRegistry.setupLocationRegistryForTesting(mgmt);
+        Assert.assertNotNull(mgmt.getLocationRegistry().getDefinedLocationByName("localhost"));
+    }
+
+    @Test
+    public void testCircularReference() {
+        BrooklynProperties properties = BrooklynProperties.Factory.newEmpty();
+        properties.put("brooklyn.location.named.bar", "named:bar");
+        mgmt = LocalManagementContextForTests.newInstance(properties);
+        log.info("bar properties gave defined locations: "+mgmt.getLocationRegistry().getDefinedLocations());
+        boolean resolved = false;
+        try {
+            mgmt.getLocationRegistry().resolve("bar");
+            resolved = true;
+        } catch (IllegalStateException e) {
+            //expected
+            log.info("bar properties correctly caught circular reference: "+e);
+        }
+        if (resolved)
+            // probably won't happen, if test fails will loop endlessly above
+            Assert.fail("Circular reference resolved location");
+    }
+
+    protected boolean findLocationMatching(String regex) {
+        for (LocationDefinition d: mgmt.getLocationRegistry().getDefinedLocations().values()) {
+            if (d.getName()!=null && d.getName().matches(regex)) return true;
+        }
+        return false;
+    }
+    
+    @Test
+    public void testLocalhostEnabled() {
+        BrooklynProperties properties = BrooklynProperties.Factory.newEmpty();
+        properties.put("brooklyn.location.localhost.enabled", true);
+        mgmt = LocalManagementContextForTests.newInstance(properties);
+        Assert.assertTrue( findLocationMatching("localhost") );
+    }
+
+    @Test
+    public void testLocalhostDisabled() {
+        BrooklynProperties properties = BrooklynProperties.Factory.newEmpty();
+        properties.put("brooklyn.location.localhost.enabled", false);
+        mgmt = LocalManagementContextForTests.newInstance(properties);
+        log.info("RESOLVERS: "+mgmt.getLocationRegistry().getDefinedLocations());
+        log.info("DEFINED LOCATIONS: "+mgmt.getLocationRegistry().getDefinedLocations());
+        Assert.assertFalse( findLocationMatching("localhost") );
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/MachineDetailsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/MachineDetailsTest.java b/core/src/test/java/org/apache/brooklyn/location/core/MachineDetailsTest.java
new file mode 100644
index 0000000..9a02212
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/MachineDetailsTest.java
@@ -0,0 +1,83 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
+
+import java.util.Arrays;
+
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineDetails;
+import org.apache.brooklyn.api.location.OsDetails;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.core.BasicMachineDetails;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class MachineDetailsTest {
+
+    private static final Logger LOG = LoggerFactory.getLogger(MachineDetailsTest.class);
+
+    TestApplication app;
+    ManagementContext mgmt;
+    SshMachineLocation host;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setup() throws Exception {
+        app = TestApplication.Factory.newManagedInstanceForTests();
+        mgmt = app.getManagementContext();
+
+        LocalhostMachineProvisioningLocation localhost = mgmt.getLocationManager().createLocation(
+                LocationSpec.create(LocalhostMachineProvisioningLocation.class));
+        host = localhost.obtain();
+        app.start(Arrays.asList(host));
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (mgmt != null) Entities.destroyAll(mgmt);
+        mgmt = null;
+    }
+
+    @Test(groups = "Integration")
+    public void testGetMachineDetails() {
+        Task<BasicMachineDetails> detailsTask = app.getExecutionContext().submit(
+                BasicMachineDetails.taskForSshMachineLocation(host));
+        MachineDetails machine = detailsTask.getUnchecked();
+        LOG.info("Found the following on localhost: {}", machine);
+        assertNotNull(machine);
+        OsDetails details = machine.getOsDetails();
+        assertNotNull(details);
+        assertNotNull(details.getArch());
+        assertNotNull(details.getName());
+        assertNotNull(details.getVersion());
+        assertFalse(details.getArch().startsWith("architecture:"), "architecture prefix not removed from details");
+        assertFalse(details.getName().startsWith("name:"), "name prefix not removed from details");
+        assertFalse(details.getVersion().startsWith("version:"), "version prefix not removed from details");
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/MultiLocationRebindTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/MultiLocationRebindTest.java b/core/src/test/java/org/apache/brooklyn/location/core/MultiLocationRebindTest.java
new file mode 100644
index 0000000..98d50a3
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/MultiLocationRebindTest.java
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import java.io.File;
+import java.util.List;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.cloud.AvailabilityZoneExtension;
+import org.apache.brooklyn.location.core.MultiLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.collections.MutableSet;
+import org.apache.brooklyn.util.net.Networking;
+import org.apache.brooklyn.util.os.Os;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Function;
+import com.google.common.base.Predicates;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+
+public class MultiLocationRebindTest {
+
+    private ClassLoader classLoader = getClass().getClassLoader();
+    private ManagementContext origManagementContext;
+    private ManagementContext newManagementContext;
+    private File mementoDir;
+    
+    private TestApplication origApp;
+    private TestApplication newApp;
+    private SshMachineLocation mac1a;
+    private SshMachineLocation mac2a;
+    private FixedListMachineProvisioningLocation<SshMachineLocation> loc1;
+    private FixedListMachineProvisioningLocation<SshMachineLocation> loc2;
+    private MultiLocation<SshMachineLocation> multiLoc;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        mementoDir = Os.newTempDir(getClass());
+        origManagementContext = RebindTestUtils.newPersistingManagementContext(mementoDir, classLoader, 1);
+        origApp = ApplicationBuilder.newManagedApp(EntitySpec.create(TestApplication.class), origManagementContext);
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (origManagementContext != null) Entities.destroyAll(origManagementContext);
+        if (newApp != null) Entities.destroyAll(newApp.getManagementContext());
+        if (newManagementContext != null) Entities.destroyAll(newManagementContext);
+        if (mementoDir != null) RebindTestUtils.deleteMementoDir(mementoDir);
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testRebindsMultiLocation() throws Exception {
+        mac1a = origManagementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .displayName("mac1a")
+                .configure("address", Networking.getInetAddressWithFixedName("1.1.1.1")));
+        mac2a = origManagementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .displayName("mac2a")
+                .configure("address", Networking.getInetAddressWithFixedName("1.1.1.3")));
+        loc1 = origManagementContext.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
+                .displayName("loc1")
+                .configure("machines", MutableSet.of(mac1a)));
+        loc2 = origManagementContext.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
+                .displayName("loc2")
+                .configure("machines", MutableSet.of(mac2a)));
+        multiLoc = origManagementContext.getLocationManager().createLocation(LocationSpec.create(MultiLocation.class)
+                        .displayName("multiLoc")
+                        .configure("subLocations", ImmutableList.of(loc1, loc2)));
+        
+        newApp = rebind();
+        newManagementContext = newApp.getManagementContext();
+        
+        MultiLocation newMultiLoc = (MultiLocation) Iterables.find(newManagementContext.getLocationManager().getLocations(), Predicates.instanceOf(MultiLocation.class));
+        AvailabilityZoneExtension azExtension = newMultiLoc.getExtension(AvailabilityZoneExtension.class);
+        List<Location> newSublLocs = azExtension.getAllSubLocations();
+        Iterable<String> newSubLocNames = Iterables.transform(newSublLocs, new Function<Location, String>() {
+            @Override public String apply(Location input) {
+                return (input == null) ? null : input.getDisplayName();
+            }});
+        Asserts.assertEqualsIgnoringOrder(newSubLocNames, ImmutableList.of("loc1", "loc2"));
+    }
+    
+    private TestApplication rebind() throws Exception {
+        return rebind(true);
+    }
+    
+    private TestApplication rebind(boolean checkSerializable) throws Exception {
+        RebindTestUtils.waitForPersisted(origApp);
+        if (checkSerializable) {
+            RebindTestUtils.checkCurrentMementoSerializable(origApp);
+        }
+        return (TestApplication) RebindTestUtils.rebind(mementoDir, getClass().getClassLoader());
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/MultiLocationResolverTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/MultiLocationResolverTest.java b/core/src/test/java/org/apache/brooklyn/location/core/MultiLocationResolverTest.java
new file mode 100644
index 0000000..42cebc8
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/MultiLocationResolverTest.java
@@ -0,0 +1,203 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
+import java.net.InetAddress;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.cloud.AvailabilityZoneExtension;
+import org.apache.brooklyn.location.core.LocationPredicates;
+import org.apache.brooklyn.location.core.MultiLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Objects;
+import com.google.common.base.Optional;
+import com.google.common.base.Predicate;
+import com.google.common.base.Predicates;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+
+public class MultiLocationResolverTest {
+
+    private BrooklynProperties brooklynProperties;
+    private LocalManagementContext managementContext;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        managementContext = LocalManagementContextForTests.newInstance();
+        brooklynProperties = managementContext.getBrooklynProperties();
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (managementContext != null) Entities.destroyAll(managementContext);
+    }
+    
+    @Test
+    public void testThrowsOnInvalid() throws Exception {
+        assertThrowsNoSuchElement("wrongprefix:(hosts=\"1.1.1.1\")");
+        assertThrowsIllegalArgument("single");
+    }
+    
+    @Test
+    public void testThrowsOnInvalidTarget() throws Exception {
+        assertThrowsIllegalArgument("multi:()");
+        assertThrowsIllegalArgument("multi:(wrongprefix:(hosts=\"1.1.1.1\"))");
+        assertThrowsIllegalArgument("multi:(foo:bar)");
+    }
+
+    @Test
+    public void testCleansUpOnInvalidTarget() {
+        assertThrowsNoSuchElement("multi:(targets=\"localhost:(name=testCleansUpOnInvalidTarget),thisNamedLocationDoesNotExist\")");
+        Optional<Location> subtarget = Iterables.tryFind(managementContext.getLocationManager().getLocations(), LocationPredicates.displayNameEqualTo("testCleansUpOnInvalidTarget"));
+        assertFalse(subtarget.isPresent(), "subtarget="+subtarget);
+    }
+
+
+    @Test
+    public void testResolvesSubLocs() {
+        assertMultiLocation(resolve("multi:(targets=localhost)"), 1, ImmutableList.of(Predicates.instanceOf(LocalhostMachineProvisioningLocation.class)));
+        assertMultiLocation(resolve("multi:(targets=\"localhost,localhost\")"), 2, Collections.nCopies(2, Predicates.instanceOf(LocalhostMachineProvisioningLocation.class)));
+        assertMultiLocation(resolve("multi:(targets=\"localhost,localhost,localhost\")"), 3, Collections.nCopies(3, Predicates.instanceOf(LocalhostMachineProvisioningLocation.class)));
+        assertMultiLocation(resolve("multi:(targets=\"localhost:(name=mysubname)\")"), 1, ImmutableList.of(displayNameEqualTo("mysubname")));
+        assertMultiLocation(resolve("multi:(targets=byon:(hosts=\"1.1.1.1\"))"), 1, ImmutableList.of(Predicates.and(
+                Predicates.instanceOf(FixedListMachineProvisioningLocation.class),
+                new Predicate<MachineProvisioningLocation>() {
+                    @Override public boolean apply(MachineProvisioningLocation input) {
+                        SshMachineLocation machine;
+                        try {
+                            machine = (SshMachineLocation) input.obtain(ImmutableMap.of());
+                        } catch (NoMachinesAvailableException e) {
+                            throw Exceptions.propagate(e);
+                        }
+                        try {
+                            String addr = ((SshMachineLocation)machine).getAddress().getHostAddress();
+                            return addr != null && addr.equals("1.1.1.1");
+                        } finally {
+                            input.release(machine);
+                        }
+                    }
+                })));
+        assertMultiLocation(resolve("multi:(targets=\"byon:(hosts=1.1.1.1),byon:(hosts=1.1.1.2)\")"), 2, Collections.nCopies(2, Predicates.instanceOf(FixedListMachineProvisioningLocation.class)));
+    }
+
+    @Test
+    public void testResolvesName() {
+        MultiLocation<SshMachineLocation> multiLoc = resolve("multi:(name=myname,targets=localhost)");
+        assertEquals(multiLoc.getDisplayName(), "myname");
+    }
+    
+    @Test
+    public void testNamedByonLocation() throws Exception {
+        brooklynProperties.put("brooklyn.location.named.mynamed", "multi:(targets=byon:(hosts=\"1.1.1.1\"))");
+        
+        MultiLocation<SshMachineLocation> loc = resolve("named:mynamed");
+        assertEquals(loc.obtain(ImmutableMap.of()).getAddress(), InetAddress.getByName("1.1.1.1"));
+    }
+
+    @Test
+    public void testResolvesFromMap() throws NoMachinesAvailableException {
+        Location l = managementContext.getLocationRegistry().resolve("multi", MutableMap.of("targets", 
+            MutableList.of("localhost", MutableMap.of("byon", MutableMap.of("hosts", "127.0.0.127")))));
+        MultiLocation<?> ml = (MultiLocation<?>)l;
+        Iterator<MachineProvisioningLocation<?>> ci = ml.getSubLocations().iterator();
+        
+        l = ci.next();
+        Assert.assertTrue(l instanceof LocalhostMachineProvisioningLocation, "Expected localhost, got "+l);
+        
+        l = ci.next();
+        Assert.assertTrue(l instanceof FixedListMachineProvisioningLocation, "Expected fixed, got "+l);
+        MachineLocation sl = ((FixedListMachineProvisioningLocation<?>)l).obtain();
+        Assert.assertEquals(sl.getAddress().getHostAddress(), "127.0.0.127");
+        
+        Assert.assertFalse(ci.hasNext());
+    }
+
+
+    private void assertThrowsNoSuchElement(String val) {
+        try {
+            resolve(val);
+            fail();
+        } catch (NoSuchElementException e) {
+            // success
+        }
+    }
+    
+    private void assertThrowsIllegalArgument(String val) {
+        try {
+            resolve(val);
+            fail();
+        } catch (IllegalArgumentException e) {
+            // success
+        }
+    }
+    
+    @SuppressWarnings("unchecked")
+    private MultiLocation<SshMachineLocation> resolve(String val) {
+        return (MultiLocation<SshMachineLocation>) managementContext.getLocationRegistry().resolve(val);
+    }
+    
+    @SuppressWarnings("rawtypes")
+    private void assertMultiLocation(MultiLocation<?> multiLoc, int expectedSize, List<? extends Predicate> expectedSubLocationPredicates) {
+        AvailabilityZoneExtension zones = multiLoc.getExtension(AvailabilityZoneExtension.class);
+        List<Location> subLocs = zones.getAllSubLocations();
+        assertEquals(subLocs.size(), expectedSize, "zones="+subLocs);
+        for (int i = 0; i < subLocs.size(); i++) {
+            MachineProvisioningLocation subLoc = (MachineProvisioningLocation) subLocs.get(i);
+            assertTrue(expectedSubLocationPredicates.get(i).apply(subLoc), "index="+i+"; subLocs="+subLocs);
+        }
+    }
+    
+    public static <T> Predicate<Location> displayNameEqualTo(final T val) {
+        return new Predicate<Location>() {
+            @Override
+            public boolean apply(@Nullable Location input) {
+                return Objects.equal(input.getDisplayName(), val);
+            }
+        };
+    }
+}


[69/72] [abbrv] incubator-brooklyn git commit: updated default catalog with correct package names

Posted by he...@apache.org.
updated default catalog with correct package names


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

Branch: refs/heads/master
Commit: 95277b3abb6f6aad0e8294eabfa93994fc6ddca7
Parents: c45bab0
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Wed Aug 19 10:48:02 2015 +0100
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Wed Aug 19 10:48:02 2015 +0100

----------------------------------------------------------------------
 .../main/resources/brooklyn/default.catalog.bom | 31 ++++++++++----------
 1 file changed, 15 insertions(+), 16 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/95277b3a/usage/cli/src/main/resources/brooklyn/default.catalog.bom
----------------------------------------------------------------------
diff --git a/usage/cli/src/main/resources/brooklyn/default.catalog.bom b/usage/cli/src/main/resources/brooklyn/default.catalog.bom
index 9255913..80cc57a 100644
--- a/usage/cli/src/main/resources/brooklyn/default.catalog.bom
+++ b/usage/cli/src/main/resources/brooklyn/default.catalog.bom
@@ -14,17 +14,16 @@ brooklyn.catalog:
       Provision a server, with customizable provisioning.properties and credentials installed, 
       but no other special software process or scripts executed.
     item:
-      type: brooklyn.entity.basic.EmptySoftwareProcess
+      type: org.apache.brooklyn.entity.software.base.EmptySoftwareProcess
       name: Server
 
   - id: vanilla-bash-server
     description: |
       Provision a server, with customizable provisioning.properties and credentials installed, 
       but no other special software process or scripts executed.
-      The script should be supplied in "launch.command" as per docs on
-      brooklyn.entity.basic.VanillaSoftwareProcess.
+      The script should be supplied in "launch.command" as per docs on VanillaSoftwareProcess.
     item:
-      type: brooklyn.entity.basic.VanillaSoftwareProcess
+      type: org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess
       name: Server with Launch Script (bash)
 
   - id: load-balancer
@@ -42,7 +41,7 @@ brooklyn.catalog:
       Create a cluster of entities, resizable, with starting size "initialSize",
       and using a spec supplied in the "memberSpec" key.
     item:
-      type: brooklyn.entity.group.DynamicCluster
+      type: org.apache.brooklyn.entity.group.DynamicCluster
 
   - id: 1-server-template
     itemType: template
@@ -142,12 +141,12 @@ brooklyn.catalog:
         
         brooklyn.enrichers:
         # publish the URL as a sensor; the GUI will pick this up (main.uri)
-        - type: brooklyn.enricher.basic.Transformer
+        - type: org.apache.brooklyn.sensor.enricher.Transformer
           brooklyn.config:
             uniqueTag: url-generator
             enricher.sourceSensor: host.subnet.hostname
             # use the definition from Attributes class, as it has a RendererHint so GUI makes it a link
-            enricher.targetSensor: $brooklyn:sensor("brooklyn.entity.basic.Attributes", "main.uri")
+            enricher.targetSensor: $brooklyn:sensor("org.apache.brooklyn.entity.core.Attributes", "main.uri")
             enricher.targetValue: 
               $brooklyn:formatString:
               - "http://%s:%s/" 
@@ -246,14 +245,14 @@ brooklyn.catalog:
               
               brooklyn.initializers:
               # make a simple request-count sensor, by counting the number of 200 responses in output.txt
-              - type: brooklyn.entity.software.ssh.SshCommandSensor
+              - type: org.apache.brooklyn.sensor.ssh.SshCommandSensor
                 brooklyn.config:
                   name: reqs.count
                   targetType: int
                   period: 5s
                   command: "cat output.txt | grep HTTP | grep 200 | wc | awk '{print $1}'"
               # and publish the port as a sensor so the load-balancer can pick it up
-              - type:           brooklyn.entity.software.StaticSensor
+              - type:           org.apache.brooklyn.sensor.StaticSensor
                 brooklyn.config:
                   name:         app.port
                   targetType:   int
@@ -261,13 +260,13 @@ brooklyn.catalog:
               
               brooklyn.enrichers:
               # derive reqs.per_sec from reqs.count
-              - type: brooklyn.enricher.basic.YamlTimeWeightedDeltaEnricher
+              - type: org.apache.brooklyn.sensor.enricher.YamlTimeWeightedDeltaEnricher
                 brooklyn.config:
                   enricher.sourceSensor: reqs.count
                   enricher.targetSensor: reqs.per_sec
                   enricher.delta.period: 1s
               # and take an average over 30s for reqs.per_sec into reqs.per_sec.windowed_30s
-              - type: brooklyn.enricher.basic.YamlRollingTimeWindowMeanEnricher
+              - type: org.apache.brooklyn.sensor.enricher.YamlRollingTimeWindowMeanEnricher
                 brooklyn.config:
                   enricher.sourceSensor: reqs.per_sec
                   enricher.targetSensor: reqs.per_sec.windowed_30s
@@ -286,17 +285,17 @@ brooklyn.catalog:
         
         # back at the cluster, create a total per-sec and some per-node average
         brooklyn.enrichers:
-        - type: brooklyn.enricher.basic.Aggregator
+        - type: org.apache.brooklyn.sensor.enricher.Aggregator
           brooklyn.config:
             enricher.sourceSensor: reqs.per_sec
             enricher.targetSensor: reqs.per_sec
             transformation: sum
-        - type: brooklyn.enricher.basic.Aggregator
+        - type: org.apache.brooklyn.sensor.enricher.Aggregator
           brooklyn.config:
             enricher.sourceSensor: reqs.per_sec
             enricher.targetSensor: reqs.per_sec.per_node
             transformation: average
-        - type: brooklyn.enricher.basic.Aggregator
+        - type: org.apache.brooklyn.sensor.enricher.Aggregator
           brooklyn.config:
             enricher.sourceSensor: reqs.per_sec.windowed_30s
             enricher.targetSensor: reqs.per_sec.windowed_30s.per_node
@@ -335,13 +334,13 @@ brooklyn.catalog:
       
       brooklyn.enrichers:
       # publish a few useful info sensors and KPI's to the root of the app
-      - type: brooklyn.enricher.basic.Propagator
+      - type: org.apache.brooklyn.sensor.enricher.Propagator
         brooklyn.config:
           uniqueTag:    propagate-load-balancer-url
           producer:     $brooklyn:entity("load-bal")
           propagating:
           - main.uri
-      - type: brooklyn.enricher.basic.Propagator
+      - type: org.apache.brooklyn.sensor.enricher.Propagator
         brooklyn.config:
           uniqueTag:    propagate-reqs-per-sec
           producer:     $brooklyn:entity("my-web-cluster")


[37/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/AbstractSoftwareProcessSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/AbstractSoftwareProcessSshDriver.java b/software/base/src/main/java/brooklyn/entity/basic/AbstractSoftwareProcessSshDriver.java
deleted file mode 100644
index 74fe155..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/AbstractSoftwareProcessSshDriver.java
+++ /dev/null
@@ -1,658 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import static org.apache.brooklyn.util.JavaGroovyEquivalents.elvis;
-import static org.apache.brooklyn.util.JavaGroovyEquivalents.groovyTruth;
-
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.brooklyn.api.entity.drivers.downloads.DownloadResolver;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.core.BrooklynLogging;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.effector.core.EffectorTasks;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Predicates;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-
-import brooklyn.entity.basic.lifecycle.NaiveScriptRunner;
-import brooklyn.entity.basic.lifecycle.ScriptHelper;
-import brooklyn.entity.software.SshEffectorTasks;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
-import org.apache.brooklyn.util.core.internal.ssh.SshTool;
-import org.apache.brooklyn.util.core.internal.ssh.sshj.SshjTool;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.ssh.BashCommands;
-import org.apache.brooklyn.util.stream.KnownSizeInputStream;
-import org.apache.brooklyn.util.stream.Streams;
-import org.apache.brooklyn.util.text.StringPredicates;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.time.Duration;
-
-/**
- * An abstract SSH implementation of the {@link AbstractSoftwareProcessDriver}.
- *
- * This provides conveniences for clients implementing the install/customize/launch/isRunning/stop lifecycle
- * over SSH.  These conveniences include checking whether software is already installed,
- * creating/using a PID file for some operations, and reading ssh-specific config from the entity
- * to override/augment ssh flags on the session.
- */
-public abstract class AbstractSoftwareProcessSshDriver extends AbstractSoftwareProcessDriver implements NaiveScriptRunner {
-
-    public static final Logger log = LoggerFactory.getLogger(AbstractSoftwareProcessSshDriver.class);
-    public static final Logger logSsh = LoggerFactory.getLogger(BrooklynLogging.SSH_IO);
-
-    // we cache these for efficiency and in case the entity becomes unmanaged
-    private volatile String installDir;
-    private volatile String runDir;
-    private volatile String expandedInstallDir;
-    private final Object installDirSetupMutex = new Object();
-
-    protected volatile DownloadResolver resolver;
-
-    /** include this flag in newScript creation to prevent entity-level flags from being included;
-     * any SSH-specific flags passed to newScript override flags from the entity,
-     * and flags from the entity override flags on the location
-     * (where there aren't conflicts, flags from all three are used however) */
-    public static final String IGNORE_ENTITY_SSH_FLAGS = SshEffectorTasks.IGNORE_ENTITY_SSH_FLAGS.getName();
-
-    public AbstractSoftwareProcessSshDriver(EntityLocal entity, SshMachineLocation machine) {
-        super(entity, machine);
-
-        // FIXME this assumes we own the location, and causes warnings about configuring location after deployment;
-        // better would be to wrap the ssh-execution-provider to supply these flags
-        if (getSshFlags()!=null && !getSshFlags().isEmpty())
-            machine.configure(getSshFlags());
-
-        // ensure these are set using the routines below, not a global ConfigToAttributes.apply()
-        getInstallDir();
-        getRunDir();
-    }
-
-    /** returns location (tighten type, since we know it is an ssh machine location here) */
-    public SshMachineLocation getLocation() {
-        return (SshMachineLocation) super.getLocation();
-    }
-
-    protected void setInstallDir(String installDir) {
-        this.installDir = installDir;
-        entity.setAttribute(SoftwareProcess.INSTALL_DIR, installDir);
-    }
-
-    public String getInstallDir() {
-        if (installDir != null) return installDir;
-
-        String existingVal = getEntity().getAttribute(SoftwareProcess.INSTALL_DIR);
-        if (Strings.isNonBlank(existingVal)) { // e.g. on rebind
-            installDir = existingVal;
-            return installDir;
-        }
-
-        synchronized (installDirSetupMutex) {
-            // previously we looked at sensor value, but we shouldn't as it might have been converted from the config key value
-            // *before* we computed the install label, or that label may have changed since previous install; now force a recompute
-            setInstallLabel();
-
-            // deprecated in 0.7.0 - "brooklyn.dirs.install" is no longer supported
-            Maybe<Object> minstallDir = getEntity().getConfigRaw(SoftwareProcess.INSTALL_DIR, false);
-            if (!minstallDir.isPresent() || minstallDir.get()==null) {
-                String installBasedir = ((EntityInternal)entity).getManagementContext().getConfig().getFirst("brooklyn.dirs.install");
-                if (installBasedir != null) {
-                    log.warn("Using legacy 'brooklyn.dirs.install' setting for "+entity+"; may be removed in future versions.");
-                    setInstallDir(Os.tidyPath(Os.mergePathsUnix(installBasedir, getEntityVersionLabel()+"_"+entity.getId())));
-                    return installDir;
-                }
-            }
-
-            // set it null first so that we force a recompute
-            setInstallDir(null);
-            setInstallDir(Os.tidyPath(ConfigToAttributes.apply(getEntity(), SoftwareProcess.INSTALL_DIR)));
-            return installDir;
-        }
-    }
-
-    protected void setInstallLabel() {
-        if (getEntity().getConfigRaw(SoftwareProcess.INSTALL_UNIQUE_LABEL, false).isPresentAndNonNull()) return;
-        getEntity().setConfig(SoftwareProcess.INSTALL_UNIQUE_LABEL,
-            getEntity().getEntityType().getSimpleName()+
-            (Strings.isNonBlank(getVersion()) ? "_"+getVersion() : "")+
-            (Strings.isNonBlank(getInstallLabelExtraSalt()) ? "_"+getInstallLabelExtraSalt() : "") );
-    }
-
-    /** allows subclasses to return extra salt (ie unique hash)
-     * for cases where install dirs need to be distinct e.g. based on extra plugins being placed in the install dir;
-     * {@link #setInstallLabel()} uses entity-type simple name and version already
-     * <p>
-     * this salt should not be too long and must not contain invalid path chars.
-     * a hash code of other relevant info is not a bad choice.
-     **/
-    protected String getInstallLabelExtraSalt() {
-        return null;
-    }
-
-    protected void setRunDir(String runDir) {
-        this.runDir = runDir;
-        entity.setAttribute(SoftwareProcess.RUN_DIR, runDir);
-    }
-
-    public String getRunDir() {
-        if (runDir != null) return runDir;
-
-        String existingVal = getEntity().getAttribute(SoftwareProcess.RUN_DIR);
-        if (Strings.isNonBlank(existingVal)) { // e.g. on rebind
-            runDir = existingVal;
-            return runDir;
-        }
-
-        // deprecated in 0.7.0
-        Maybe<Object> mRunDir = getEntity().getConfigRaw(SoftwareProcess.RUN_DIR, true);
-        if (!mRunDir.isPresent() || mRunDir.get()==null) {
-            String runBasedir = ((EntityInternal)entity).getManagementContext().getConfig().getFirst("brooklyn.dirs.run");
-            if (runBasedir != null) {
-                log.warn("Using legacy 'brooklyn.dirs.run' setting for "+entity+"; may be removed in future versions.");
-                runDir = Os.mergePathsUnix(runBasedir, entity.getApplication().getId()+"/"+"entities"+"/"+getEntityVersionLabel()+"_"+entity.getId());
-                runDir = Os.tidyPath(runDir);
-                getEntity().setAttribute(SoftwareProcess.RUN_DIR, runDir);
-                return runDir;
-            }
-        }
-
-        setRunDir(Os.tidyPath(ConfigToAttributes.apply(getEntity(), SoftwareProcess.RUN_DIR)));
-        return runDir;
-    }
-
-    public void setExpandedInstallDir(String val) {
-        String oldVal = getEntity().getAttribute(SoftwareProcess.EXPANDED_INSTALL_DIR);
-        if (Strings.isNonBlank(oldVal) && !oldVal.equals(val)) {
-            log.info("Resetting expandedInstallDir (to "+val+" from "+oldVal+") for "+getEntity());
-        }
-
-        expandedInstallDir = val;
-        getEntity().setAttribute(SoftwareProcess.EXPANDED_INSTALL_DIR, val);
-    }
-
-    public String getExpandedInstallDir() {
-        if (expandedInstallDir != null) return expandedInstallDir;
-
-        String existingVal = getEntity().getAttribute(SoftwareProcess.EXPANDED_INSTALL_DIR);
-        if (Strings.isNonBlank(existingVal)) { // e.g. on rebind
-            expandedInstallDir = existingVal;
-            return expandedInstallDir;
-        }
-
-        String untidiedVal = ConfigToAttributes.apply(getEntity(), SoftwareProcess.EXPANDED_INSTALL_DIR);
-        if (Strings.isNonBlank(untidiedVal)) {
-            setExpandedInstallDir(Os.tidyPath(untidiedVal));
-            return expandedInstallDir;
-        } else {
-            throw new IllegalStateException("expandedInstallDir is null; most likely install was not called for "+getEntity());
-        }
-    }
-
-    public SshMachineLocation getMachine() { return getLocation(); }
-    public String getHostname() { return entity.getAttribute(Attributes.HOSTNAME); }
-    public String getAddress() { return entity.getAttribute(Attributes.ADDRESS); }
-    public String getSubnetHostname() { return entity.getAttribute(Attributes.SUBNET_HOSTNAME); }
-    public String getSubnetAddress() { return entity.getAttribute(Attributes.SUBNET_ADDRESS); }
-
-    protected Map<String, Object> getSshFlags() {
-        return SshEffectorTasks.getSshFlags(getEntity(), getMachine());
-    }
-
-    public int execute(String command, String summaryForLogging) {
-        return execute(ImmutableList.of(command), summaryForLogging);
-    }
-
-    public int execute(List<String> script, String summaryForLogging) {
-        return execute(Maps.newLinkedHashMap(), script, summaryForLogging);
-    }
-
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    @Override
-    public int execute(Map flags2, List<String> script, String summaryForLogging) {
-        // TODO replace with SshEffectorTasks.ssh ?; remove the use of flags
-
-        Map flags = Maps.newLinkedHashMap();
-        if (!flags2.containsKey(IGNORE_ENTITY_SSH_FLAGS)) {
-            flags.putAll(getSshFlags());
-        }
-        flags.putAll(flags2);
-        Map<String, String> environment = (Map<String, String>) flags.get("env");
-        if (environment == null) {
-            // Important only to call getShellEnvironment() if env was not supplied; otherwise it
-            // could cause us to resolve config (e.g. block for attributeWhenReady) too early.
-            environment = getShellEnvironment();
-        }
-        if (Tasks.current()!=null) {
-            // attach tags here, as well as in ScriptHelper, because they may have just been read from the driver
-            if (environment!=null) {
-                Tasks.addTagDynamically(BrooklynTaskTags.tagForEnvStream(BrooklynTaskTags.STREAM_ENV, environment));
-            }
-            if (BrooklynTaskTags.stream(Tasks.current(), BrooklynTaskTags.STREAM_STDIN)==null) {
-                Tasks.addTagDynamically(BrooklynTaskTags.tagForStreamSoft(BrooklynTaskTags.STREAM_STDIN,
-                    Streams.byteArrayOfString(Strings.join(script, "\n"))));
-            }
-            if (BrooklynTaskTags.stream(Tasks.current(), BrooklynTaskTags.STREAM_STDOUT)==null) {
-                ByteArrayOutputStream stdout = new ByteArrayOutputStream();
-                Tasks.addTagDynamically(BrooklynTaskTags.tagForStreamSoft(BrooklynTaskTags.STREAM_STDOUT, stdout));
-                ByteArrayOutputStream stderr = new ByteArrayOutputStream();
-                Tasks.addTagDynamically(BrooklynTaskTags.tagForStreamSoft(BrooklynTaskTags.STREAM_STDERR, stderr));
-                flags.put("out", stdout);
-                flags.put("err", stderr);
-            }
-        }
-        if (!flags.containsKey("logPrefix")) flags.put("logPrefix", ""+entity.getId()+"@"+getLocation().getDisplayName());
-        return getMachine().execScript(flags, summaryForLogging, script, environment);
-    }
-
-    @Override
-    public void copyInstallResources() {
-        getLocation().acquireMutex("installing " + elvis(entity, this), "installation lock at host for files and templates");
-        try {
-            super.copyInstallResources();
-        } catch (Exception e) {
-            log.warn("Error copying install resources", e);
-            throw Exceptions.propagate(e);
-        } finally {
-            getLocation().releaseMutex("installing " + elvis(entity, this));
-        }
-    }
-
-    @Override
-    public void runPreInstallCommand(String command) {
-        execute(ImmutableList.of(command), "running pre-install commands");
-    }
-
-    @Override
-    public void runPostInstallCommand(String command) {
-        execute(ImmutableList.of(command), "running post-install commands");
-    }
-
-    @Override
-    public void runPreLaunchCommand(String command) {
-        execute(ImmutableList.of(command), "running pre-launch commands");
-    }
-
-    @Override
-    public void runPostLaunchCommand(String command) {
-        execute(ImmutableList.of(command), "running post-launch commands");
-    }
-
-    /**
-     * The environment variables to be set when executing the commands (for install, run, check running, etc).
-     * @see SoftwareProcess#SHELL_ENVIRONMENT
-     */
-    public Map<String, String> getShellEnvironment() {
-        return Strings.toStringMap(entity.getConfig(SoftwareProcess.SHELL_ENVIRONMENT), "");
-    }
-
-
-    /**
-     * @param sshFlags Extra flags to be used when making an SSH connection to the entity's machine.
-     *                 If the map contains the key {@link #IGNORE_ENTITY_SSH_FLAGS} then only the
-     *                 given flags are used. Otherwise, the given flags are combined with (and take
-     *                 precendence over) the flags returned by {@link #getSshFlags()}.
-     * @param source URI of file to copy, e.g. file://.., http://.., classpath://..
-     * @param target Destination on server, relative to {@link #getRunDir()} if not absolute path
-     * @param createParentDir Whether to create the parent target directory, if it doesn't already exist
-     * @return The exit code of the SSH command run
-     */
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    public int copyResource(Map<Object,Object> sshFlags, String source, String target, boolean createParentDir) {
-        // TODO use SshTasks.put instead, better logging
-        Map flags = Maps.newLinkedHashMap();
-        if (!sshFlags.containsKey(IGNORE_ENTITY_SSH_FLAGS)) {
-            flags.putAll(getSshFlags());
-        }
-        flags.putAll(sshFlags);
-
-        String destination = Os.isAbsolutish(target) ? target : Os.mergePathsUnix(getRunDir(), target);
-
-        if (createParentDir) {
-            // don't use File.separator because it's remote machine's format, rather than local machine's
-            int lastSlashIndex = destination.lastIndexOf("/");
-            String parent = (lastSlashIndex > 0) ? destination.substring(0, lastSlashIndex) : null;
-            if (parent != null) {
-                getMachine().execCommands("createParentDir", ImmutableList.of("mkdir -p "+parent));
-            }
-        }
-
-        int result = getMachine().installTo(resource, flags, source, destination);
-        if (result == 0) {
-            if (log.isDebugEnabled()) {
-                log.debug("Copied file for {}: {} to {} - result {}", new Object[] { entity, source, destination, result });
-            }
-        }
-        return result;
-    }
-
-    /**
-     * Input stream will be closed automatically.
-     * <p>
-     * If using {@link SshjTool} usage, consider using {@link KnownSizeInputStream} to avoid having
-     * to write out stream once to find its size!
-     *
-     * @see #copyResource(Map, String, String) for parameter descriptions.
-     */
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    public int copyResource(Map<Object,Object> sshFlags, InputStream source, String target, boolean createParentDir) {
-        Map flags = Maps.newLinkedHashMap();
-        if (!sshFlags.containsKey(IGNORE_ENTITY_SSH_FLAGS)) {
-            flags.putAll(getSshFlags());
-        }
-        flags.putAll(sshFlags);
-
-        String destination = Os.isAbsolutish(target) ? target : Os.mergePathsUnix(getRunDir(), target);
-
-        if (createParentDir) {
-            // don't use File.separator because it's remote machine's format, rather than local machine's
-            int lastSlashIndex = destination.lastIndexOf("/");
-            String parent = (lastSlashIndex > 0) ? destination.substring(0, lastSlashIndex) : null;
-            if (parent != null) {
-                getMachine().execCommands("createParentDir", ImmutableList.of("mkdir -p "+parent));
-            }
-        }
-
-        // TODO SshMachineLocation.copyTo currently doesn't log warn on non-zero or set blocking details
-        // (because delegated to by installTo, for multiple calls). So do it here for now.
-        int result;
-        String prevBlockingDetails = Tasks.setBlockingDetails("copying resource to server at "+destination);
-        try {
-            result = getMachine().copyTo(flags, source, destination);
-        } finally {
-            Tasks.setBlockingDetails(prevBlockingDetails);
-        }
-
-        if (result == 0) {
-            log.debug("copying stream complete; {} on {}", new Object[] { destination, getMachine() });
-        } else {
-            log.warn("copying stream failed; {} on {}: {}", new Object[] { destination, getMachine(), result });
-        }
-        return result;
-    }
-
-    public void checkNoHostnameBug() {
-        try {
-            ProcessTaskWrapper<Integer> hostnameTask = DynamicTasks.queue(SshEffectorTasks.ssh("echo FOREMARKER; hostname; echo AFTMARKER")).block();
-            String stdout = Strings.getFragmentBetween(hostnameTask.getStdout(), "FOREMARKER", "AFTMARKER");
-            if (hostnameTask.getExitCode() == 0 && Strings.isNonBlank(stdout)) {
-                String hostname = stdout.trim();
-                if (hostname.equals("(none)")) {
-                    String newHostname = "br-"+getEntity().getId().toLowerCase();
-                    log.info("Detected no-hostname bug with hostname "+hostname+" for "+getEntity()+"; renaming "+getMachine()+"  to hostname "+newHostname);
-                    DynamicTasks.queue(SshEffectorTasks.ssh(BashCommands.setHostname(newHostname, null))).block();
-                }
-            } else {
-                log.debug("Hostname could not be determined for location "+EffectorTasks.findSshMachine()+"; not doing no-hostname bug check");
-            }
-        } catch (Exception e) {
-            Exceptions.propagateIfFatal(e);
-            log.warn("Error checking/fixing no-hostname bug (continuing): "+e, e);
-        }
-    }
-
-    public static final String INSTALLING = "installing";
-    public static final String CUSTOMIZING = "customizing";
-    public static final String LAUNCHING = "launching";
-    public static final String CHECK_RUNNING = "check-running";
-    public static final String STOPPING = "stopping";
-    public static final String KILLING = "killing";
-    public static final String RESTARTING = "restarting";
-
-    public static final String PID_FILENAME = "pid.txt";
-
-    /* Flags */
-
-    /**
-     * Use a PID file, created by <em>launching</em>, and reading it for <em>check-running</em>,
-     * <em>stopping</em> and <em>killing</em>. The value can be <em>true</em> or a path to a file to
-     * use; either relative to <em>RUN_DIR</em> or an absolute path.
-     */
-    public static final String USE_PID_FILE = "usePidFile";
-
-    /**
-     * Define the process owner if not the same as the brooklyn user. Both <em>stopping</em> and
-     * <em>killing</em> will sudo to this user before issuing the <code>kill</code> command. Only valid
-     * if <em>USE_PID_FILE</em> is also set.
-     */
-    public static final String PROCESS_OWNER = "processOwner";
-
-    /**
-     * Marks the script as having a customised setup, to prevent the default headers and footers being
-     * added to the list of commands.
-     */
-    public static final String NON_STANDARD_LAYOUT = "nonStandardLayout";
-
-    /**
-     * Prevents creation of the <code>$INSTALL_DIR/BROOKLYN</code> marker file after <em>installing</em>
-     * phase finishes, to allow further installation phases to execute.
-     */
-    public static final String INSTALL_INCOMPLETE = "installIncomplete";
-
-    /**
-     * Enable shell debugging output via <code>set -x</code> prepended to the command header.
-     */
-    public static final String DEBUG = "debug";
-
-    /** Permitted flags for {@link #newScript(Map, String)}. */
-    public static final List<String> VALID_FLAGS =
-            ImmutableList.of(USE_PID_FILE, PROCESS_OWNER, NON_STANDARD_LAYOUT, INSTALL_INCOMPLETE, DEBUG);
-
-    /** @see #newScript(Map, String) */
-    protected ScriptHelper newScript(String phase) {
-        return newScript(Maps.<String, Object>newLinkedHashMap(), phase);
-    }
-
-    /**
-     * Sets up a {@link ScriptHelper} to generate a script that controls the given phase
-     * (<em>check-running</em>, <em>launching</em> etc.) including default header and
-     * footer commands.
-     * <p>
-     * Supported flags:
-     * <ul>
-     * <li><strong>usePidFile</strong> - <em>true</em> or <em>filename</em> to save and retrieve the PID
-     * <li><strong>processOwner</strong> - <em>username</em> that owns the running process
-     * <li><strong>nonStandardLayout</strong> - <em>true</em> to omit all default commands
-     * <li><strong>installIncomplete</strong> - <em>true</em> to prevent marking complete
-     * <li><strong>debug</strong> - <em>true</em> to enable shell debug output
-     * </li>
-     *
-     * @param flags a {@link Map} of flags to control script generation
-     * @param phase the phase to create the ScriptHelper for
-     *
-     * @see #newScript(String)
-     * @see #USE_PID_FILE
-     * @see #PROCESS_OWNER
-     * @see #NON_STANDARD_LAYOUT
-     * @see #INSTALL_INCOMPLETE
-     * @see #DEBUG
-     */
-    protected ScriptHelper newScript(Map<String, ?> flags, String phase) {
-        if (!Entities.isManaged(getEntity()))
-            throw new IllegalStateException(getEntity()+" is no longer managed; cannot create script to run here ("+phase+")");
-
-        if (!Iterables.all(flags.keySet(), StringPredicates.equalToAny(VALID_FLAGS))) {
-            throw new IllegalArgumentException("Invalid flags passed: " + flags);
-        }
-
-        ScriptHelper s = new ScriptHelper(this, phase+" "+elvis(entity,this));
-        if (!groovyTruth(flags.get(NON_STANDARD_LAYOUT))) {
-            if (groovyTruth(flags.get(DEBUG))) {
-                s.header.prepend("set -x");
-            }
-            if (INSTALLING.equals(phase)) {
-                // mutexId should be global because otherwise package managers will contend with each other
-                s.useMutex(getLocation(), "installation lock at host", "installing "+elvis(entity,this));
-                s.header.append(
-                        "export INSTALL_DIR=\""+getInstallDir()+"\"",
-                        "mkdir -p $INSTALL_DIR",
-                        "cd $INSTALL_DIR",
-                        "test -f BROOKLYN && exit 0"
-                        );
-
-                if (!groovyTruth(flags.get(INSTALL_INCOMPLETE))) {
-                    s.footer.append("date > $INSTALL_DIR/BROOKLYN");
-                }
-                // don't set vars during install phase, prevent dependency resolution
-                s.environmentVariablesReset();
-            }
-            if (ImmutableSet.of(CUSTOMIZING, LAUNCHING, CHECK_RUNNING, STOPPING, KILLING, RESTARTING).contains(phase)) {
-                s.header.append(
-                        "export RUN_DIR=\""+getRunDir()+"\"",
-                        "mkdir -p $RUN_DIR",
-                        "cd $RUN_DIR"
-                        );
-            }
-        }
-
-        if (ImmutableSet.of(LAUNCHING, RESTARTING).contains(phase)) {
-            s.failIfBodyEmpty();
-        }
-        if (ImmutableSet.of(STOPPING, KILLING).contains(phase)) {
-            // stopping and killing allowed to have empty body if pid file set
-            if (!groovyTruth(flags.get(USE_PID_FILE)))
-                s.failIfBodyEmpty();
-        }
-        if (ImmutableSet.of(INSTALLING, LAUNCHING).contains(phase)) {
-            s.updateTaskAndFailOnNonZeroResultCode();
-        }
-        if (phase.equalsIgnoreCase(CHECK_RUNNING)) {
-            s.setInessential();
-            s.setTransient();
-            s.setFlag(SshTool.PROP_CONNECT_TIMEOUT, Duration.TEN_SECONDS.toMilliseconds());
-            s.setFlag(SshTool.PROP_SESSION_TIMEOUT, Duration.THIRTY_SECONDS.toMilliseconds());
-            s.setFlag(SshTool.PROP_SSH_TRIES, 1);
-        }
-
-        if (groovyTruth(flags.get(USE_PID_FILE))) {
-            Object usePidFile = flags.get(USE_PID_FILE);
-            String pidFile = (usePidFile instanceof CharSequence ? usePidFile : Os.mergePathsUnix(getRunDir(), PID_FILENAME)).toString();
-            String processOwner = (String) flags.get(PROCESS_OWNER);
-            if (LAUNCHING.equals(phase)) {
-                entity.setAttribute(SoftwareProcess.PID_FILE, pidFile);
-                s.footer.prepend("echo $! > "+pidFile);
-            } else if (CHECK_RUNNING.equals(phase)) {
-                // old method, for supplied service, or entity.id
-                // "ps aux | grep ${service} | grep \$(cat ${pidFile}) > /dev/null"
-                // new way, preferred?
-                if (processOwner != null) {
-                    s.body.append(
-                            BashCommands.sudoAsUser(processOwner, "test -f "+pidFile) + " || exit 1",
-                            "ps -p $(" + BashCommands.sudoAsUser(processOwner, "cat "+pidFile) + ")"
-                    );
-                } else {
-                    s.body.append(
-                            "test -f "+pidFile+" || exit 1",
-                            "ps -p `cat "+pidFile+"`"
-                    );
-                }
-                // no pid, not running; 1 is not running
-                s.requireResultCode(Predicates.or(Predicates.equalTo(0), Predicates.equalTo(1)));
-            } else if (STOPPING.equals(phase)) {
-                if (processOwner != null) {
-                    s.body.append(
-                            "export PID=$(" + BashCommands.sudoAsUser(processOwner, "cat "+pidFile) + ")",
-                            "test -n \"$PID\" || exit 0",
-                            BashCommands.sudoAsUser(processOwner, "kill $PID"),
-                            BashCommands.sudoAsUser(processOwner, "kill -9 $PID"),
-                            BashCommands.sudoAsUser(processOwner, "rm -f "+pidFile)
-                    );
-                } else {
-                    s.body.append(
-                            "export PID=$(cat "+pidFile+")",
-                            "test -n \"$PID\" || exit 0",
-                            "kill $PID",
-                            "kill -9 $PID",
-                            "rm -f "+pidFile
-                    );
-                }
-            } else if (KILLING.equals(phase)) {
-                if (processOwner != null) {
-                    s.body.append(
-                            "export PID=$(" + BashCommands.sudoAsUser(processOwner, "cat "+pidFile) + ")",
-                            "test -n \"$PID\" || exit 0",
-                            BashCommands.sudoAsUser(processOwner, "kill -9 $PID"),
-                            BashCommands.sudoAsUser(processOwner, "rm -f "+pidFile)
-                    );
-                } else {
-                    s.body.append(
-                            "export PID=$(cat "+pidFile+")",
-                            "test -n \"$PID\" || exit 0",
-                            "kill -9 $PID",
-                            "rm -f "+pidFile
-                    );
-                }
-            } else if (RESTARTING.equals(phase)) {
-                if (processOwner != null) {
-                    s.footer.prepend(
-                            BashCommands.sudoAsUser(processOwner, "test -f "+pidFile) + " || exit 1",
-                            "ps -p $(" + BashCommands.sudoAsUser(processOwner, "cat "+pidFile) + ") || exit 1"
-                    );
-                } else {
-                    s.footer.prepend(
-                            "test -f "+pidFile+" || exit 1",
-                            "ps -p $(cat "+pidFile+") || exit 1"
-                    );
-                }
-                // no pid, not running; no process; can't restart, 1 is not running
-            } else {
-                log.warn(USE_PID_FILE + ": script option not valid for " + s.summary);
-            }
-        }
-
-        return s;
-    }
-
-    @Override
-    protected void createDirectory(String directoryName, String summaryForLogging) {
-        DynamicTasks.queue(SshEffectorTasks.ssh("mkdir -p " + directoryName).summary(summaryForLogging)
-                .requiringExitCodeZero()).get();
-    }
-
-    public Set<Integer> getPortsUsed() {
-        Set<Integer> result = Sets.newLinkedHashSet();
-        result.add(22);
-        return result;
-    }
-
-    @Override
-    public void setup() { }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/AbstractSoftwareProcessWinRmDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/AbstractSoftwareProcessWinRmDriver.java b/software/base/src/main/java/brooklyn/entity/basic/AbstractSoftwareProcessWinRmDriver.java
deleted file mode 100644
index 48402bc..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/AbstractSoftwareProcessWinRmDriver.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import java.io.File;
-import java.io.InputStream;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.config.ConfigKey;
-import org.python.core.PyException;
-import org.apache.brooklyn.location.basic.WinRmMachineLocation;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.util.exceptions.ReferenceWithError;
-import org.apache.brooklyn.util.repeat.Repeater;
-import org.apache.brooklyn.util.time.Duration;
-
-import io.cloudsoft.winrm4j.winrm.WinRmToolResponse;
-
-import com.google.api.client.util.Strings;
-import com.google.common.collect.ImmutableList;
-
-public abstract class AbstractSoftwareProcessWinRmDriver extends AbstractSoftwareProcessDriver {
-
-    AttributeSensor<String> WINDOWS_USERNAME = Sensors.newStringSensor("windows.username",
-            "Default Windows username to be used when connecting to the Entity's VM");
-    AttributeSensor<String> WINDOWS_PASSWORD = Sensors.newStringSensor("windows.password",
-            "Default Windows password to be used when connecting to the Entity's VM");
-
-    public AbstractSoftwareProcessWinRmDriver(EntityLocal entity, WinRmMachineLocation location) {
-        super(entity, location);
-        entity.setAttribute(WINDOWS_USERNAME, location.config().get(WinRmMachineLocation.USER));
-        entity.setAttribute(WINDOWS_PASSWORD, location.config().get(WinRmMachineLocation.PASSWORD));
-    }
-
-    @Override
-    public void runPreInstallCommand(String command) {
-        execute(ImmutableList.of(command));
-    }
-
-    @Override
-    public void setup() {
-        // Default to no-op
-    }
-
-    @Override
-    public void runPostInstallCommand(String command) {
-        execute(ImmutableList.of(command));
-    }
-
-    @Override
-    public void runPreLaunchCommand(String command) {
-        execute(ImmutableList.of(command));
-    }
-
-    @Override
-    public void runPostLaunchCommand(String command) {
-        execute(ImmutableList.of(command));
-    }
-
-    @Override
-    public WinRmMachineLocation getLocation() {
-        return (WinRmMachineLocation)super.getLocation();
-    }
-
-    @Override
-    public String getRunDir() {
-        // TODO: This needs to be tidied, and read from the appropriate flags (if set)
-        return "$HOME\\brooklyn-managed-processes\\apps\\" + entity.getApplicationId() + "\\entities\\" + getEntityVersionLabel()+"_"+entity.getId();
-    }
-
-    @Override
-    public String getInstallDir() {
-        // TODO: This needs to be tidied, and read from the appropriate flags (if set)
-        return "$HOME\\brooklyn-managed-processes\\installs\\" + entity.getApplicationId() + "\\" + getEntityVersionLabel()+"_"+entity.getId();
-    }
-
-    @Override
-    public int copyResource(Map<Object, Object> sshFlags, String source, String target, boolean createParentDir) {
-        if (createParentDir) {
-            createDirectory(getDirectory(target), "Creating resource directory");
-        }
-        return copyTo(new File(source), target);
-    }
-
-    @Override
-    public int copyResource(Map<Object, Object> sshFlags, InputStream source, String target, boolean createParentDir) {
-        if (createParentDir) {
-            createDirectory(getDirectory(target), "Creating resource directory");
-        }
-        return copyTo(source, target);
-    }
-
-    @Override
-    protected void createDirectory(String directoryName, String summaryForLogging) {
-        getLocation().executePsScript("New-Item -path \"" + directoryName + "\" -type directory -ErrorAction SilentlyContinue");
-    }
-
-    protected WinRmToolResponse executeCommand(ConfigKey<String> regularCommandKey, ConfigKey<String> powershellCommandKey, boolean allowNoOp) {
-        String regularCommand = getEntity().getConfig(regularCommandKey);
-        String powershellCommand = getEntity().getConfig(powershellCommandKey);
-        if (Strings.isNullOrEmpty(regularCommand) && Strings.isNullOrEmpty(powershellCommand)) {
-            if (allowNoOp) {
-                return new WinRmToolResponse("", "", 0);
-            } else {
-                throw new IllegalStateException(String.format("Exactly one of %s or %s must be set", regularCommandKey.getName(), powershellCommandKey.getName()));
-            }
-        } else if (!Strings.isNullOrEmpty(regularCommand) && !Strings.isNullOrEmpty(powershellCommand)) {
-            throw new IllegalStateException(String.format("%s and %s cannot both be set", regularCommandKey.getName(), powershellCommandKey.getName()));
-        }
-
-        if (Strings.isNullOrEmpty(regularCommand)) {
-            return getLocation().executePsScript(ImmutableList.of(powershellCommand));
-        } else {
-            return getLocation().executeScript(ImmutableList.of(regularCommand));
-        }
-    }
-
-    public int execute(List<String> script) {
-        return getLocation().executeScript(script).getStatusCode();
-    }
-
-    public int executePsScriptNoRetry(List<String> psScript) {
-        return getLocation().executePsScriptNoRetry(psScript).getStatusCode();
-    }
-
-    public int executePsScript(List<String> psScript) {
-        return getLocation().executePsScript(psScript).getStatusCode();
-    }
-
-    public int copyTo(File source, String destination) {
-        return getLocation().copyTo(source, destination);
-    }
-
-    public int copyTo(InputStream source, String destination) {
-        return getLocation().copyTo(source, destination);
-    }
-
-    public void rebootAndWait() {
-        try {
-            executePsScriptNoRetry(ImmutableList.of("Restart-Computer -Force"));
-        } catch (PyException e) {
-            // Restarting the computer will cause the command to fail; ignore the exception and continue
-        }
-        waitForWinRmStatus(false, entity.getConfig(VanillaWindowsProcess.REBOOT_BEGUN_TIMEOUT));
-        waitForWinRmStatus(true, entity.getConfig(VanillaWindowsProcess.REBOOT_COMPLETED_TIMEOUT)).getWithError();
-    }
-
-    private String getDirectory(String fileName) {
-        return fileName.substring(0, fileName.lastIndexOf("\\"));
-    }
-
-    private ReferenceWithError<Boolean> waitForWinRmStatus(final boolean requiredStatus, Duration timeout) {
-        // TODO: Reduce / remove duplication between this and JcloudsLocation.waitForWinRmAvailable
-        Callable<Boolean> checker = new Callable<Boolean>() {
-            @Override
-            public Boolean call() throws Exception {
-                try {
-                    return (execute(ImmutableList.of("hostname")) == 0) == requiredStatus;
-                } catch (Exception e) {
-                    return !requiredStatus;
-                }
-            }
-        };
-
-        return new Repeater()
-                .every(1, TimeUnit.SECONDS)
-                .until(checker)
-                .limitTimeTo(timeout)
-                .runKeepingError();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/AbstractVanillaProcess.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/AbstractVanillaProcess.java b/software/base/src/main/java/brooklyn/entity/basic/AbstractVanillaProcess.java
deleted file mode 100644
index 675ff88..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/AbstractVanillaProcess.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.sensor.core.AttributeSensorAndConfigKey;
-
-public interface AbstractVanillaProcess extends SoftwareProcess {
-    AttributeSensorAndConfigKey<String, String> DOWNLOAD_URL = SoftwareProcess.DOWNLOAD_URL;
-
-    ConfigKey<String> SUGGESTED_VERSION = ConfigKeys.newConfigKeyWithDefault(SoftwareProcess.SUGGESTED_VERSION, "0.0.0");
-    
-    ConfigKey<String> INSTALL_COMMAND = ConfigKeys.newStringConfigKey("install.command", "command to run during the install phase");
-    ConfigKey<String> CUSTOMIZE_COMMAND = ConfigKeys.newStringConfigKey("customize.command", "command to run during the customization phase");
-    ConfigKey<String> LAUNCH_COMMAND = ConfigKeys.newStringConfigKey("launch.command", "command to run to launch the process");
-    ConfigKey<String> CHECK_RUNNING_COMMAND = ConfigKeys.newStringConfigKey("checkRunning.command", "command to determine whether the process is running");
-    ConfigKey<String> STOP_COMMAND = ConfigKeys.newStringConfigKey("stop.command", "command to run to stop the process");
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/EmptySoftwareProcess.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/EmptySoftwareProcess.java b/software/base/src/main/java/brooklyn/entity/basic/EmptySoftwareProcess.java
deleted file mode 100644
index 2d2c771..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/EmptySoftwareProcess.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import org.apache.brooklyn.api.entity.ImplementedBy;
-
-@ImplementedBy(EmptySoftwareProcessImpl.class)
-public interface EmptySoftwareProcess extends SoftwareProcess {
-
-    public SoftwareProcessDriver getDriver();
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/EmptySoftwareProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/EmptySoftwareProcessDriver.java b/software/base/src/main/java/brooklyn/entity/basic/EmptySoftwareProcessDriver.java
deleted file mode 100644
index 5a3fac7..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/EmptySoftwareProcessDriver.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-public interface EmptySoftwareProcessDriver extends SoftwareProcessDriver {
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/EmptySoftwareProcessImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/EmptySoftwareProcessImpl.java b/software/base/src/main/java/brooklyn/entity/basic/EmptySoftwareProcessImpl.java
deleted file mode 100644
index ba86768..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/EmptySoftwareProcessImpl.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-public class EmptySoftwareProcessImpl extends SoftwareProcessImpl implements EmptySoftwareProcess {
-
-    @Override
-    public Class<?> getDriverInterface() {
-        return EmptySoftwareProcessDriver.class;
-    }
-
-    @Override
-    protected void connectSensors() {
-        super.connectSensors();
-        connectServiceUpIsRunning();
-    }
-
-    @Override
-    protected void disconnectSensors() {
-        disconnectServiceUpIsRunning();
-        super.disconnectSensors();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/EmptySoftwareProcessSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/EmptySoftwareProcessSshDriver.java b/software/base/src/main/java/brooklyn/entity/basic/EmptySoftwareProcessSshDriver.java
deleted file mode 100644
index ce1282b..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/EmptySoftwareProcessSshDriver.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-
-public class EmptySoftwareProcessSshDriver extends AbstractSoftwareProcessSshDriver implements EmptySoftwareProcessDriver {
-
-    private final AtomicBoolean running = new AtomicBoolean();
-
-    public EmptySoftwareProcessSshDriver(EmptySoftwareProcessImpl entity, SshMachineLocation machine) {
-        super(entity, machine);
-    }
-
-    @Override
-    public boolean isRunning() {
-        return running.get();
-    }
-
-    @Override
-    public void install() { }
-
-    @Override
-    public void customize() { }
-
-    @Override
-    public void copyInstallResources() { 
-        Map<String, String> installFiles = entity.getConfig(SoftwareProcess.INSTALL_FILES);
-        Map<String, String> installTemplates = entity.getConfig(SoftwareProcess.INSTALL_TEMPLATES);
-        if ((installFiles!=null && !installFiles.isEmpty()) || (installTemplates!=null && !installTemplates.isEmpty())) {
-            // only do this if there are files, to prevent unnecessary `mkdir`
-            super.copyInstallResources();
-        }
-    }
-
-    @Override
-    public void copyRuntimeResources() { 
-        Map<String, String> runtimeFiles = entity.getConfig(SoftwareProcess.RUNTIME_FILES);
-        Map<String, String> runtimeTemplates = entity.getConfig(SoftwareProcess.RUNTIME_TEMPLATES);
-        if ((runtimeFiles!=null && !runtimeFiles.isEmpty()) || (runtimeTemplates!=null && !runtimeTemplates.isEmpty())) {
-            // only do this if there are files, to prevent unnecessary `mkdir`
-            super.copyRuntimeResources();
-        }        
-    }
-
-    @Override
-    public void launch() {
-        running.set(true);
-    }
-
-    @Override
-    public void rebind() {
-        super.rebind();
-        /* TODO not necessarily, but there is not yet an easy way to persist state without 
-         * using config/sensors which we might not want do. */
-        running.set(true);
-    }
-
-    @Override
-    public void stop() {
-        running.set(false);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/SameServerDriverLifecycleEffectorTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/SameServerDriverLifecycleEffectorTasks.java b/software/base/src/main/java/brooklyn/entity/basic/SameServerDriverLifecycleEffectorTasks.java
deleted file mode 100644
index f79c993..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/SameServerDriverLifecycleEffectorTasks.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import java.util.Collection;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.location.PortRange;
-import org.apache.brooklyn.api.mgmt.TaskAdaptable;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.entity.core.AbstractEntity;
-import org.apache.brooklyn.entity.trait.StartableMethods;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Supplier;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-import com.google.common.reflect.TypeToken;
-
-import brooklyn.entity.software.MachineLifecycleEffectorTasks;
-
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
-import org.apache.brooklyn.util.collections.MutableSet;
-import org.apache.brooklyn.util.core.flags.TypeCoercions;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.guava.Maybe;
-
-public class SameServerDriverLifecycleEffectorTasks extends MachineLifecycleEffectorTasks {
-
-    private static final Logger LOG = LoggerFactory.getLogger(SameServerDriverLifecycleEffectorTasks.class);
-
-    @Override
-    protected SameServerEntityImpl entity() {
-        return (SameServerEntityImpl) super.entity();
-    }
-
-    /**
-     * @return the ports that this entity wants to use, aggregated for all its child entities.
-     */
-    protected Collection<Integer> getRequiredOpenPorts() {
-        Set<Integer> result = Sets.newLinkedHashSet();
-        result.addAll(getRequiredOpenPorts(entity()));
-        LOG.debug("getRequiredOpenPorts detected aggregated default {} for {}", result, this);
-        return result;
-    }
-
-    /** @return the ports required for a specific child entity */
-    protected Collection<Integer> getRequiredOpenPorts(Entity entity) {
-        Set<Integer> ports = MutableSet.of(22);
-        /* TODO: This won't work if there's a port collision, which will cause the corresponding port attribute
-           to be incremented until a free port is found. In that case the entity will use the free port, but the
-           firewall will open the initial port instead. Mostly a problem for SameServerEntity, localhost location.
-        */
-        // TODO: Remove duplication between this and SoftwareProcessImpl.getRequiredOpenPorts
-        for (ConfigKey<?> k: entity.getEntityType().getConfigKeys()) {
-            Object value;
-            if (PortRange.class.isAssignableFrom(k.getType()) || k.getName().matches(".*\\.port")) {
-                value = entity.config().get(k);
-            } else {
-                // config().get() will cause this to block until all config has been resolved
-                // using config().getRaw(k) means that we won't be able to use e.g. 'http.port: $brooklyn:component("x").attributeWhenReady("foo")'
-                // but that's unlikely to be used
-                Maybe<Object> maybeValue = ((AbstractEntity.BasicConfigurationSupport)entity.config()).getRaw(k);
-                value = maybeValue.isPresent() ? maybeValue.get() : null;
-            }
-
-            Maybe<PortRange> maybePortRange = TypeCoercions.tryCoerce(value, TypeToken.of(PortRange.class));
-
-            if (maybePortRange.isPresentAndNonNull()) {
-                PortRange p = maybePortRange.get();
-                if (p != null && !p.isEmpty()) ports.add(p.iterator().next());
-            }
-        }
-        LOG.debug("getRequiredOpenPorts detected default {} for {}", ports, entity);
-
-        for (Entity child : entity.getChildren()) {
-            ports.addAll(getRequiredOpenPorts(child));
-        }
-        return ports;
-    }
-
-    @SuppressWarnings("unchecked")
-    @Override
-    protected Map<String, Object> obtainProvisioningFlags(MachineProvisioningLocation<?> location) {
-        Map<String, Object> result = super.obtainProvisioningFlags(location);
-        result.putAll(obtainProvisioningFlags(entity(), location));
-        Collection<Integer> ports = getRequiredOpenPorts();
-
-        if (result.containsKey("inboundPorts")) {
-            ports.addAll((Collection<Integer>) result.get("inboundPorts"));
-        }
-        if (!ports.isEmpty()) {
-            result.put("inboundPorts", ports);
-        }
-
-        result.put(LocationConfigKeys.CALLER_CONTEXT.getName(), entity());
-        return result;
-    }
-
-    /** @return provisioning flags for the given entity */
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    protected Map<String,Object> obtainProvisioningFlags(Entity entity, MachineProvisioningLocation location) {
-        Map<String,Object> result = Maps.newLinkedHashMap();
-        result.putAll(Maps.newLinkedHashMap(location.getProvisioningFlags(ImmutableList.of(entity.getEntityType().getName()))));
-        result.putAll(entity.getConfig(SameServerEntity.PROVISIONING_PROPERTIES));
-
-        for (Entity child : entity.getChildren()) {
-            result.putAll(obtainProvisioningFlags(child, location));
-        }
-        return result;
-    }
-
-    @Override
-    protected String startProcessesAtMachine(Supplier<MachineLocation> machineS) {
-        DynamicTasks.queueIfPossible(StartableMethods.startingChildren(entity(), machineS.get()))
-                .orSubmitAsync(entity())
-                .getTask()
-                .getUnchecked();
-        DynamicTasks.waitForLast();
-        return "children started";
-    }
-
-    // Also see stopProcessesAtMachine in SoftwareProcessDriverLifecycleEffectorTasks.
-    // Any fixes made there should probably be applied here too.
-    @Override
-    protected String stopProcessesAtMachine() {
-        TaskAdaptable<?> children = StartableMethods.stoppingChildren(entity());
-        DynamicTasks.queue(children);
-        Exception childException = null;
-        try {
-            DynamicTasks.waitForLast();
-        } catch (Exception e) {
-            childException = e;
-        }
-
-        try {
-            children.asTask().get();
-        } catch (Exception e) {
-            childException = e;
-            LOG.debug("Error stopping children; continuing and will rethrow if no other errors", e);
-        }
-
-        if (childException != null)
-            throw new IllegalStateException("error stopping child", childException);
-
-        return "children stopped";
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/SameServerEntity.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/SameServerEntity.java b/software/base/src/main/java/brooklyn/entity/basic/SameServerEntity.java
deleted file mode 100644
index c2ac288..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/SameServerEntity.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic.ComputeServiceIndicatorsFromChildrenAndMembers;
-import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.collections.QuorumCheck;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-
-import com.google.common.reflect.TypeToken;
-
-/**
- * An entity that, on start({@link MachineProvisioningLocation}), will obtain a machine
- * and pass that to each of its children by calling their {@link Startable#start(java.util.Collection)}
- * methods with that machine.
- * 
- * Thus multiple entities can be set up to run on the same machine.
- * 
- * @author aled
- */
-@ImplementedBy(SameServerEntityImpl.class)
-@SuppressWarnings("serial")
-public interface SameServerEntity extends Entity, Startable {
-
-    @SetFromFlag("provisioningProperties")
-    ConfigKey<Map<String,Object>> PROVISIONING_PROPERTIES = ConfigKeys.newConfigKey(
-            new TypeToken<Map<String, Object>>() {},
-            "provisioning.properties", "Custom properties to be passed in when provisioning a new machine",
-            MutableMap.<String, Object>of());
-    
-    ConfigKey<QuorumCheck> UP_QUORUM_CHECK = ComputeServiceIndicatorsFromChildrenAndMembers.UP_QUORUM_CHECK;
-    ConfigKey<QuorumCheck> RUNNING_QUORUM_CHECK = ComputeServiceIndicatorsFromChildrenAndMembers.RUNNING_QUORUM_CHECK;
-
-    AttributeSensor<Lifecycle> SERVICE_STATE_ACTUAL = Attributes.SERVICE_STATE_ACTUAL;
-
-    @SuppressWarnings("rawtypes")
-    AttributeSensor<MachineProvisioningLocation> PROVISIONING_LOCATION = new BasicAttributeSensor<MachineProvisioningLocation>(
-            MachineProvisioningLocation.class, "softwareservice.provisioningLocation", "Location used to provision a machine where this is running");
-    
-    AttributeSensor<String> HOSTNAME = Attributes.HOSTNAME;
-    
-    AttributeSensor<String> ADDRESS = Attributes.ADDRESS;
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/SameServerEntityImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/SameServerEntityImpl.java b/software/base/src/main/java/brooklyn/entity/basic/SameServerEntityImpl.java
deleted file mode 100644
index 057e6c2..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/SameServerEntityImpl.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.Collection;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.entity.core.AbstractEntity;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic.ComputeServiceIndicatorsFromChildrenAndMembers;
-import org.apache.brooklyn.util.collections.QuorumCheck;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.Tasks;
-
-import brooklyn.entity.software.MachineLifecycleEffectorTasks;
-
-public class SameServerEntityImpl extends AbstractEntity implements SameServerEntity {
-
-    private static final MachineLifecycleEffectorTasks LIFECYCLE_TASKS = new SameServerDriverLifecycleEffectorTasks();
-
-    @Override
-    protected void initEnrichers() {
-        super.initEnrichers();
-        
-        // Because can have multiple children (similar to groups/clusters/apps), need to
-        // monitor their health and indicate this has failed if any of them have failed.
-        addEnricher(ServiceStateLogic.newEnricherFromChildren()
-                .configure(ComputeServiceIndicatorsFromChildrenAndMembers.UP_QUORUM_CHECK, QuorumCheck.QuorumChecks.all()));
-    }
-    
-    /**
-     * Restarts the entity and its children.
-     * <p/>
-     * Subclasses should override {@link #doRestart(ConfigBag)} to customise behaviour. */
-    @Override
-    public final void restart() {
-        if (DynamicTasks.getTaskQueuingContext() != null) {
-            doRestart(ConfigBag.EMPTY);
-        } else {
-            Task<?> task = Tasks.builder().name("restart").body(new Runnable() { public void run() { doRestart(ConfigBag.EMPTY); } }).build();
-            Entities.submit(this, task).getUnchecked();
-        }
-    }
-
-    /**
-     * Starts the entity and its children in the given locations.
-     * <p/>
-     * Subclasses should override {@link #doStart} to customise behaviour.
-     */
-    @Override
-    public final void start(final Collection<? extends Location> locations) {
-        checkNotNull(locations, "locations");
-        if (DynamicTasks.getTaskQueuingContext() != null) {
-            doStart(locations);
-        } else {
-            Task<?> task = Tasks.builder().name("start").body(new Runnable() { public void run() { doStart(locations); } }).build();
-            Entities.submit(this, task).getUnchecked();
-        }
-    }
-
-    /**
-     * Stops the entity and its children.
-     * <p/>
-     * Subclasses should override {@link #doStop} to customise behaviour.
-     */
-    @Override
-    public final void stop() {
-        if (DynamicTasks.getTaskQueuingContext() != null) {
-            doStop();
-        } else {
-            Task<?> task = Tasks.builder().name("stop").body(new Runnable() { public void run() { doStop(); } }).build();
-            Entities.submit(this, task).getUnchecked();
-        }
-    }
-
-    /**
-     * To be overridden instead of {@link #start(Collection)}; sub-classes should call
-     * {@code super.doStart(locations)} and should add do additional work via tasks,
-     * executed using {@link DynamicTasks#queue(String, java.util.concurrent.Callable)}.
-     */
-    protected void doStart(Collection<? extends Location> locations) {
-        LIFECYCLE_TASKS.start(locations);
-    }
-
-    /**
-     * To be overridden instead of {@link #stop()}; sub-classes should call {@code
-     * super.doStop()} and should add do additional work via tasks, executed using
-     * {@link DynamicTasks#queue(String, java.util.concurrent.Callable)}.
-     */
-    protected void doStop() {
-        LIFECYCLE_TASKS.stop(ConfigBag.EMPTY);
-    }
-
-    /**
-     * To be overridden instead of {@link #restart()}; sub-classes should call {@code
-     * super.doRestart(ConfigBag)} and should add do additional work via tasks, executed using
-     * {@link DynamicTasks#queue(String, java.util.concurrent.Callable)}.
-     */
-    protected void doRestart(ConfigBag parameters) {
-        LIFECYCLE_TASKS.restart(parameters);
-    }
-
-    @Deprecated /** @deprecated since 0.7.0 subclasses should instead override {@link #doRestart(ConfigBag)} */
-    protected final void doRestart() {
-        doRestart(ConfigBag.EMPTY);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/SoftwareProcess.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/SoftwareProcess.java b/software/base/src/main/java/brooklyn/entity/basic/SoftwareProcess.java
deleted file mode 100644
index 9fa724b..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/SoftwareProcess.java
+++ /dev/null
@@ -1,362 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import java.util.Collection;
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.config.MapConfigKey;
-import org.apache.brooklyn.entity.annotation.Effector;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle.Transition;
-import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.sensor.core.AttributeSensorAndConfigKey;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.apache.brooklyn.util.time.Duration;
-
-import com.google.common.annotations.Beta;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.reflect.TypeToken;
-
-public interface SoftwareProcess extends Entity, Startable {
-
-    AttributeSensor<String> HOSTNAME = Attributes.HOSTNAME;
-    AttributeSensor<String> ADDRESS = Attributes.ADDRESS;
-    AttributeSensor<String> SUBNET_HOSTNAME = Attributes.SUBNET_HOSTNAME;
-    AttributeSensor<String> SUBNET_ADDRESS = Attributes.SUBNET_ADDRESS;
-
-    @SuppressWarnings("serial")
-    ConfigKey<Collection<Integer>> REQUIRED_OPEN_LOGIN_PORTS = ConfigKeys.newConfigKey(
-            new TypeToken<Collection<Integer>>() {},
-            "requiredOpenLoginPorts",
-            "The port(s) to be opened, to allow login",
-            ImmutableSet.of(22));
-
-    @SetFromFlag("startTimeout")
-    ConfigKey<Duration> START_TIMEOUT = BrooklynConfigKeys.START_TIMEOUT;
-
-    @SetFromFlag("startLatch")
-    ConfigKey<Boolean> START_LATCH = BrooklynConfigKeys.START_LATCH;
-
-    @SetFromFlag("setupLatch")
-    ConfigKey<Boolean> SETUP_LATCH = BrooklynConfigKeys.SETUP_LATCH;
-
-    @SetFromFlag("installResourcesLatch")
-    ConfigKey<Boolean> INSTALL_RESOURCES_LATCH = BrooklynConfigKeys.INSTALL_RESOURCES_LATCH;
-
-    @SetFromFlag("installLatch")
-    ConfigKey<Boolean> INSTALL_LATCH = BrooklynConfigKeys.INSTALL_LATCH;
-
-    @SetFromFlag("runtimeResourcesLatch")
-    ConfigKey<Boolean> RUNTIME_RESOURCES_LATCH = BrooklynConfigKeys.RUNTIME_RESOURCES_LATCH;
-
-    @SetFromFlag("customizeLatch")
-    ConfigKey<Boolean> CUSTOMIZE_LATCH = BrooklynConfigKeys.CUSTOMIZE_LATCH;
-
-    @SetFromFlag("launchLatch")
-    ConfigKey<Boolean> LAUNCH_LATCH = BrooklynConfigKeys.LAUNCH_LATCH;
-
-    @SetFromFlag("skipStart")
-    ConfigKey<Boolean> ENTITY_STARTED = BrooklynConfigKeys.SKIP_ENTITY_START;
-
-    @SetFromFlag("skipStartIfRunning")
-    ConfigKey<Boolean> SKIP_ENTITY_START_IF_RUNNING = BrooklynConfigKeys.SKIP_ENTITY_START_IF_RUNNING;
-
-    @SetFromFlag("skipInstall")
-    ConfigKey<Boolean> SKIP_INSTALLATION = BrooklynConfigKeys.SKIP_ENTITY_INSTALLATION;
-
-    @SetFromFlag("preInstallCommand")
-    ConfigKey<String> PRE_INSTALL_COMMAND = BrooklynConfigKeys.PRE_INSTALL_COMMAND;
-
-    @SetFromFlag("postInstallCommand")
-    ConfigKey<String> POST_INSTALL_COMMAND = BrooklynConfigKeys.POST_INSTALL_COMMAND;
-
-    @SetFromFlag("preLaunchCommand")
-    ConfigKey<String> PRE_LAUNCH_COMMAND = BrooklynConfigKeys.PRE_LAUNCH_COMMAND;
-
-    @SetFromFlag("postLaunchCommand")
-    ConfigKey<String> POST_LAUNCH_COMMAND = BrooklynConfigKeys.POST_LAUNCH_COMMAND;
-
-    @SetFromFlag("version")
-    ConfigKey<String> SUGGESTED_VERSION = BrooklynConfigKeys.SUGGESTED_VERSION;
-
-    @SetFromFlag("downloadUrl")
-    AttributeSensorAndConfigKey<String,String> DOWNLOAD_URL = Attributes.DOWNLOAD_URL;
-
-    @SetFromFlag("downloadAddonUrls")
-    AttributeSensorAndConfigKey<Map<String,String>,Map<String,String>> DOWNLOAD_ADDON_URLS = Attributes.DOWNLOAD_ADDON_URLS;
-
-    @SetFromFlag("installLabel")
-    ConfigKey<String> INSTALL_UNIQUE_LABEL = BrooklynConfigKeys.INSTALL_UNIQUE_LABEL;
-
-    @SetFromFlag("expandedInstallDir")
-    AttributeSensorAndConfigKey<String,String> EXPANDED_INSTALL_DIR = BrooklynConfigKeys.EXPANDED_INSTALL_DIR;
-
-    @SetFromFlag("installDir")
-    AttributeSensorAndConfigKey<String,String> INSTALL_DIR = BrooklynConfigKeys.INSTALL_DIR;
-    @Deprecated
-    ConfigKey<String> SUGGESTED_INSTALL_DIR = BrooklynConfigKeys.SUGGESTED_INSTALL_DIR;
-
-    @SetFromFlag("runDir")
-    AttributeSensorAndConfigKey<String,String> RUN_DIR = BrooklynConfigKeys.RUN_DIR;
-    @Deprecated
-    ConfigKey<String> SUGGESTED_RUN_DIR = BrooklynConfigKeys.SUGGESTED_RUN_DIR;
-
-    public static final ConfigKey<Boolean> OPEN_IPTABLES = ConfigKeys.newBooleanConfigKey("openIptables", 
-            "Whether to open the INBOUND_PORTS via iptables rules; " +
-            "if true then ssh in to run iptables commands, as part of machine provisioning", false);
-
-    public static final ConfigKey<Boolean> STOP_IPTABLES = ConfigKeys.newBooleanConfigKey("stopIptables", 
-            "Whether to stop iptables entirely; " +
-            "if true then ssh in to stop the iptables service, as part of machine provisioning", false);
-
-    public static final ConfigKey<Boolean> DONT_REQUIRE_TTY_FOR_SUDO = ConfigKeys.newBooleanConfigKey("dontRequireTtyForSudo", 
-            "Whether to explicitly set /etc/sudoers, so don't need tty (will leave unchanged if 'false'); " +
-            "some machines require a tty for sudo; brooklyn by default does not use a tty " +
-            "(so that it can get separate error+stdout streams); you can enable a tty as an " +
-            "option to every ssh command, or you can do it once and " +
-            "modify the machine so that a tty is not subsequently required.",
-            false);
-    
-    /**
-     * Files to be copied to the server before pre-install.
-     * <p>
-     * Map of {@code classpath://foo/file.txt} (or other url) source to destination path,
-     * as {@code subdir/file} relative to installation directory or {@code /absolute/path/to/file}.
-     *
-     * @see #PRE_INSTALL_TEMPLATES
-     */
-    @Beta
-    @SuppressWarnings("serial")
-    @SetFromFlag("preInstallFiles")
-    ConfigKey<Map<String, String>> PRE_INSTALL_FILES = ConfigKeys.newConfigKey(new TypeToken<Map<String, String>>() { },
-            "files.preinstall", "Mapping of files, to be copied before install, to destination name relative to installDir");
-
-    /**
-     * Templates to be filled in and then copied to the server before install.
-     *
-     * @see #PRE_INSTALL_FILES
-     */
-    @Beta
-    @SuppressWarnings("serial")
-    @SetFromFlag("preInstallTemplates")
-    ConfigKey<Map<String, String>> PRE_INSTALL_TEMPLATES = ConfigKeys.newConfigKey(new TypeToken<Map<String, String>>() { },
-            "templates.preinstall", "Mapping of templates, to be filled in and copied before pre-install, to destination name relative to installDir");
-
-    /**
-     * Files to be copied to the server before install.
-     * <p>
-     * Map of {@code classpath://foo/file.txt} (or other url) source to destination path,
-     * as {@code subdir/file} relative to installation directory or {@code /absolute/path/to/file}.
-     *
-     * @see #INSTALL_TEMPLATES
-     */
-    @Beta
-    @SuppressWarnings("serial")
-    @SetFromFlag("installFiles")
-    ConfigKey<Map<String, String>> INSTALL_FILES = ConfigKeys.newConfigKey(new TypeToken<Map<String, String>>() { },
-            "files.install", "Mapping of files, to be copied before install, to destination name relative to installDir");
-
-    /**
-     * Templates to be filled in and then copied to the server before install.
-     *
-     * @see #INSTALL_FILES
-     */
-    @Beta
-    @SuppressWarnings("serial")
-    @SetFromFlag("installTemplates")
-    ConfigKey<Map<String, String>> INSTALL_TEMPLATES = ConfigKeys.newConfigKey(new TypeToken<Map<String, String>>() { },
-            "templates.install", "Mapping of templates, to be filled in and copied before install, to destination name relative to installDir");
-
-    /**
-     * Files to be copied to the server after customisation.
-     * <p>
-     * Map of {@code classpath://foo/file.txt} (or other url) source to destination path,
-     * as {@code subdir/file} relative to runtime directory or {@code /absolute/path/to/file}.
-     *
-     * @see #RUNTIME_TEMPLATES
-     */
-    @Beta
-    @SuppressWarnings("serial")
-    @SetFromFlag("runtimeFiles")
-    ConfigKey<Map<String, String>> RUNTIME_FILES = ConfigKeys.newConfigKey(new TypeToken<Map<String, String>>() { },
-            "files.runtime", "Mapping of files, to be copied before customisation, to destination name relative to runDir");
-
-    /**
-     * Templates to be filled in and then copied to the server after customisation.
-     *
-     * @see #RUNTIME_FILES
-     */
-    @Beta
-    @SuppressWarnings("serial")
-    @SetFromFlag("runtimeTemplates")
-    ConfigKey<Map<String, String>> RUNTIME_TEMPLATES = ConfigKeys.newConfigKey(new TypeToken<Map<String, String>>() { },
-            "templates.runtime", "Mapping of templates, to be filled in and copied before customisation, to destination name relative to runDir");
-
-    @SetFromFlag("env")
-    MapConfigKey<Object> SHELL_ENVIRONMENT = new MapConfigKey<Object>(Object.class,
-            "shell.env", "Map of environment variables to pass to the runtime shell", MutableMap.<String,Object>of());
-
-    @SetFromFlag("provisioningProperties")
-    MapConfigKey<Object> PROVISIONING_PROPERTIES = new MapConfigKey<Object>(Object.class,
-            "provisioning.properties", "Custom properties to be passed in when provisioning a new machine", MutableMap.<String,Object>of());
-
-    @SetFromFlag("maxRebindSensorsDelay")
-    ConfigKey<Duration> MAXIMUM_REBIND_SENSOR_CONNECT_DELAY = ConfigKeys.newConfigKey(Duration.class,
-            "softwareProcess.maxSensorRebindDelay",
-            "The maximum delay to apply when reconnecting sensors when rebinding to this entity. " +
-                    "Brooklyn will wait a random amount of time, up to the value of this config key, to " +
-                    "avoid a thundering herd problem when the entity shares its machine with " +
-                    "several others. Set to null or to 0 to disable any delay.",
-            Duration.TEN_SECONDS);
-
-    /**
-     * Sets the object that manages the sequence of calls of the entity's driver.
-     */
-    @Beta
-    @SetFromFlag("lifecycleEffectorTasks")
-    ConfigKey<SoftwareProcessDriverLifecycleEffectorTasks> LIFECYCLE_EFFECTOR_TASKS = ConfigKeys.newConfigKey(SoftwareProcessDriverLifecycleEffectorTasks.class,
-            "softwareProcess.lifecycleTasks", "An object that handles lifecycle of an entity's associated machine.",
-            new SoftwareProcessDriverLifecycleEffectorTasks());
-
-    ConfigKey<Boolean> RETRIEVE_USAGE_METRICS = ConfigKeys.newBooleanConfigKey(
-            "metrics.usage.retrieve",
-            "Whether to retrieve the usage (e.g. performance) metrics",
-            true);
-
-    /** Controls the behavior when starting (stop, restart) {@link Startable} children as part of the start (stop, restart) effector on this entity
-     * <p>
-     * (NB: restarts are currently not propagated to children in the default {@link SoftwareProcess}
-     * due to the various semantics which may be desired; this may change, but if entities have specific requirements for restart,
-     * developers should either subclass the {@link SoftwareProcessDriverLifecycleEffectorTasks} and/or lean on sensors from the parent */
-    enum ChildStartableMode {
-        /** do nothing with {@link Startable} children */
-        NONE(true, false, false),
-        /** start (stop) {@link Startable} children concurrent with *driver* start (stop),
-         * in foreground, so invoking entity will wait for children to complete.
-         * <p>
-         * if the child requires the parent to reach a particular state before acting,
-         * when running in foreground the parent should communicate its state using sensors
-         * which the child listens for.
-         * note that often sensors at the parent are not activated until it is started,
-         * so the usual sensors connected at an entity may not be available when running in this mode */
-        FOREGROUND(false, false, false),
-        /** as {@link #FOREGROUND} but {@link ChildStartableMode#isLate} */
-        FOREGROUND_LATE(false, false, true),
-        /** start {@link Startable} children concurrent with *driver* start (stop, restart),
-         * but in background, ie disassociated from the effector task at this entity
-         * (so that this entity can complete start/stop independent of children) */
-        BACKGROUND(false, true, false),
-        /** as {@link #BACKGROUND} but {@link ChildStartableMode#isLate} */
-        BACKGROUND_LATE(false, true, true);
-
-        /** whether starting (stopping, restarting) children is disabled */
-        public final boolean isDisabled;
-        /** whether starting (stopping, restarting) children is backgrounded, so parent should not wait on them */
-        public final boolean isBackground;
-        /** whether starting (stopping, restarting) children should be nested, so start occurs after the driver is started,
-         * and stop before the driver is stopped (if false the children operations are concurrent with the parent),
-         * (with restart always being done in parallel though this behaviour may change) */
-        public final boolean isLate;
-
-        private ChildStartableMode(boolean isDisabled, boolean isBackground, boolean isLate) {
-            this.isDisabled = isDisabled;
-            this.isBackground = isBackground;
-            this.isLate = isLate;
-        }
-
-    }
-
-    @SetFromFlag("childStartMode")
-    ConfigKey<ChildStartableMode> CHILDREN_STARTABLE_MODE = ConfigKeys.newConfigKey(ChildStartableMode.class,
-            "children.startable.mode", "Controls behaviour when starting Startable children as part of this entity's lifecycle.",
-            ChildStartableMode.NONE);
-
-    @SuppressWarnings("rawtypes")
-    AttributeSensor<MachineProvisioningLocation> PROVISIONING_LOCATION = Sensors.newSensor(
-            MachineProvisioningLocation.class, "softwareservice.provisioningLocation", "Location used to provision a machine where this is running");
-
-    AttributeSensor<Boolean> SERVICE_PROCESS_IS_RUNNING = Sensors.newBooleanSensor("service.process.isRunning", 
-            "Whether the process for the service is confirmed as running");
-    
-    AttributeSensor<Lifecycle> SERVICE_STATE_ACTUAL = Attributes.SERVICE_STATE_ACTUAL;
-    AttributeSensor<Transition> SERVICE_STATE_EXPECTED = Attributes.SERVICE_STATE_EXPECTED;
- 
-    AttributeSensor<String> PID_FILE = Sensors.newStringSensor("softwareprocess.pid.file", "PID file");
-
-    @Beta
-    public static class RestartSoftwareParameters {
-        @Beta /** @since 0.7.0 semantics of parameters to restart being explored */
-        public static final ConfigKey<Boolean> RESTART_CHILDREN = ConfigKeys.newConfigKey(Boolean.class, "restartChildren",
-            "Whether to restart children; default false", false);
-
-        @Beta /** @since 0.7.0 semantics of parameters to restart being explored */
-        public static final ConfigKey<Object> RESTART_MACHINE = ConfigKeys.newConfigKey(Object.class, "restartMachine",
-            "Whether to restart/replace the machine provisioned for this entity:  'true', 'false', or 'auto' are supported, "
-            + "with the default being 'auto' which means to restart or reprovision the machine if there is no simpler way known to restart the entity "
-            + "(for example, if the machine is unhealthy, it would not be possible to restart the process, not even via a stop-then-start sequence); "
-            + "if the machine was not provisioned for this entity, this parameter has no effect", 
-            RestartMachineMode.AUTO.toString().toLowerCase());
-        
-        // we supply a typed variant for retrieval; we want the untyped (above) to use lower case as the default in the GUI
-        // (very hard if using enum, since enum takes the name, and RendererHints do not apply to parameters) 
-        @Beta /** @since 0.7.0 semantics of parameters to restart being explored */
-        public static final ConfigKey<RestartMachineMode> RESTART_MACHINE_TYPED = ConfigKeys.newConfigKey(RestartMachineMode.class, "restartMachine");
-            
-        public enum RestartMachineMode { TRUE, FALSE, AUTO }
-    }
-
-    @Beta
-    public static class StopSoftwareParameters {
-        //IF_NOT_STOPPED includes STARTING, STOPPING, RUNNING
-        public enum StopMode { ALWAYS, IF_NOT_STOPPED, NEVER };
-
-        @Beta /** @since 0.7.0 semantics of parameters to restart being explored */
-        public static final ConfigKey<StopMode> STOP_PROCESS_MODE = ConfigKeys.newConfigKey(StopMode.class, "stopProcessMode",
-                "When to stop the process with regard to the entity state. " +
-                "ALWAYS will try to stop the process even if the entity is marked as stopped, " +
-                "IF_NOT_STOPPED stops the process only if the entity is not marked as stopped, " +
-                "NEVER doesn't stop the process.", StopMode.IF_NOT_STOPPED);
-
-        @Beta /** @since 0.7.0 semantics of parameters to restart being explored */
-        public static final ConfigKey<StopMode> STOP_MACHINE_MODE = ConfigKeys.newConfigKey(StopMode.class, "stopMachineMode",
-                "When to stop the machine with regard to the entity state. " +
-                "ALWAYS will try to stop the machine even if the entity is marked as stopped, " +
-                "IF_NOT_STOPPED stops the machine only if the entity is not marked as stopped, " +
-                "NEVER doesn't stop the machine.", StopMode.IF_NOT_STOPPED);
-    }
-    
-    // NB: the START, STOP, and RESTART effectors themselves are (re)defined by MachineLifecycleEffectorTasks
-
-    /**
-     * @since 0.8.0
-     */
-    @Effector(description="Populates the attribute service.notUp.diagnostics, with any available health indicators")
-    @Beta
-    void populateServiceNotUpDiagnostics();
-}



[65/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/PersistenceObjectStore.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/PersistenceObjectStore.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/PersistenceObjectStore.java
new file mode 100644
index 0000000..aa83e14
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/PersistenceObjectStore.java
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import java.util.Date;
+import java.util.List;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.locks.ReadWriteLock;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.util.time.Duration;
+
+import com.google.common.annotations.Beta;
+
+/**
+ * Interface for working with persistence targets, including file system and jclouds object stores.
+ * @author Andrea Turli
+ */
+public interface PersistenceObjectStore {
+
+    /** accessor to an object/item in a {@link PersistenceObjectStore} */
+    public interface StoreObjectAccessor {
+        /** gets the object, or null if not found */
+        String get();
+        byte[] getBytes();
+        boolean exists();
+        void put(String contentsToReplaceOrCreate);
+        void append(String contentsToAppendOrCreate);
+        void delete();
+        // NB: creation date is available for many blobstores but 
+        // not on java.io.File and filesystems, so it is not included here 
+        /** last modified date, null if not supported or does not exist */
+        Date getLastModifiedDate();
+    }
+    public interface StoreObjectAccessorWithLock extends StoreObjectAccessor {
+        /** waits for all currently scheduled write lock operations (puts, appends, and deletes) to complete;
+         * but does not wait on or prevent subsequent modifications.
+         * this is suitable for a model where the caller is managing synchronization.
+         * <p> 
+         * for more complex uses, readers should <code>getLockObject().readLock().lockInterruptibly()</code> 
+         * and ensure they subsequently <code>unlock()</code> it of course. see {@link #getLockObject()}. */
+        void waitForCurrentWrites(Duration timeout) throws InterruptedException, TimeoutException;
+        
+        /** returns the underlying lock in case callers need more complex synchronization control */ 
+        ReadWriteLock getLockObject();
+    }
+
+    /** human-readable name of this object store */
+    public String getSummaryName();
+    
+    /**
+     * Allows a way for an object store to be created ahead of time, and a mgmt context injected.
+     * Currently subsequent changes are not permitted.
+     * <p>
+     * A {@link ManagementContext} must be supplied via constructor or this method before invoking other methods.
+     */
+    @Beta
+    public void injectManagementContext(ManagementContext managementContext);
+    
+    /**
+     * Prepares the persistence store for read use and non-contentious write use,
+     * in particular detecting whether we should clean or register a need for backup etc.
+     * Typically called early in the setup lifecycle, after {@link #injectManagementContext(ManagementContext)},
+     * but before {@link #prepareForMasterUse()}.
+     * <p>
+     * See {@link #prepareForMasterUse()} for discussion of "contentious writes".
+     */
+    @Beta
+    public void prepareForSharedUse(PersistMode persistMode, HighAvailabilityMode highAvailabilityMode);
+
+    /** 
+     * Prepares the persistence store for "contentious writes".
+     * These are defined as those writes which might overwrite important information.
+     * Implementations usually perform backup/versioning of the store if required.
+     * <p>
+     * Caller must call {@link #prepareForSharedUse(PersistMode, HighAvailabilityMode)} first
+     * (and {@link #injectManagementContext(ManagementContext)} before that).
+     * <p>
+     * This is typically invoked "at the last moment" e.g. before the any such write,
+     * mainly in order to prevent backups being made unnecessarily (e.g. if a node is standby,
+     * or if it tries to become master but is not capable),
+     * but also to prevent simultaneous backups which can cause problems with some stores
+     * (only a mgmt who knows he is the master should invoke this).
+     **/
+    @Beta
+    public void prepareForMasterUse();
+    
+    /**
+     * For reading/writing data to the item at the given path.
+     * Note that the accessor is not generally thread safe, usually does not support blocking,
+     * and multiple instances may conflict with each other.
+     * <p>
+     * Clients should wrap in a dedicated {@link StoreObjectAccessorLocking} and share
+     * if multiple threads may be accessing the store.
+     * This method may be changed in future to allow access to a shared locking accessor.
+     */
+    @Beta
+    // TODO requiring clients to wrap and cache accessors is not very nice API, 
+    // better would be to do caching here probably,
+    // but we've already been doing it this way above for now (Jun 2014)
+    StoreObjectAccessor newAccessor(String path);
+
+    /** create the directory at the given subPath relative to the base of this store */
+    void createSubPath(String subPath);
+
+    /**
+     * Lists the paths of objects contained at the given path, including the subpath.
+     * For example, if a file-based ObjectStore is configured to write to file://path/to/root/
+     * then parentSubPath=entities would return the contents of /path/to/root/entities/, such as
+     * [entities/e1, entities/e2, entities/e3].
+     * The returned paths values are usable in calls to {@link #newAccessor(String)}.
+     */
+    List<String> listContentsWithSubPath(String subPath);
+
+    /** Entirely delete the contents of this persistence location.
+     * Use with care, primarily in tests. This will recursively wipe the indicated location. */ 
+    public void deleteCompletely();
+    
+    /**
+     * Closes all resources used by this ObjectStore. No subsequent calls should be made to the ObjectStore;
+     * behaviour of such calls is undefined but likely to throw exceptions.
+     */
+    void close();
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/RetryingMementoSerializer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/RetryingMementoSerializer.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/RetryingMementoSerializer.java
new file mode 100644
index 0000000..480a2ec
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/RetryingMementoSerializer.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoPersister.LookupContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class RetryingMementoSerializer<T> implements MementoSerializer<T> {
+    
+    private static final Logger LOG = LoggerFactory.getLogger(RetryingMementoSerializer.class);
+    
+    private final MementoSerializer<T> delegate;
+    private final int maxAttempts;
+    
+    public RetryingMementoSerializer(MementoSerializer<T> delegate, int maxAttempts) {
+        this.delegate = checkNotNull(delegate, "delegate");
+        this.maxAttempts = maxAttempts;
+        if (maxAttempts < 1) throw new IllegalArgumentException("Max attempts must be at least 1, but was "+maxAttempts);
+    }
+    
+    @Override
+    public String toString(T memento) {
+        RuntimeException lastException = null;
+        int attempt = 0;
+        do {
+            attempt++;
+            try {
+                String result = delegate.toString(memento);
+                if (attempt>1) 
+                    LOG.info("Success following previous serialization error");
+                return result;
+            } catch (RuntimeException e) {
+                LOG.warn("Error serializing memento (attempt "+attempt+" of "+maxAttempts+") for "+memento+
+                        "; expected sometimes if attribute value modified", e);
+                lastException = e;
+            }
+        } while (attempt < maxAttempts);
+        
+        throw lastException;
+    }
+    
+    @Override
+    public T fromString(String string) {
+        if (string==null)
+            return null;
+        
+        RuntimeException lastException = null;
+        int attempt = 0;
+        do {
+            attempt++;
+            try {
+                T result = delegate.fromString(string);
+                if (attempt>1)
+                    LOG.info("Success following previous deserialization error, got: "+result);
+                return result;
+            } catch (RuntimeException e) {
+                // trying multiple times only makes sense for a few errors (namely ConcModExceptions); perhaps deprecate that strategy?
+                LOG.warn("Error deserializing memento (attempt "+attempt+" of "+maxAttempts+"): "+e, e);
+                if (attempt==1) LOG.debug("Memento which was not deserialized is:\n"+string);
+                lastException = e;
+            }
+        } while (attempt < maxAttempts);
+        
+        throw lastException;
+    }
+
+    @Override
+    public void setLookupContext(LookupContext lookupContext) {
+        delegate.setLookupContext(lookupContext);
+    }
+
+    @Override
+    public void unsetLookupContext() {
+        delegate.unsetLookupContext();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/StoreObjectAccessorLocking.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/StoreObjectAccessorLocking.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/StoreObjectAccessorLocking.java
new file mode 100644
index 0000000..302121f
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/StoreObjectAccessorLocking.java
@@ -0,0 +1,218 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import java.util.Comparator;
+import java.util.Date;
+import java.util.Set;
+import java.util.concurrent.ConcurrentSkipListSet;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore.StoreObjectAccessor;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.javalang.JavaClassNames;
+import org.apache.brooklyn.util.time.Duration;
+
+/** Wraps access to an object (the delegate {@link StoreObjectAccessor} 
+ * in a guarded read-write context such that callers will be blocked if another thread
+ * is accessing the object in an incompatible way (e.g. trying to read when someone is writing).
+ * See {@link ReadWriteLock}.
+ * <p>
+ * This has no visibility or control over other access to the delegate or underlying object, of course.
+ * It can only affect callers coming through this wrapper instance.  Thus callers must share instances
+ * of this class for a given item.
+ * <p>
+ * No locking is done with respect to {@link #getLastModifiedDate()}. 
+ **/
+public class StoreObjectAccessorLocking implements PersistenceObjectStore.StoreObjectAccessorWithLock {
+
+    protected static class ThreadComparator implements Comparator<Thread> {
+        @Override
+        public int compare(Thread o1, Thread o2) {
+            if (o1.getId()<o2.getId()) return -1;
+            if (o1.getId()>o2.getId()) return 1;
+            return 0;
+        }
+    }
+    
+    ReadWriteLock lock = new ReentrantReadWriteLock(true);
+    Set<Thread> queuedReaders = new ConcurrentSkipListSet<Thread>(new ThreadComparator());
+    Set<Thread> queuedWriters = new ConcurrentSkipListSet<Thread>(new ThreadComparator());
+    
+    final PersistenceObjectStore.StoreObjectAccessor delegate;
+    
+    public StoreObjectAccessorLocking(PersistenceObjectStore.StoreObjectAccessor delegate) {
+        this.delegate = delegate;
+    }
+    
+    @Override
+    public String get() {
+        try {
+            queuedReaders.add(Thread.currentThread());
+            lock.readLock().lockInterruptibly();
+            try {
+                return delegate.get();
+                
+            } finally {
+                lock.readLock().unlock();
+            }
+        } catch (InterruptedException e) {
+            throw Exceptions.propagate(e);
+        } finally {
+            queuedReaders.remove(Thread.currentThread());
+        }
+    }
+
+    @Override
+    public byte[] getBytes() {
+        try {
+            queuedReaders.add(Thread.currentThread());
+            lock.readLock().lockInterruptibly();
+            try {
+                return delegate.getBytes();
+                
+            } finally {
+                lock.readLock().unlock();
+            }
+        } catch (InterruptedException e) {
+            throw Exceptions.propagate(e);
+        } finally {
+            queuedReaders.remove(Thread.currentThread());
+        }
+    }
+
+    @Override
+    public boolean exists() {
+        try {
+            queuedReaders.add(Thread.currentThread());
+            lock.readLock().lockInterruptibly();
+            try {
+                return delegate.exists();
+                
+            } finally {
+                lock.readLock().unlock();
+            }
+        } catch (InterruptedException e) {
+            throw Exceptions.propagate(e);
+        } finally {
+            queuedReaders.remove(Thread.currentThread());
+        }
+    }
+
+    protected boolean hasScheduledPutOrDeleteWithNoRead() {
+        // skip write if there is another write queued and no reader waiting
+        return (!queuedWriters.isEmpty() && queuedReaders.isEmpty());
+    }
+    
+    @Override
+    public void put(String val) {
+        try {
+            queuedWriters.add(Thread.currentThread());
+            lock.writeLock().lockInterruptibly();
+            try {
+                queuedWriters.remove(Thread.currentThread());
+                if (hasScheduledPutOrDeleteWithNoRead()) 
+                    // don't bother writing if someone will write after us and no one is reading
+                    return;
+                delegate.put(val);
+                
+            } finally {
+                lock.writeLock().unlock();
+            }
+        } catch (InterruptedException e) {
+            throw Exceptions.propagate(e);
+        } finally {
+            queuedWriters.remove(Thread.currentThread());
+        }
+    }
+    
+    @Override
+    public void append(String val) {
+        try {
+            lock.writeLock().lockInterruptibly();
+            try {
+                if (hasScheduledPutOrDeleteWithNoRead())
+                    // don't bother appending if someone will write after us and no one is reading
+                    return;
+                
+                delegate.append(val);
+                
+            } finally {
+                lock.writeLock().unlock();
+            }
+        } catch (InterruptedException e) {
+            throw Exceptions.propagate(e);
+        }
+    }
+    
+    @Override
+    public void delete() {
+        try {
+            queuedWriters.add(Thread.currentThread());
+            lock.writeLock().lockInterruptibly();
+            try {
+                queuedWriters.remove(Thread.currentThread());
+                if (hasScheduledPutOrDeleteWithNoRead()) {
+                    // don't bother deleting if someone will write after us and no one is reading
+                    return;
+                }
+                delegate.delete();
+                
+            } finally {
+                lock.writeLock().unlock();
+            }
+        } catch (InterruptedException e) {
+            throw Exceptions.propagate(e);
+        } finally {
+            queuedWriters.remove(Thread.currentThread());
+        }
+    }
+    
+    @Override
+    public void waitForCurrentWrites(Duration timeout) throws InterruptedException, TimeoutException {
+        try {
+            boolean locked = lock.readLock().tryLock(timeout.toMillisecondsRoundingUp(), TimeUnit.MILLISECONDS);
+            if (locked) {
+                lock.readLock().unlock();
+            } else {
+                throw new TimeoutException("Timeout waiting for writes of "+delegate+" after "+timeout);
+            }
+        } catch (InterruptedException e) {
+            throw Exceptions.propagate(e);
+        }
+    }
+    
+    @Override
+    public Date getLastModifiedDate() {
+        return delegate.getLastModifiedDate();
+    }
+
+    @Override
+    public ReadWriteLock getLockObject() {
+        return lock;
+    }
+
+    @Override
+    public String toString() {
+        return JavaClassNames.simpleClassName(this)+":"+delegate.toString();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/XmlMementoSerializer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/XmlMementoSerializer.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/XmlMementoSerializer.java
new file mode 100644
index 0000000..799ad91
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/persist/XmlMementoSerializer.java
@@ -0,0 +1,505 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.io.IOException;
+import java.io.Writer;
+import java.util.NoSuchElementException;
+import java.util.Stack;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.api.catalog.CatalogItem;
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.internal.AbstractBrooklynObjectSpec;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.api.mgmt.classloading.BrooklynClassLoadingContext;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoPersister.LookupContext;
+import org.apache.brooklyn.api.objs.Identifiable;
+import org.apache.brooklyn.api.policy.Policy;
+import org.apache.brooklyn.api.sensor.Enricher;
+import org.apache.brooklyn.api.sensor.Feed;
+import org.apache.brooklyn.core.catalog.internal.CatalogBundleDto;
+import org.apache.brooklyn.core.catalog.internal.CatalogUtils;
+import org.apache.brooklyn.core.config.BasicConfigKey;
+import org.apache.brooklyn.core.mgmt.classloading.BrooklynClassLoadingContextSequential;
+import org.apache.brooklyn.core.mgmt.classloading.ClassLoaderFromBrooklynClassLoadingContext;
+import org.apache.brooklyn.core.mgmt.classloading.JavaBrooklynClassLoadingContext;
+import org.apache.brooklyn.core.mgmt.rebind.dto.BasicCatalogItemMemento;
+import org.apache.brooklyn.core.mgmt.rebind.dto.BasicEnricherMemento;
+import org.apache.brooklyn.core.mgmt.rebind.dto.BasicEntityMemento;
+import org.apache.brooklyn.core.mgmt.rebind.dto.BasicFeedMemento;
+import org.apache.brooklyn.core.mgmt.rebind.dto.BasicLocationMemento;
+import org.apache.brooklyn.core.mgmt.rebind.dto.BasicPolicyMemento;
+import org.apache.brooklyn.core.mgmt.rebind.dto.MutableBrooklynMemento;
+import org.apache.brooklyn.effector.core.BasicParameterType;
+import org.apache.brooklyn.effector.core.EffectorAndBody;
+import org.apache.brooklyn.effector.core.EffectorTasks.EffectorBodyTaskFactory;
+import org.apache.brooklyn.effector.core.EffectorTasks.EffectorTaskFactory;
+import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
+import org.apache.brooklyn.util.core.xstream.XmlSerializer;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.text.Strings;
+
+import com.thoughtworks.xstream.converters.Converter;
+import com.thoughtworks.xstream.converters.MarshallingContext;
+import com.thoughtworks.xstream.converters.SingleValueConverter;
+import com.thoughtworks.xstream.converters.UnmarshallingContext;
+import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;
+import com.thoughtworks.xstream.core.ReferencingMarshallingContext;
+import com.thoughtworks.xstream.core.util.HierarchicalStreams;
+import com.thoughtworks.xstream.io.HierarchicalStreamReader;
+import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
+import com.thoughtworks.xstream.io.path.PathTrackingReader;
+import com.thoughtworks.xstream.mapper.Mapper;
+import com.thoughtworks.xstream.mapper.MapperWrapper;
+
+/* uses xml, cleaned up a bit
+ * 
+ * there is an early attempt at doing this with JSON in pull request #344 but 
+ * it is not nicely deserializable, see comments at http://xstream.codehaus.org/json-tutorial.html */  
+public class XmlMementoSerializer<T> extends XmlSerializer<T> implements MementoSerializer<T> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(XmlMementoSerializer.class);
+
+    private final ClassLoader classLoader;
+    private LookupContext lookupContext;
+
+    public XmlMementoSerializer(ClassLoader classLoader) {
+        this.classLoader = checkNotNull(classLoader, "classLoader");
+        xstream.setClassLoader(this.classLoader);
+        
+        // old (deprecated in 070? or earlier) single-file persistence uses this keyword; TODO remove soon in 080 ?
+        xstream.alias("brooklyn", MutableBrooklynMemento.class);
+        
+        xstream.alias("entity", BasicEntityMemento.class);
+        xstream.alias("location", BasicLocationMemento.class);
+        xstream.alias("policy", BasicPolicyMemento.class);
+        xstream.alias("feed", BasicFeedMemento.class);
+        xstream.alias("enricher", BasicEnricherMemento.class);
+        xstream.alias("configKey", BasicConfigKey.class);
+        xstream.alias("catalogItem", BasicCatalogItemMemento.class);
+        xstream.alias("bundle", CatalogBundleDto.class);
+        xstream.alias("attributeSensor", BasicAttributeSensor.class);
+
+        xstream.alias("effector", Effector.class);
+        xstream.addDefaultImplementation(EffectorAndBody.class, Effector.class);
+        xstream.alias("parameter", BasicParameterType.class);
+        xstream.addDefaultImplementation(EffectorBodyTaskFactory.class, EffectorTaskFactory.class);
+        
+        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 FeedConverter());
+        xstream.registerConverter(new CatalogItemConverter());
+        xstream.registerConverter(new SpecConverter());
+
+        xstream.registerConverter(new ManagementContextConverter());
+        xstream.registerConverter(new TaskConverter(xstream.getMapper()));
+    
+        //For compatibility with existing persistence stores content.
+        xstream.aliasField("registeredTypeName", BasicCatalogItemMemento.class, "symbolicName");
+        xstream.registerLocalConverter(BasicCatalogItemMemento.class, "libraries", new CatalogItemLibrariesConverter());
+    }
+    
+    // Warning: this is called in the super-class constuctor, so before this constructor!
+    @Override
+    protected MapperWrapper wrapMapper(MapperWrapper next) {
+        MapperWrapper mapper = super.wrapMapper(next);
+        mapper = new CustomMapper(mapper, Entity.class, "entityProxy");
+        mapper = new CustomMapper(mapper, Location.class, "locationProxy");
+        return mapper;
+    }
+
+    @Override
+    public void serialize(Object object, Writer writer) {
+        super.serialize(object, writer);
+        try {
+            writer.append("\n");
+        } catch (IOException e) {
+            throw Exceptions.propagate(e);
+        }
+    }
+
+    @Override
+    public void setLookupContext(LookupContext lookupContext) {
+        this.lookupContext = checkNotNull(lookupContext, "lookupContext");
+    }
+
+    @Override
+    public void unsetLookupContext() {
+        this.lookupContext = null;
+    }
+    
+    /**
+     * For changing the tag used for anything that implements/extends the given type.
+     * Necessary for using EntityRef rather than the default "dynamic-proxy" tag.
+     * 
+     * @author aled
+     */
+    public class CustomMapper extends MapperWrapper {
+        private final Class<?> clazz;
+        private final String alias;
+
+        public CustomMapper(Mapper wrapped, Class<?> clazz, String alias) {
+            super(wrapped);
+            this.clazz = checkNotNull(clazz, "clazz");
+            this.alias = checkNotNull(alias, "alias");
+        }
+
+        public String getAlias() {
+            return alias;
+        }
+
+        @Override
+        public String serializedClass(@SuppressWarnings("rawtypes") Class type) {
+            if (type != null && clazz.isAssignableFrom(type)) {
+                return alias;
+            } else {
+                return super.serializedClass(type);
+            }
+        }
+
+        @Override
+        public Class<?> realClass(String elementName) {
+            if (elementName.equals(alias)) {
+                return clazz;
+            } else {
+                return super.realClass(elementName);
+            }
+        }
+    }
+
+    public abstract class IdentifiableConverter<IT extends Identifiable> implements SingleValueConverter {
+        private final Class<IT> clazz;
+        
+        IdentifiableConverter(Class<IT> clazz) {
+            this.clazz = clazz;
+        }
+        @Override
+        public boolean canConvert(@SuppressWarnings("rawtypes") Class type) {
+            boolean result = clazz.isAssignableFrom(type);
+            return result;
+        }
+
+        @Override
+        public String toString(Object obj) {
+            return obj == null ? null : ((Identifiable)obj).getId();
+        }
+        @Override
+        public Object fromString(String str) {
+            if (lookupContext == null) {
+                LOG.warn("Cannot unmarshal from persisted xml {} {}; no lookup context supplied!", clazz.getSimpleName(), str);
+                return null;
+            } else {
+                return lookup(str);
+            }
+        }
+        
+        protected abstract IT lookup(String id);
+    }
+
+    public class LocationConverter extends IdentifiableConverter<Location> {
+        LocationConverter() {
+            super(Location.class);
+        }
+        @Override
+        protected Location lookup(String id) {
+            return lookupContext.lookupLocation(id);
+        }
+    }
+
+    public class PolicyConverter extends IdentifiableConverter<Policy> {
+        PolicyConverter() {
+            super(Policy.class);
+        }
+        @Override
+        protected Policy lookup(String id) {
+            return lookupContext.lookupPolicy(id);
+        }
+    }
+
+    public class EnricherConverter extends IdentifiableConverter<Enricher> {
+        EnricherConverter() {
+            super(Enricher.class);
+        }
+        @Override
+        protected Enricher lookup(String id) {
+            return lookupContext.lookupEnricher(id);
+        }
+    }
+    
+    public class FeedConverter extends IdentifiableConverter<Feed> {
+        FeedConverter() {
+            super(Feed.class);
+        }
+        @Override
+        protected Feed lookup(String id) {
+            return lookupContext.lookupFeed(id);
+        }
+    }
+    
+    public class EntityConverter extends IdentifiableConverter<Entity> {
+        EntityConverter() {
+            super(Entity.class);
+        }
+        @Override
+        protected Entity lookup(String id) {
+            return lookupContext.lookupEntity(id);
+        }
+    }
+
+    @SuppressWarnings("rawtypes")
+    public class CatalogItemConverter extends IdentifiableConverter<CatalogItem> {
+        CatalogItemConverter() {
+            super(CatalogItem.class);
+        }
+        @Override
+        protected CatalogItem<?,?> lookup(String id) {
+            return lookupContext.lookupCatalogItem(id);
+        }
+    }
+
+
+    static boolean loggedTaskWarning = false;
+    public class TaskConverter implements Converter {
+        private final Mapper mapper;
+        
+        TaskConverter(Mapper mapper) {
+            this.mapper = mapper;
+        }
+        @Override
+        public boolean canConvert(@SuppressWarnings("rawtypes") Class type) {
+            return Task.class.isAssignableFrom(type);
+        }
+        @SuppressWarnings("deprecation")
+        @Override
+        public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
+            if (source == null) return;
+            if (((Task<?>)source).isDone() && !((Task<?>)source).isError()) {
+                try {
+                    context.convertAnother(((Task<?>)source).get());
+                } catch (InterruptedException e) {
+                    throw Exceptions.propagate(e);
+                } catch (ExecutionException e) {
+                    LOG.warn("Unexpected exception getting done (and non-error) task result for "+source+"; continuing: "+e, e);
+                }
+            } else {
+                // TODO How to log sensibly, without it logging this every second?!
+                // jun 2014, have added a "log once" which is not ideal but better than the log never behaviour
+                if (!loggedTaskWarning) {
+                    LOG.warn("Intercepting and skipping request to serialize a Task"
+                        + (context instanceof ReferencingMarshallingContext ? " at "+((ReferencingMarshallingContext)context).currentPath() : "")+
+                        " (only logging this once): "+source);
+                    loggedTaskWarning = true;
+                }
+                
+                return;
+            }
+        }
+        @Override
+        public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
+            if (reader.hasMoreChildren()) {
+                Class<?> type = HierarchicalStreams.readClassType(reader, mapper);
+                reader.moveDown();
+                Object result = context.convertAnother(null, type);
+                reader.moveUp();
+                return result;
+            } else {
+                return null;
+            }
+        }
+    }
+    
+    public class ManagementContextConverter implements Converter {
+        @Override
+        public boolean canConvert(@SuppressWarnings("rawtypes") Class type) {
+            return ManagementContext.class.isAssignableFrom(type);
+        }
+        @Override
+        public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
+            // write nothing, and always insert the current mgmt context
+        }
+        @Override
+        public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
+            return lookupContext.lookupManagementContext();
+        }
+    }
+
+    /** When reading/writing specs, it checks whether there is a catalog item id set and uses it to load */
+    public class SpecConverter extends ReflectionConverter {
+        SpecConverter() {
+            super(xstream.getMapper(), xstream.getReflectionProvider());
+        }
+        @Override
+        public boolean canConvert(@SuppressWarnings("rawtypes") Class type) {
+            return AbstractBrooklynObjectSpec.class.isAssignableFrom(type);
+        }
+        @Override
+        public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
+            if (source == null) return;
+            AbstractBrooklynObjectSpec<?, ?> spec = (AbstractBrooklynObjectSpec<?, ?>) source;
+            String catalogItemId = spec.getCatalogItemId();
+            if (Strings.isNonBlank(catalogItemId)) {
+                // write this field first, so we can peek at it when we read
+                writer.startNode("catalogItemId");
+                writer.setValue(catalogItemId);
+                writer.endNode();
+                
+                // we're going to write the catalogItemId field twice :( but that's okay.
+                // better solution would be to have mark/reset on reader so we can peek for such a field;
+                // see comment below
+                super.marshal(source, writer, context);
+            } else {
+                super.marshal(source, writer, context);
+            }
+        }
+        @Override
+        public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
+            String catalogItemId = null;
+            instantiateNewInstanceSettingCache(reader, context);
+            
+            if (reader instanceof PathTrackingReader) {
+                // have to assume this is first; there is no mark/reset support on these readers
+                // (if there were then it would be easier, we could just look for that child anywhere,
+                // and not need a custom writer!)
+                if ("catalogItemId".equals( ((PathTrackingReader)reader).peekNextChild() )) {
+                    // cache the instance
+                    
+                    reader.moveDown();
+                    catalogItemId = reader.getValue();
+                    reader.moveUp();
+                }
+            }
+            boolean customLoaderSet = false;
+            try {
+                if (Strings.isNonBlank(catalogItemId)) {
+                    if (lookupContext==null) throw new NullPointerException("lookupContext required to load catalog item "+catalogItemId);
+                    CatalogItem<?, ?> cat = CatalogUtils.getCatalogItemOptionalVersion(lookupContext.lookupManagementContext(), catalogItemId);
+                    if (cat==null) throw new NoSuchElementException("catalog item: "+catalogItemId);
+                    BrooklynClassLoadingContext clcNew = CatalogUtils.newClassLoadingContext(lookupContext.lookupManagementContext(), cat);
+                    pushXstreamCustomClassLoader(clcNew);
+                    customLoaderSet = true;
+                }
+                
+                AbstractBrooklynObjectSpec<?, ?> result = (AbstractBrooklynObjectSpec<?, ?>) super.unmarshal(reader, context);
+                // we wrote it twice so this shouldn't be necessary; but if we fix it so we only write once, we'd need this
+                result.catalogItemId(catalogItemId);
+                return result;
+            } finally {
+                instance = null;
+                if (customLoaderSet) {
+                    popXstreamCustomClassLoader();
+                }
+            }
+        }
+
+        Object instance;
+        
+        @Override
+        protected Object instantiateNewInstance(HierarchicalStreamReader reader, UnmarshallingContext context) {
+            // the super calls getAttribute which requires that we have not yet done moveDown,
+            // so we do this earlier and cache it for when we call super.unmarshal
+            if (instance==null)
+                throw new IllegalStateException("Instance should be created and cached");
+            return instance;
+        }
+        protected void instantiateNewInstanceSettingCache(HierarchicalStreamReader reader, UnmarshallingContext context) {
+            instance = super.instantiateNewInstance(reader, context);
+        }
+    }
+    
+    Stack<BrooklynClassLoadingContext> contexts = new Stack<BrooklynClassLoadingContext>();
+    Stack<ClassLoader> cls = new Stack<ClassLoader>();
+    AtomicReference<Thread> xstreamLockOwner = new AtomicReference<Thread>();
+    int lockCount;
+    
+    /** Must be accompanied by a corresponding {@link #popXstreamCustomClassLoader()} when finished. */
+    @SuppressWarnings("deprecation")
+    protected void pushXstreamCustomClassLoader(BrooklynClassLoadingContext clcNew) {
+        acquireXstreamLock();
+        BrooklynClassLoadingContext oldClc;
+        if (!contexts.isEmpty()) {
+            oldClc = contexts.peek();
+        } else {
+            // TODO XmlMementoSerializer should take a BCLC instead of a CL
+            oldClc = JavaBrooklynClassLoadingContext.create(lookupContext.lookupManagementContext(), xstream.getClassLoader());
+        }
+        BrooklynClassLoadingContextSequential clcMerged = new BrooklynClassLoadingContextSequential(lookupContext.lookupManagementContext(),
+            oldClc, clcNew);
+        contexts.push(clcMerged);
+        cls.push(xstream.getClassLoader());
+        ClassLoader newCL = ClassLoaderFromBrooklynClassLoadingContext.of(clcMerged);
+        xstream.setClassLoader(newCL);
+    }
+
+    protected void popXstreamCustomClassLoader() {
+        synchronized (xstreamLockOwner) {
+            releaseXstreamLock();
+            xstream.setClassLoader(cls.pop());
+            contexts.pop();
+        }
+    }
+    
+    protected void acquireXstreamLock() {
+        synchronized (xstreamLockOwner) {
+            while (true) {
+                if (xstreamLockOwner.compareAndSet(null, Thread.currentThread()) || 
+                    Thread.currentThread().equals( xstreamLockOwner.get() )) {
+                    break;
+                }
+                try {
+                    xstreamLockOwner.wait(1000);
+                } catch (InterruptedException e) {
+                    throw Exceptions.propagate(e);
+                }
+            }
+            lockCount++;
+        }
+    }
+
+    protected void releaseXstreamLock() {
+        synchronized (xstreamLockOwner) {
+            if (lockCount<=0) {
+                throw new IllegalStateException("xstream not locked");
+            }
+            if (--lockCount == 0) {
+                if (!xstreamLockOwner.compareAndSet(Thread.currentThread(), null)) {
+                    Thread oldOwner = xstreamLockOwner.getAndSet(null);
+                    throw new IllegalStateException("xstream was locked by "+oldOwner+" but unlock attempt by "+Thread.currentThread());
+                }
+                xstreamLockOwner.notifyAll();
+            }
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/ActivePartialRebindIteration.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/ActivePartialRebindIteration.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/ActivePartialRebindIteration.java
index 6b586a8..d6c3160 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/ActivePartialRebindIteration.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/ActivePartialRebindIteration.java
@@ -36,8 +36,8 @@ import org.apache.brooklyn.api.objs.BrooklynObject;
 import org.apache.brooklyn.api.objs.BrooklynObjectType;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynMementoPersisterToObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceActivityMetrics;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceActivityMetrics;
 import org.apache.brooklyn.core.mgmt.rebind.transformer.CompoundTransformer;
 import org.apache.brooklyn.core.objs.BrooklynObjectInternal;
 import org.apache.brooklyn.entity.core.EntityInternal;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/BasicLocationRebindSupport.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/BasicLocationRebindSupport.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/BasicLocationRebindSupport.java
index 74a0497..c3b657d 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/BasicLocationRebindSupport.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/BasicLocationRebindSupport.java
@@ -30,7 +30,7 @@ import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.mgmt.rebind.dto.MementosGenerators;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.AbstractLocation;
+import org.apache.brooklyn.location.core.AbstractLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.flags.FlagUtils;
 import org.apache.brooklyn.util.core.flags.TypeCoercions;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/ImmediateDeltaChangeListener.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/ImmediateDeltaChangeListener.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/ImmediateDeltaChangeListener.java
index c69dca4..81785bc 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/ImmediateDeltaChangeListener.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/ImmediateDeltaChangeListener.java
@@ -37,7 +37,7 @@ import org.apache.brooklyn.api.mgmt.rebind.mementos.PolicyMemento;
 import org.apache.brooklyn.api.objs.BrooklynObject;
 import org.apache.brooklyn.api.policy.Policy;
 import org.apache.brooklyn.api.sensor.Enricher;
-import org.apache.brooklyn.location.basic.LocationInternal;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 
 import com.google.common.collect.Maps;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/InitialFullRebindIteration.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/InitialFullRebindIteration.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/InitialFullRebindIteration.java
index 8a36a0d..8b4cc29 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/InitialFullRebindIteration.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/InitialFullRebindIteration.java
@@ -31,7 +31,7 @@ import org.apache.brooklyn.core.mgmt.internal.BrooklynObjectManagementMode;
 import org.apache.brooklyn.core.mgmt.internal.EntityManagerInternal;
 import org.apache.brooklyn.core.mgmt.internal.LocationManagerInternal;
 import org.apache.brooklyn.core.mgmt.internal.ManagementTransitionMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceActivityMetrics;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceActivityMetrics;
 import org.apache.brooklyn.entity.core.EntityInternal;
 import org.apache.brooklyn.util.text.Strings;
 import org.slf4j.Logger;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/PeriodicDeltaChangeListener.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/PeriodicDeltaChangeListener.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/PeriodicDeltaChangeListener.java
index 7d68438..663061d 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/PeriodicDeltaChangeListener.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/PeriodicDeltaChangeListener.java
@@ -44,8 +44,8 @@ import org.apache.brooklyn.api.sensor.Enricher;
 import org.apache.brooklyn.api.sensor.Feed;
 import org.apache.brooklyn.core.internal.BrooklynFeatureEnablement;
 import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynPersistenceUtils;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceActivityMetrics;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynPersistenceUtils;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceActivityMetrics;
 import org.apache.brooklyn.core.objs.BrooklynObjectInternal;
 import org.apache.brooklyn.entity.core.EntityInternal;
 import org.apache.brooklyn.util.collections.MutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindIteration.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindIteration.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindIteration.java
index fc50d30..83cc155 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindIteration.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindIteration.java
@@ -71,8 +71,8 @@ import org.apache.brooklyn.core.mgmt.internal.EntityManagerInternal;
 import org.apache.brooklyn.core.mgmt.internal.LocationManagerInternal;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
 import org.apache.brooklyn.core.mgmt.internal.ManagementTransitionMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceActivityMetrics;
 import org.apache.brooklyn.core.mgmt.rebind.RebindManagerImpl.RebindTracker;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceActivityMetrics;
 import org.apache.brooklyn.core.objs.AbstractBrooklynObject;
 import org.apache.brooklyn.core.objs.BrooklynObjectInternal;
 import org.apache.brooklyn.core.objs.proxy.InternalEntityFactory;
@@ -82,8 +82,8 @@ import org.apache.brooklyn.core.objs.proxy.InternalPolicyFactory;
 import org.apache.brooklyn.entity.core.AbstractApplication;
 import org.apache.brooklyn.entity.core.AbstractEntity;
 import org.apache.brooklyn.entity.core.EntityInternal;
-import org.apache.brooklyn.location.basic.AbstractLocation;
-import org.apache.brooklyn.location.basic.LocationInternal;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 import org.apache.brooklyn.policy.core.AbstractPolicy;
 import org.apache.brooklyn.sensor.enricher.AbstractEnricher;
 import org.apache.brooklyn.sensor.feed.AbstractFeed;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindManagerImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindManagerImpl.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindManagerImpl.java
index 3372fef..4c82dbe 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindManagerImpl.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindManagerImpl.java
@@ -48,10 +48,10 @@ import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.core.internal.BrooklynFeatureEnablement;
 import org.apache.brooklyn.core.mgmt.ha.HighAvailabilityManagerImpl;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynMementoPersisterToObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynPersistenceUtils;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceActivityMetrics;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynPersistenceUtils.CreateBackupMode;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynPersistenceUtils;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceActivityMetrics;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynPersistenceUtils.CreateBackupMode;
 import org.apache.brooklyn.core.mgmt.rebind.transformer.CompoundTransformer;
 import org.apache.brooklyn.core.server.BrooklynServerConfig;
 import org.apache.brooklyn.entity.core.Entities;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/dto/MementosGenerators.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/dto/MementosGenerators.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/dto/MementosGenerators.java
index c62b064..505c844 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/dto/MementosGenerators.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/dto/MementosGenerators.java
@@ -49,13 +49,13 @@ import org.apache.brooklyn.api.sensor.Feed;
 import org.apache.brooklyn.api.sensor.AttributeSensor.SensorPersistenceMode;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.catalog.internal.CatalogItemDo;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynPersistenceUtils;
 import org.apache.brooklyn.core.mgmt.rebind.AbstractBrooklynObjectRebindSupport;
 import org.apache.brooklyn.core.mgmt.rebind.TreeUtils;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynPersistenceUtils;
 import org.apache.brooklyn.core.objs.BrooklynTypes;
 import org.apache.brooklyn.entity.core.EntityDynamicType;
 import org.apache.brooklyn.entity.core.EntityInternal;
-import org.apache.brooklyn.location.basic.LocationInternal;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 import org.apache.brooklyn.policy.core.AbstractPolicy;
 import org.apache.brooklyn.sensor.enricher.AbstractEnricher;
 import org.apache.brooklyn.sensor.feed.AbstractFeed;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterToObjectStore.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterToObjectStore.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterToObjectStore.java
deleted file mode 100644
index eb22d2e..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterToObjectStore.java
+++ /dev/null
@@ -1,697 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.io.IOException;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-import javax.annotation.Nullable;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.api.catalog.CatalogItem;
-import org.apache.brooklyn.api.mgmt.rebind.PersistenceExceptionHandler;
-import org.apache.brooklyn.api.mgmt.rebind.RebindExceptionHandler;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMemento;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoManifest;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoPersister;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.CatalogItemMemento;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.Memento;
-import org.apache.brooklyn.api.objs.BrooklynObject;
-import org.apache.brooklyn.api.objs.BrooklynObjectType;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.config.StringConfigMap;
-import org.apache.brooklyn.core.catalog.internal.CatalogUtils;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.mgmt.classloading.ClassLoaderFromBrooklynClassLoadingContext;
-import org.apache.brooklyn.core.mgmt.rebind.PeriodicDeltaChangeListener;
-import org.apache.brooklyn.core.mgmt.rebind.PersisterDeltaImpl;
-import org.apache.brooklyn.core.mgmt.rebind.dto.BrooklynMementoImpl;
-import org.apache.brooklyn.core.mgmt.rebind.dto.BrooklynMementoManifestImpl;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore.StoreObjectAccessor;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore.StoreObjectAccessorWithLock;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.xstream.XmlUtil;
-import org.apache.brooklyn.util.exceptions.CompoundRuntimeException;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-
-import com.google.common.annotations.Beta;
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Objects;
-import com.google.common.base.Stopwatch;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Lists;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-
-/** Implementation of the {@link BrooklynMementoPersister} backed by a pluggable
- * {@link PersistenceObjectStore} such as a file system or a jclouds object store */
-public class BrooklynMementoPersisterToObjectStore implements BrooklynMementoPersister {
-
-    // TODO Crazy amount of duplication between handling entity, location, policy, enricher + feed;
-    // Need to remove that duplication.
-
-    // TODO Should stop() take a timeout, and shutdown the executor gracefully?
-    
-    private static final Logger LOG = LoggerFactory.getLogger(BrooklynMementoPersisterToObjectStore.class);
-
-    public static final ConfigKey<Integer> PERSISTER_MAX_THREAD_POOL_SIZE = ConfigKeys.newIntegerConfigKey(
-            "persister.threadpool.maxSize",
-            "Maximum number of concurrent operations for persistence (reads/writes/deletes of *different* objects)", 
-            10);
-
-    public static final ConfigKey<Integer> PERSISTER_MAX_SERIALIZATION_ATTEMPTS = ConfigKeys.newIntegerConfigKey(
-            "persister.maxSerializationAttempts",
-            "Maximum number of attempts to serialize a memento (e.g. if first attempts fail because of concurrent modifications of an entity)", 
-            5);
-
-    private final PersistenceObjectStore objectStore;
-    private final MementoSerializer<Object> serializerWithStandardClassLoader;
-
-    private final Map<String, StoreObjectAccessorWithLock> writers = new LinkedHashMap<String, PersistenceObjectStore.StoreObjectAccessorWithLock>();
-
-    private final ListeningExecutorService executor;
-
-    private volatile boolean writesAllowed = false;
-    private volatile boolean writesShuttingDown = false;
-    private StringConfigMap brooklynProperties;
-    
-    private List<Delta> queuedDeltas = new CopyOnWriteArrayList<BrooklynMementoPersister.Delta>();
-    
-    /**
-     * Lock used on writes (checkpoint + delta) so that {@link #waitForWritesCompleted(Duration)} can block
-     * for any concurrent call to complete.
-     */
-    private final ReadWriteLock lock = new ReentrantReadWriteLock(true);
-
-    public BrooklynMementoPersisterToObjectStore(PersistenceObjectStore objectStore, StringConfigMap brooklynProperties, ClassLoader classLoader) {
-        this.objectStore = checkNotNull(objectStore, "objectStore");
-        this.brooklynProperties = brooklynProperties;
-        
-        int maxSerializationAttempts = brooklynProperties.getConfig(PERSISTER_MAX_SERIALIZATION_ATTEMPTS);
-        MementoSerializer<Object> rawSerializer = new XmlMementoSerializer<Object>(classLoader);
-        this.serializerWithStandardClassLoader = new RetryingMementoSerializer<Object>(rawSerializer, maxSerializationAttempts);
-
-        int maxThreadPoolSize = brooklynProperties.getConfig(PERSISTER_MAX_THREAD_POOL_SIZE);
-
-        objectStore.createSubPath("entities");
-        objectStore.createSubPath("locations");
-        objectStore.createSubPath("policies");
-        objectStore.createSubPath("enrichers");
-        objectStore.createSubPath("feeds");
-        objectStore.createSubPath("catalog");
-
-        // FIXME does it belong here or to ManagementPlaneSyncRecordPersisterToObjectStore ?
-        objectStore.createSubPath("plane");
-        
-        executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(maxThreadPoolSize, new ThreadFactory() {
-            @Override public Thread newThread(Runnable r) {
-                // Note: Thread name referenced in logback-includes' ThreadNameDiscriminator
-                return new Thread(r, "brooklyn-persister");
-            }}));
-    }
-
-    public MementoSerializer<Object> getMementoSerializer() {
-        return getSerializerWithStandardClassLoader();
-    }
-    
-    protected MementoSerializer<Object> getSerializerWithStandardClassLoader() {
-        return serializerWithStandardClassLoader;
-    }
-    
-    protected MementoSerializer<Object> getSerializerWithCustomClassLoader(LookupContext lookupContext, BrooklynObjectType type, String objectId) {
-        ClassLoader cl = getCustomClassLoaderForBrooklynObject(lookupContext, type, objectId);
-        if (cl==null) return serializerWithStandardClassLoader;
-        return getSerializerWithCustomClassLoader(lookupContext, cl);
-    }
-    
-    protected MementoSerializer<Object> getSerializerWithCustomClassLoader(LookupContext lookupContext, ClassLoader classLoader) {
-        int maxSerializationAttempts = brooklynProperties.getConfig(PERSISTER_MAX_SERIALIZATION_ATTEMPTS);
-        MementoSerializer<Object> rawSerializer = new XmlMementoSerializer<Object>(classLoader);
-        MementoSerializer<Object> result = new RetryingMementoSerializer<Object>(rawSerializer, maxSerializationAttempts);
-        result.setLookupContext(lookupContext);
-        return result;
-    }
-    
-    @Nullable protected ClassLoader getCustomClassLoaderForBrooklynObject(LookupContext lookupContext, BrooklynObjectType type, String objectId) {
-        BrooklynObject item = lookupContext.peek(type, objectId);
-        String catalogItemId = (item == null) ? null : item.getCatalogItemId();
-        // TODO enrichers etc aren't yet known -- would need to backtrack to the entity to get them from bundles
-        if (catalogItemId == null) {
-            return null;
-        }
-        // See RebindIteration.BrooklynObjectInstantiator.load(), for handling where catalog item is missing;
-        // similar logic here.
-        CatalogItem<?, ?> catalogItem = CatalogUtils.getCatalogItemOptionalVersion(lookupContext.lookupManagementContext(), catalogItemId);
-        if (catalogItem == null) {
-            // TODO do we need to only log once, rather than risk log.warn too often? I think this only happens on rebind, so ok.
-            LOG.warn("Unable to load catalog item "+catalogItemId+" for custom class loader of "+type+" "+objectId+"; will use default class loader");
-            return null;
-        } else {
-            return ClassLoaderFromBrooklynClassLoadingContext.of(CatalogUtils.newClassLoadingContext(lookupContext.lookupManagementContext(), catalogItem));
-        }
-    }
-    
-    @Override public void enableWriteAccess() {
-        writesAllowed = true;
-    }
-    
-    @Override
-    public void disableWriteAccess(boolean graceful) {
-        writesShuttingDown = true;
-        try {
-            writesAllowed = false;
-            // a very long timeout to ensure we don't lose state. 
-            // If persisting thousands of entities over slow network to Object Store, could take minutes.
-            waitForWritesCompleted(Duration.ONE_HOUR);
-            
-        } catch (Exception e) {
-            throw Exceptions.propagate(e);
-        } finally {
-            writesShuttingDown = false;
-        }
-    }
-    
-    @Override 
-    public void stop(boolean graceful) {
-        disableWriteAccess(graceful);
-        
-        if (executor != null) {
-            if (graceful) {
-                executor.shutdown();
-                try {
-                    // should be quick because we've just turned off writes, waiting for their completion
-                    executor.awaitTermination(1, TimeUnit.MINUTES);
-                } catch (InterruptedException e) {
-                    throw Exceptions.propagate(e);
-                }
-            } else {
-                executor.shutdownNow();
-            }
-        }
-    }
-
-    public PersistenceObjectStore getObjectStore() {
-        return objectStore;
-    }
-
-    protected StoreObjectAccessorWithLock getWriter(String path) {
-        String id = path.substring(path.lastIndexOf('/')+1);
-        synchronized (writers) {
-            StoreObjectAccessorWithLock writer = writers.get(id);
-            if (writer == null) {
-                writer = new StoreObjectAccessorLocking( objectStore.newAccessor(path) );
-                writers.put(id, writer);
-            }
-            return writer;
-        }
-    }
-
-    private Map<String,String> makeIdSubPathMap(Iterable<String> subPathLists) {
-        Map<String,String> result = MutableMap.of();
-        for (String subpath: subPathLists) {
-            String id = subpath;
-            id = id.substring(id.lastIndexOf('/')+1);
-            id = id.substring(id.lastIndexOf('\\')+1);
-            // assumes id is the filename; should work even if not, as id is later read from xpath
-            // but you'll get warnings (and possibility of loss if there is a collision)
-            result.put(id, subpath);
-        }
-        return result;
-    }
-    
-    protected BrooklynMementoRawData listMementoSubPathsAsData(final RebindExceptionHandler exceptionHandler) {
-        final BrooklynMementoRawData.Builder subPathDataBuilder = BrooklynMementoRawData.builder();
-
-        Stopwatch stopwatch = Stopwatch.createStarted();
-        try {
-            for (BrooklynObjectType type: BrooklynPersistenceUtils.STANDARD_BROOKLYN_OBJECT_TYPE_PERSISTENCE_ORDER)
-                subPathDataBuilder.putAll(type, makeIdSubPathMap(objectStore.listContentsWithSubPath(type.getSubPathName())));
-            
-        } catch (Exception e) {
-            Exceptions.propagateIfFatal(e);
-            exceptionHandler.onLoadMementoFailed(BrooklynObjectType.UNKNOWN, "Failed to list files", e);
-            throw new IllegalStateException("Failed to list memento files in "+objectStore, e);
-        }
-
-        BrooklynMementoRawData subPathData = subPathDataBuilder.build();
-        LOG.debug("Loaded rebind lists; took {}: {} entities, {} locations, {} policies, {} enrichers, {} feeds, {} catalog items; from {}", new Object[]{
-            Time.makeTimeStringRounded(stopwatch),
-            subPathData.getEntities().size(), subPathData.getLocations().size(), subPathData.getPolicies().size(), subPathData.getEnrichers().size(), 
-            subPathData.getFeeds().size(), subPathData.getCatalogItems().size(),
-            objectStore.getSummaryName() });
-        
-        return subPathData;
-    }
-    
-    public BrooklynMementoRawData loadMementoRawData(final RebindExceptionHandler exceptionHandler) {
-        BrooklynMementoRawData subPathData = listMementoSubPathsAsData(exceptionHandler);
-        
-        final BrooklynMementoRawData.Builder builder = BrooklynMementoRawData.builder();
-        
-        Visitor loaderVisitor = new Visitor() {
-            @Override
-            public void visit(BrooklynObjectType type, String id, String contentsSubpath) throws Exception {
-                String contents = null;
-                try {
-                    contents = read(contentsSubpath);
-                } catch (Exception e) {
-                    Exceptions.propagateIfFatal(e);
-                    exceptionHandler.onLoadMementoFailed(type, "memento "+id+" read error", e);
-                }
-                
-                String xmlId = (String) XmlUtil.xpath(contents, "/"+type.toCamelCase()+"/id");
-                String safeXmlId = Strings.makeValidFilename(xmlId);
-                if (!Objects.equal(id, safeXmlId))
-                    LOG.warn("ID mismatch on "+type.toCamelCase()+", "+id+" from path, "+safeXmlId+" from xml");
-                
-                builder.put(type, xmlId, contents);
-            }
-        };
-
-        Stopwatch stopwatch = Stopwatch.createStarted();
-
-        visitMemento("loading raw", subPathData, loaderVisitor, exceptionHandler);
-        
-        BrooklynMementoRawData result = builder.build();
-
-        if (LOG.isDebugEnabled()) {
-            LOG.debug("Loaded rebind raw data; took {}; {} entities, {} locations, {} policies, {} enrichers, {} feeds, {} catalog items, from {}", new Object[]{
-                     Time.makeTimeStringRounded(stopwatch.elapsed(TimeUnit.MILLISECONDS)), result.getEntities().size(), 
-                     result.getLocations().size(), result.getPolicies().size(), result.getEnrichers().size(),
-                     result.getFeeds().size(), result.getCatalogItems().size(),
-                     objectStore.getSummaryName() });
-        }
-
-        return result;
-    }
-
-    @Override
-    public BrooklynMementoManifest loadMementoManifest(BrooklynMementoRawData mementoData, final RebindExceptionHandler exceptionHandler) throws IOException {
-        if (mementoData==null)
-            mementoData = loadMementoRawData(exceptionHandler);
-        
-        final BrooklynMementoManifestImpl.Builder builder = BrooklynMementoManifestImpl.builder();
-
-        Visitor visitor = new Visitor() {
-            @Override
-            public void visit(BrooklynObjectType type, String objectId, final String contents) throws Exception {
-                final String prefix = "/"+type.toCamelCase()+"/";
-
-                class XPathHelper {
-                    private String get(String innerPath) {
-                        return (String) XmlUtil.xpath(contents, prefix+innerPath);
-                    }
-                }
-                XPathHelper x = new XPathHelper();
-                
-                switch (type) {
-                    case ENTITY:
-                        builder.entity(x.get("id"), x.get("type"), 
-                            Strings.emptyToNull(x.get("parent")), Strings.emptyToNull(x.get("catalogItemId")));
-                        break;
-                    case LOCATION:
-                    case POLICY:
-                    case ENRICHER:
-                    case FEED:
-                        builder.putType(type, x.get("id"), x.get("type"));
-                        break;
-                    case CATALOG_ITEM:
-                        try {
-                            CatalogItemMemento memento = (CatalogItemMemento) getSerializerWithStandardClassLoader().fromString(contents);
-                            if (memento == null) {
-                                LOG.warn("No "+type.toCamelCase()+"-memento deserialized from " + objectId + "; ignoring and continuing");
-                            } else {
-                                builder.catalogItem(memento);
-                            }
-                        } catch (Exception e) {
-                            exceptionHandler.onLoadMementoFailed(type, "memento "+objectId+" early catalog deserialization error", e);
-                        }
-                        break;
-                    default:
-                        throw new IllegalStateException("Unexpected brooklyn type: "+type);
-                }
-            }
-        };
-
-        Stopwatch stopwatch = Stopwatch.createStarted();
-
-        visitMemento("manifests", mementoData, visitor, exceptionHandler);
-        
-        BrooklynMementoManifest result = builder.build();
-
-        if (LOG.isDebugEnabled()) {
-            LOG.debug("Loaded rebind manifests; took {}: {} entities, {} locations, {} policies, {} enrichers, {} feeds, {} catalog items; from {}", new Object[]{
-                     Time.makeTimeStringRounded(stopwatch), 
-                     result.getEntityIdToManifest().size(), result.getLocationIdToType().size(), 
-                     result.getPolicyIdToType().size(), result.getEnricherIdToType().size(), result.getFeedIdToType().size(), 
-                     result.getCatalogItemMementos().size(),
-                     objectStore.getSummaryName() });
-        }
-
-        return result;
-    }
-    
-    @Override
-    public BrooklynMemento loadMemento(BrooklynMementoRawData mementoData, final LookupContext lookupContext, final RebindExceptionHandler exceptionHandler) throws IOException {
-        if (mementoData==null)
-            mementoData = loadMementoRawData(exceptionHandler);
-
-        Stopwatch stopwatch = Stopwatch.createStarted();
-
-        final BrooklynMementoImpl.Builder builder = BrooklynMementoImpl.builder();
-        
-        Visitor visitor = new Visitor() {
-            @Override
-            public void visit(BrooklynObjectType type, String objectId, String contents) throws Exception {
-                try {
-                    Memento memento = (Memento) getSerializerWithCustomClassLoader(lookupContext, type, objectId).fromString(contents);
-                    if (memento == null) {
-                        LOG.warn("No "+type.toCamelCase()+"-memento deserialized from " + objectId + "; ignoring and continuing");
-                    } else {
-                        builder.memento(memento);
-                    }
-                } catch (Exception e) {
-                    exceptionHandler.onLoadMementoFailed(type, "memento "+objectId+" deserialization error", e);
-                }
-            }
-
-        };
-
-        // TODO not convinced this is single threaded on reads; maybe should get a new one each time?
-        getSerializerWithStandardClassLoader().setLookupContext(lookupContext);
-        try {
-            visitMemento("deserialization", mementoData, visitor, exceptionHandler);
-        } finally {
-            getSerializerWithStandardClassLoader().unsetLookupContext();
-        }
-
-        BrooklynMemento result = builder.build();
-        
-        if (LOG.isDebugEnabled()) {
-            LOG.debug("Loaded rebind mementos; took {}: {} entities, {} locations, {} policies, {} enrichers, {} feeds, {} catalog items, from {}", new Object[]{
-                      Time.makeTimeStringRounded(stopwatch.elapsed(TimeUnit.MILLISECONDS)), result.getEntityIds().size(), 
-                      result.getLocationIds().size(), result.getPolicyIds().size(), result.getEnricherIds().size(), 
-                      result.getFeedIds().size(), result.getCatalogItemIds().size(),
-                      objectStore.getSummaryName() });
-        }
-        
-        return result;
-    }
-    
-    protected interface Visitor {
-        public void visit(BrooklynObjectType type, String id, String contents) throws Exception;
-    }
-    
-    protected void visitMemento(final String phase, final BrooklynMementoRawData rawData, final Visitor visitor, final RebindExceptionHandler exceptionHandler) {
-        List<ListenableFuture<?>> futures = Lists.newArrayList();
-        
-        class VisitorWrapper implements Runnable {
-            private final BrooklynObjectType type;
-            private final Map.Entry<String,String> objectIdAndData;
-            public VisitorWrapper(BrooklynObjectType type, Map.Entry<String,String> objectIdAndData) {
-                this.type = type;
-                this.objectIdAndData = objectIdAndData;
-            }
-            public void run() {
-                try {
-                    visitor.visit(type, objectIdAndData.getKey(), objectIdAndData.getValue());
-                } catch (Exception e) {
-                    Exceptions.propagateIfFatal(e);
-                    exceptionHandler.onLoadMementoFailed(type, "memento "+objectIdAndData.getKey()+" "+phase+" error", e);
-                }
-            }
-        }
-        
-        for (BrooklynObjectType type: BrooklynPersistenceUtils.STANDARD_BROOKLYN_OBJECT_TYPE_PERSISTENCE_ORDER) {
-            for (final Map.Entry<String,String> entry : rawData.getObjectsOfType(type).entrySet()) {
-                futures.add(executor.submit(new VisitorWrapper(type, entry)));
-            }
-        }
-
-        try {
-            // Wait for all, failing fast if any exceptions.
-            Futures.allAsList(futures).get();
-        } catch (Exception e) {
-            Exceptions.propagateIfFatal(e);
-            
-            List<Exception> exceptions = Lists.newArrayList();
-            
-            for (ListenableFuture<?> future : futures) {
-                if (future.isDone()) {
-                    try {
-                        future.get();
-                    } catch (InterruptedException e2) {
-                        throw Exceptions.propagate(e2);
-                    } catch (ExecutionException e2) {
-                        LOG.warn("Problem loading memento ("+phase+"): "+e2, e2);
-                        exceptions.add(e2);
-                    }
-                    future.cancel(true);
-                }
-            }
-            if (exceptions.isEmpty()) {
-                throw Exceptions.propagate(e);
-            } else {
-                // Normally there should be at lesat one failure; otherwise all.get() would not have failed.
-                throw new CompoundRuntimeException("Problem loading mementos ("+phase+")", exceptions);
-            }
-        }
-    }
-
-    protected void checkWritesAllowed() {
-        if (!writesAllowed && !writesShuttingDown) {
-            throw new IllegalStateException("Writes not allowed in "+this);
-        }
-    }
-    
-    /** See {@link BrooklynPersistenceUtils} for conveniences for using this method. */
-    @Override
-    @Beta
-    public void checkpoint(BrooklynMementoRawData newMemento, PersistenceExceptionHandler exceptionHandler) {
-        checkWritesAllowed();
-        try {
-            lock.writeLock().lockInterruptibly();
-        } catch (InterruptedException e) {
-            throw Exceptions.propagate(e);
-        }
-        
-        try {
-            objectStore.prepareForMasterUse();
-            
-            Stopwatch stopwatch = Stopwatch.createStarted();
-            List<ListenableFuture<?>> futures = Lists.newArrayList();
-            
-            for (BrooklynObjectType type: BrooklynPersistenceUtils.STANDARD_BROOKLYN_OBJECT_TYPE_PERSISTENCE_ORDER) {
-                for (Map.Entry<String, String> entry : newMemento.getObjectsOfType(type).entrySet()) {
-                    futures.add(asyncPersist(type.getSubPathName(), type, entry.getKey(), entry.getValue(), exceptionHandler));
-                }
-            }
-            
-            try {
-                // Wait for all the tasks to complete or fail, rather than aborting on the first failure.
-                // But then propagate failure if any fail. (hence the two calls).
-                Futures.successfulAsList(futures).get();
-                Futures.allAsList(futures).get();
-            } catch (Exception e) {
-                throw Exceptions.propagate(e);
-            }
-            if (LOG.isDebugEnabled()) LOG.debug("Checkpointed entire memento in {}", Time.makeTimeStringRounded(stopwatch));
-        } finally {
-            lock.writeLock().unlock();
-        }
-    }
-
-    @Override
-    public void delta(Delta delta, PersistenceExceptionHandler exceptionHandler) {
-        checkWritesAllowed();
-
-        while (!queuedDeltas.isEmpty()) {
-            Delta extraDelta = queuedDeltas.remove(0);
-            doDelta(extraDelta, exceptionHandler, true);
-        }
-
-        doDelta(delta, exceptionHandler, false);
-    }
-    
-    protected void doDelta(Delta delta, PersistenceExceptionHandler exceptionHandler, boolean previouslyQueued) {
-        Stopwatch stopwatch = deltaImpl(delta, exceptionHandler);
-        
-        if (LOG.isDebugEnabled()) LOG.debug("Checkpointed "+(previouslyQueued ? "previously queued " : "")+"delta of memento in {}: "
-                + "updated {} entities, {} locations, {} policies, {} enrichers, {} catalog items; "
-                + "removed {} entities, {} locations, {} policies, {} enrichers, {} catalog items",
-                    new Object[] {Time.makeTimeStringRounded(stopwatch),
-                        delta.entities().size(), delta.locations().size(), delta.policies().size(), delta.enrichers().size(), delta.catalogItems().size(),
-                        delta.removedEntityIds().size(), delta.removedLocationIds().size(), delta.removedPolicyIds().size(), delta.removedEnricherIds().size(), delta.removedCatalogItemIds().size()});
-    }
-    
-    @Override
-    public void queueDelta(Delta delta) {
-        queuedDeltas.add(delta);
-    }
-    
-    /**
-     * Concurrent calls will queue-up (the lock is "fair", which means an "approximately arrival-order policy").
-     * Current usage is with the {@link PeriodicDeltaChangeListener} so we expect only one call at a time.
-     * 
-     * TODO Longer term, if we care more about concurrent calls we could merge the queued deltas so that we
-     * don't do unnecessary repeated writes of an entity.
-     */
-    private Stopwatch deltaImpl(Delta delta, PersistenceExceptionHandler exceptionHandler) {
-        try {
-            lock.writeLock().lockInterruptibly();
-        } catch (InterruptedException e) {
-            throw Exceptions.propagate(e);
-        }
-        try {
-            objectStore.prepareForMasterUse();
-            
-            Stopwatch stopwatch = Stopwatch.createStarted();
-            List<ListenableFuture<?>> futures = Lists.newArrayList();
-            
-            for (BrooklynObjectType type: BrooklynPersistenceUtils.STANDARD_BROOKLYN_OBJECT_TYPE_PERSISTENCE_ORDER) {
-                for (Memento entity : delta.getObjectsOfType(type)) {
-                    futures.add(asyncPersist(type.getSubPathName(), entity, exceptionHandler));
-                }
-            }
-            for (BrooklynObjectType type: BrooklynPersistenceUtils.STANDARD_BROOKLYN_OBJECT_TYPE_PERSISTENCE_ORDER) {
-                for (String id : delta.getRemovedIdsOfType(type)) {
-                    futures.add(asyncDelete(type.getSubPathName(), id, exceptionHandler));
-                }
-            }
-            
-            try {
-                // Wait for all the tasks to complete or fail, rather than aborting on the first failure.
-                // But then propagate failure if any fail. (hence the two calls).
-                Futures.successfulAsList(futures).get();
-                Futures.allAsList(futures).get();
-            } catch (Exception e) {
-                throw Exceptions.propagate(e);
-            }
-            
-            return stopwatch;
-        } finally {
-            lock.writeLock().unlock();
-        }
-    }
-
-    @Override
-    public void waitForWritesCompleted(Duration timeout) throws InterruptedException, TimeoutException {
-        boolean locked = lock.readLock().tryLock(timeout.toMillisecondsRoundingUp(), TimeUnit.MILLISECONDS);
-        if (locked) {
-            ImmutableSet<StoreObjectAccessorWithLock> wc;
-            synchronized (writers) {
-                wc = ImmutableSet.copyOf(writers.values());
-            }
-            lock.readLock().unlock();
-            
-            // Belt-and-braces: the lock above should be enough to ensure no outstanding writes, because
-            // each writer is now synchronous.
-            for (StoreObjectAccessorWithLock writer : wc) {
-                writer.waitForCurrentWrites(timeout);
-            }
-        } else {
-            throw new TimeoutException("Timeout waiting for writes to "+objectStore);
-        }
-    }
-
-    private String read(String subPath) {
-        StoreObjectAccessor objectAccessor = objectStore.newAccessor(subPath);
-        return objectAccessor.get();
-    }
-
-    private void persist(String subPath, Memento memento, PersistenceExceptionHandler exceptionHandler) {
-        try {
-            getWriter(getPath(subPath, memento.getId())).put(getSerializerWithStandardClassLoader().toString(memento));
-        } catch (Exception e) {
-            exceptionHandler.onPersistMementoFailed(memento, e);
-        }
-    }
-    
-    private void persist(String subPath, BrooklynObjectType type, String id, String content, PersistenceExceptionHandler exceptionHandler) {
-        try {
-            if (content==null) {
-                LOG.warn("Null content for "+type+" "+id);
-            }
-            getWriter(getPath(subPath, id)).put(content);
-        } catch (Exception e) {
-            exceptionHandler.onPersistRawMementoFailed(type, id, e);
-        }
-    }
-    
-    private void delete(String subPath, String id, PersistenceExceptionHandler exceptionHandler) {
-        try {
-            StoreObjectAccessorWithLock w = getWriter(getPath(subPath, id));
-            w.delete();
-            synchronized (writers) {
-                writers.remove(id);
-            }
-        } catch (Exception e) {
-            exceptionHandler.onDeleteMementoFailed(id, e);
-        }
-    }
-
-    private ListenableFuture<?> asyncPersist(final String subPath, final Memento memento, final PersistenceExceptionHandler exceptionHandler) {
-        return executor.submit(new Runnable() {
-            public void run() {
-                persist(subPath, memento, exceptionHandler);
-            }});
-    }
-
-    private ListenableFuture<?> asyncPersist(final String subPath, final BrooklynObjectType type, final String id, final String content, final PersistenceExceptionHandler exceptionHandler) {
-        return executor.submit(new Runnable() {
-            public void run() {
-                persist(subPath, type, id, content, exceptionHandler);
-            }});
-    }
-
-    private ListenableFuture<?> asyncDelete(final String subPath, final String id, final PersistenceExceptionHandler exceptionHandler) {
-        return executor.submit(new Runnable() {
-            public void run() {
-                delete(subPath, id, exceptionHandler);
-            }});
-    }
-    
-    private String getPath(String subPath, String id) {
-        return subPath+"/"+Strings.makeValidFilename(id);
-    }
-
-    @Override
-    public String getBackingStoreDescription() {
-        return getObjectStore().getSummaryName();
-    }
-}


[29/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/software/MachineLifecycleEffectorTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/software/MachineLifecycleEffectorTasks.java b/software/base/src/main/java/brooklyn/entity/software/MachineLifecycleEffectorTasks.java
deleted file mode 100644
index 927816d..0000000
--- a/software/base/src/main/java/brooklyn/entity/software/MachineLifecycleEffectorTasks.java
+++ /dev/null
@@ -1,949 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software;
-
-import java.io.Serializable;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.MachineManagementMixins;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.api.location.MachineManagementMixins.SuspendsMachines;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.config.Sanitizer;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.effector.core.EffectorBody;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
-import org.apache.brooklyn.entity.stock.EffectorStartableImpl.StartParameters;
-import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.entity.trait.StartableMethods;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Supplier;
-import com.google.common.base.Suppliers;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.basic.SoftwareProcess.RestartSoftwareParameters;
-import brooklyn.entity.basic.SoftwareProcess.RestartSoftwareParameters.RestartMachineMode;
-import brooklyn.entity.basic.SoftwareProcess.StopSoftwareParameters;
-import brooklyn.entity.basic.SoftwareProcess.StopSoftwareParameters.StopMode;
-
-import org.apache.brooklyn.location.basic.AbstractLocation;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.location.basic.Machines;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.location.cloud.CloudLocationConfig;
-import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.net.UserAndHostAndPort;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.ssh.BashCommands;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.time.Duration;
-
-/**
- * Default skeleton for start/stop/restart tasks on machines.
- * <p>
- * Knows how to provision machines, making use of {@link ProvidesProvisioningFlags#obtainProvisioningFlags(MachineProvisioningLocation)},
- * and provides hooks for injecting behaviour at common places.
- * <p>
- * Methods are designed for overriding, with the convention that *Async methods should queue (and not block).
- * The following methods are commonly overridden (and you can safely queue tasks, block, or return immediately in them):
- * <ul>
- *  <li> {@link #startProcessesAtMachine(Supplier)} (required)
- *  <li> {@link #stopProcessesAtMachine()} (required, but can be left blank if you assume the VM will be destroyed)
- *  <li> {@link #preStartCustom(MachineLocation)}
- *  <li> {@link #postStartCustom()}
- *  <li> {@link #preStopCustom()}
- *  <li> {@link #postStopCustom()}
- * </ul>
- * Note methods at this level typically look after the {@link Attributes#SERVICE_STATE} sensor.
- *
- * @since 0.6.0
- */
-@Beta
-public abstract class MachineLifecycleEffectorTasks {
-
-    private static final Logger log = LoggerFactory.getLogger(MachineLifecycleEffectorTasks.class);
-
-    public static final ConfigKey<Boolean> ON_BOX_BASE_DIR_RESOLVED = ConfigKeys.newBooleanConfigKey("onbox.base.dir.resolved",
-        "Whether the on-box base directory has been resolved (for internal use)");
-
-    public static final ConfigKey<Collection<? extends Location>> LOCATIONS = StartParameters.LOCATIONS;
-    public static final ConfigKey<Duration> STOP_PROCESS_TIMEOUT = ConfigKeys.newConfigKey(Duration.class,
-            "process.stop.timeout", "How long to wait for the processes to be stopped; use null to mean forever", Duration.TWO_MINUTES);
-
-    protected final MachineInitTasks machineInitTasks = new MachineInitTasks();
-    
-    /** Attaches lifecycle effectors (start, restart, stop) to the given entity post-creation. */
-    public void attachLifecycleEffectors(Entity entity) {
-        ((EntityInternal) entity).getMutableEntityType().addEffector(newStartEffector());
-        ((EntityInternal) entity).getMutableEntityType().addEffector(newRestartEffector());
-        ((EntityInternal) entity).getMutableEntityType().addEffector(newStopEffector());
-    }
-
-    /**
-     * Return an effector suitable for setting in a {@code public static final} or attaching dynamically.
-     * <p>
-     * The effector overrides the corresponding effector from {@link Startable} with
-     * the behaviour in this lifecycle class instance.
-     */
-    public Effector<Void> newStartEffector() {
-        return Effectors.effector(Startable.START).impl(newStartEffectorTask()).build();
-    }
-
-    /** @see {@link #newStartEffector()} */
-    public Effector<Void> newRestartEffector() {
-        return Effectors.effector(Startable.RESTART)
-                .parameter(RestartSoftwareParameters.RESTART_CHILDREN)
-                .parameter(RestartSoftwareParameters.RESTART_MACHINE)
-                .impl(newRestartEffectorTask())
-                .build();
-    }
-    
-    /** @see {@link #newStartEffector()} */
-    public Effector<Void> newStopEffector() {
-        return Effectors.effector(Startable.STOP)
-                .parameter(StopSoftwareParameters.STOP_PROCESS_MODE)
-                .parameter(StopSoftwareParameters.STOP_MACHINE_MODE)
-                .impl(newStopEffectorTask())
-                .build();
-    }
-
-    /** @see {@link #newStartEffector()} */
-    public Effector<Void> newSuspendEffector() {
-        return Effectors.effector(Void.class, "suspend")
-                .description("Suspend the process/service represented by an entity")
-                .parameter(StopSoftwareParameters.STOP_PROCESS_MODE)
-                .parameter(StopSoftwareParameters.STOP_MACHINE_MODE)
-                .impl(newSuspendEffectorTask())
-                .build();
-    }
-
-    /**
-     * Returns the {@link EffectorBody} which supplies the implementation for the start effector.
-     * <p>
-     * Calls {@link #start(Collection)} in this class.
-     */
-    public EffectorBody<Void> newStartEffectorTask() {
-        // TODO included anonymous inner class for backwards compatibility with persisted state.
-        new EffectorBody<Void>() {
-            @Override
-            public Void call(ConfigBag parameters) {
-                Collection<? extends Location> locations  = null;
-
-                Object locationsRaw = parameters.getStringKey(LOCATIONS.getName());
-                locations = Locations.coerceToCollection(entity().getManagementContext(), locationsRaw);
-
-                if (locations==null) {
-                    // null/empty will mean to inherit from parent
-                    locations = Collections.emptyList();
-                }
-
-                start(locations);
-                return null;
-            }
-        };
-        return new StartEffectorBody();
-    }
-
-    private class StartEffectorBody extends EffectorBody<Void> {
-        @Override
-        public Void call(ConfigBag parameters) {
-            Collection<? extends Location> locations = null;
-
-            Object locationsRaw = parameters.getStringKey(LOCATIONS.getName());
-            locations = Locations.coerceToCollection(entity().getManagementContext(), locationsRaw);
-
-            if (locations == null) {
-                // null/empty will mean to inherit from parent
-                locations = Collections.emptyList();
-            }
-
-            start(locations);
-            return null;
-        }
-
-    }
-
-    /**
-     * Calls {@link #restart(ConfigBag)}.
-     *
-     * @see {@link #newStartEffectorTask()}
-     */
-    public EffectorBody<Void> newRestartEffectorTask() {
-        // TODO included anonymous inner class for backwards compatibility with persisted state.
-        new EffectorBody<Void>() {
-            @Override
-            public Void call(ConfigBag parameters) {
-                restart(parameters);
-                return null;
-            }
-        };
-        return new RestartEffectorBody();
-    }
-
-    private class RestartEffectorBody extends EffectorBody<Void> {
-        @Override
-        public Void call(ConfigBag parameters) {
-            restart(parameters);
-            return null;
-        }
-    }
-
-    /**
-     * Calls {@link #stop(ConfigBag)}.
-     *
-     * @see {@link #newStartEffectorTask()}
-     */
-    public EffectorBody<Void> newStopEffectorTask() {
-        // TODO included anonymous inner class for backwards compatibility with persisted state.
-        new EffectorBody<Void>() {
-            @Override
-            public Void call(ConfigBag parameters) {
-                stop(parameters);
-                return null;
-            }
-        };
-        return new StopEffectorBody();
-    }
-
-    private class StopEffectorBody extends EffectorBody<Void> {
-        @Override
-        public Void call(ConfigBag parameters) {
-            stop(parameters);
-            return null;
-        }
-    }
-
-    /**
-     * Calls {@link #suspend(ConfigBag)}.
-     *
-     * @see {@link #newStartEffectorTask()}
-     */
-    public EffectorBody<Void> newSuspendEffectorTask() {
-        return new SuspendEffectorBody();
-    }
-
-    private class SuspendEffectorBody extends EffectorBody<Void> {
-        @Override
-        public Void call(ConfigBag parameters) {
-            suspend(parameters);
-            return null;
-        }
-    }
-
-    protected EntityInternal entity() {
-        return (EntityInternal) BrooklynTaskTags.getTargetOrContextEntity(Tasks.current());
-    }
-
-    protected Location getLocation(@Nullable Collection<? extends Location> locations) {
-        if (locations==null || locations.isEmpty()) locations = entity().getLocations();
-        if (locations.isEmpty()) {
-            MachineProvisioningLocation<?> provisioner = entity().getAttribute(SoftwareProcess.PROVISIONING_LOCATION);
-            if (provisioner!=null) locations = Arrays.<Location>asList(provisioner);
-        }
-        locations = Locations.getLocationsCheckingAncestors(locations, entity());
-
-        Maybe<MachineLocation> ml = Locations.findUniqueMachineLocation(locations);
-        if (ml.isPresent()) return ml.get();
-
-        if (locations.isEmpty())
-            throw new IllegalArgumentException("No locations specified when starting "+entity());
-        if (locations.size() != 1 || Iterables.getOnlyElement(locations)==null)
-            throw new IllegalArgumentException("Ambiguous locations detected when starting "+entity()+": "+locations);
-        return Iterables.getOnlyElement(locations);
-    }
-    
-    /** runs the tasks needed to start, wrapped by setting {@link Attributes#SERVICE_STATE_EXPECTED} appropriately */ 
-    public void start(Collection<? extends Location> locations) {
-        ServiceStateLogic.setExpectedState(entity(), Lifecycle.STARTING);
-        try {
-            startInLocations(locations);
-            DynamicTasks.waitForLast();
-            ServiceStateLogic.setExpectedState(entity(), Lifecycle.RUNNING);
-        } catch (Throwable t) {
-            ServiceStateLogic.setExpectedState(entity(), Lifecycle.ON_FIRE);
-            throw Exceptions.propagate(t);
-        }
-    }
-
-    /** Asserts there is a single location and calls {@link #startInLocation(Location)} with that location. */
-    protected void startInLocations(Collection<? extends Location> locations) {
-        startInLocation(getLocation(locations));
-    }
-
-    /** Dispatches to the appropriate method(s) to start in the given location. */
-    protected void startInLocation(final Location location) {
-        Supplier<MachineLocation> locationS = null;
-        if (location instanceof MachineProvisioningLocation) {
-            Task<MachineLocation> machineTask = provisionAsync((MachineProvisioningLocation<?>)location);
-            locationS = Tasks.supplier(machineTask);
-        } else if (location instanceof MachineLocation) {
-            locationS = Suppliers.ofInstance((MachineLocation)location);
-        }
-        Preconditions.checkState(locationS != null, "Unsupported location "+location+", when starting "+entity());
-
-        final Supplier<MachineLocation> locationSF = locationS;
-        preStartAtMachineAsync(locationSF);
-        DynamicTasks.queue("start (processes)", new StartProcessesAtMachineTask(locationSF));
-        postStartAtMachineAsync();
-    }
-
-    private class StartProcessesAtMachineTask implements Runnable {
-        private final Supplier<MachineLocation> machineSupplier;
-        private StartProcessesAtMachineTask(Supplier<MachineLocation> machineSupplier) {
-            this.machineSupplier = machineSupplier;
-        }
-        @Override
-        public void run() {
-            startProcessesAtMachine(machineSupplier);
-        }
-    }
-
-    /**
-     * Returns a queued {@link Task} which provisions a machine in the given location
-     * and returns that machine. The task can be used as a supplier to subsequent methods.
-     */
-    protected Task<MachineLocation> provisionAsync(final MachineProvisioningLocation<?> location) {
-        return DynamicTasks.queue(Tasks.<MachineLocation>builder().name("provisioning (" + location.getDisplayName() + ")").body(
-                new ProvisionMachineTask(location)).build());
-    }
-
-    private class ProvisionMachineTask implements Callable<MachineLocation> {
-        final MachineProvisioningLocation<?> location;
-
-        private ProvisionMachineTask(MachineProvisioningLocation<?> location) {
-            this.location = location;
-        }
-
-        public MachineLocation call() throws Exception {
-            // Blocks if a latch was configured.
-            entity().getConfig(BrooklynConfigKeys.PROVISION_LATCH);
-            final Map<String, Object> flags = obtainProvisioningFlags(location);
-            if (!(location instanceof LocalhostMachineProvisioningLocation))
-                log.info("Starting {}, obtaining a new location instance in {} with ports {}", new Object[]{entity(), location, flags.get("inboundPorts")});
-            entity().setAttribute(SoftwareProcess.PROVISIONING_LOCATION, location);
-            MachineLocation machine;
-            try {
-                machine = Tasks.withBlockingDetails("Provisioning machine in " + location, new ObtainLocationTask(location, flags));
-                if (machine == null)
-                    throw new NoMachinesAvailableException("Failed to obtain machine in " + location.toString());
-            } catch (Exception e) {
-                throw Exceptions.propagate(e);
-            }
-
-            if (log.isDebugEnabled())
-                log.debug("While starting {}, obtained new location instance {}", entity(),
-                        (machine instanceof SshMachineLocation ?
-                         machine + ", details " + ((SshMachineLocation) machine).getUser() + ":" + Sanitizer.sanitize(((SshMachineLocation) machine).config().getLocalBag())
-                                                               : machine));
-            return machine;
-        }
-    }
-
-    private static class ObtainLocationTask implements Callable<MachineLocation> {
-        final MachineProvisioningLocation<?> location;
-        final Map<String, Object> flags;
-
-        private ObtainLocationTask(MachineProvisioningLocation<?> location, Map<String, Object> flags) {
-            this.flags = flags;
-            this.location = location;
-        }
-
-        public MachineLocation call() throws NoMachinesAvailableException {
-            return location.obtain(flags);
-        }
-    }
-
-    /** Wraps a call to {@link #preStartCustom(MachineLocation)}, after setting the hostname and address. */
-    protected void preStartAtMachineAsync(final Supplier<MachineLocation> machineS) {
-        DynamicTasks.queue("pre-start", new PreStartTask(machineS.get()));
-    }
-
-    private class PreStartTask implements Runnable {
-        final MachineLocation machine;
-        private PreStartTask(MachineLocation machine) {
-            this.machine = machine;
-        }
-        public void run() {
-            log.info("Starting {} on machine {}", entity(), machine);
-            Collection<Location> oldLocs = entity().getLocations();
-            if (!oldLocs.isEmpty()) {
-                List<MachineLocation> oldSshLocs = ImmutableList.copyOf(Iterables.filter(oldLocs, MachineLocation.class));
-                if (!oldSshLocs.isEmpty()) {
-                    // check if existing locations are compatible
-                    log.debug("Entity " + entity() + " had machine locations " + oldSshLocs + " when starting at " + machine + "; checking if they are compatible");
-                    for (MachineLocation oldLoc : oldSshLocs) {
-                        // machines are deemed compatible if hostname and address are the same, or they are localhost
-                        // this allows a machine create by jclouds to then be defined with an ip-based spec
-                        if (!"localhost".equals(machine.getConfig(AbstractLocation.ORIGINAL_SPEC))) {
-                            checkLocationParametersCompatible(machine, oldLoc, "hostname",
-                                    oldLoc.getAddress().getHostName(), machine.getAddress().getHostName());
-                            checkLocationParametersCompatible(machine, oldLoc, "address",
-                                    oldLoc.getAddress().getHostAddress(), machine.getAddress().getHostAddress());
-                        }
-                    }
-                    log.debug("Entity " + entity() + " old machine locations " + oldSshLocs + " were compatible, removing them to start at " + machine);
-                    entity().removeLocations(oldSshLocs);
-                }
-            }
-            entity().addLocations(ImmutableList.of((Location) machine));
-
-            // elsewhere we rely on (public) hostname being set _after_ subnet_hostname
-            // (to prevent the tiny possibility of races resulting in hostname being returned
-            // simply because subnet is still being looked up)
-            Maybe<String> lh = Machines.getSubnetHostname(machine);
-            Maybe<String> la = Machines.getSubnetIp(machine);
-            if (lh.isPresent()) entity().setAttribute(Attributes.SUBNET_HOSTNAME, lh.get());
-            if (la.isPresent()) entity().setAttribute(Attributes.SUBNET_ADDRESS, la.get());
-            entity().setAttribute(Attributes.HOSTNAME, machine.getAddress().getHostName());
-            entity().setAttribute(Attributes.ADDRESS, machine.getAddress().getHostAddress());
-            if (machine instanceof SshMachineLocation) {
-                @SuppressWarnings("resource")
-                SshMachineLocation sshMachine = (SshMachineLocation) machine;
-                UserAndHostAndPort sshAddress = UserAndHostAndPort.fromParts(sshMachine.getUser(), sshMachine.getAddress().getHostName(), sshMachine.getPort());
-                entity().setAttribute(Attributes.SSH_ADDRESS, sshAddress);
-            }
-
-            if (Boolean.TRUE.equals(entity().getConfig(SoftwareProcess.OPEN_IPTABLES))) {
-                if (machine instanceof SshMachineLocation) {
-                    Iterable<Integer> inboundPorts = (Iterable<Integer>) machine.config().get(CloudLocationConfig.INBOUND_PORTS);
-                    machineInitTasks.openIptablesAsync(inboundPorts, (SshMachineLocation)machine);
-                } else {
-                    log.warn("Ignoring flag OPEN_IPTABLES on non-ssh location {}", machine);
-                }
-            }
-            if (Boolean.TRUE.equals(entity().getConfig(SoftwareProcess.STOP_IPTABLES))) {
-                if (machine instanceof SshMachineLocation) {
-                    machineInitTasks.stopIptablesAsync((SshMachineLocation)machine);
-                } else {
-                    log.warn("Ignoring flag STOP_IPTABLES on non-ssh location {}", machine);
-                }
-            }
-            if (Boolean.TRUE.equals(entity().getConfig(SoftwareProcess.DONT_REQUIRE_TTY_FOR_SUDO))) {
-                if (machine instanceof SshMachineLocation) {
-                    machineInitTasks.dontRequireTtyForSudoAsync((SshMachineLocation)machine);
-                } else {
-                    log.warn("Ignoring flag DONT_REQUIRE_TTY_FOR_SUDO on non-ssh location {}", machine);
-                }
-            }
-            resolveOnBoxDir(entity(), machine);
-            preStartCustom(machine);
-        }
-    }
-
-    /**
-     * Resolves the on-box dir.
-     * <p>
-     * Initialize and pre-create the right onbox working dir, if an ssh machine location.
-     * Logs a warning if not.
-     */
-    @SuppressWarnings("deprecation")
-    public static String resolveOnBoxDir(EntityInternal entity, MachineLocation machine) {
-        String base = entity.getConfig(BrooklynConfigKeys.ONBOX_BASE_DIR);
-        if (base==null) base = machine.getConfig(BrooklynConfigKeys.ONBOX_BASE_DIR);
-        if (base!=null && Boolean.TRUE.equals(entity.getConfig(ON_BOX_BASE_DIR_RESOLVED))) return base;
-        if (base==null) base = entity.getManagementContext().getConfig().getConfig(BrooklynConfigKeys.ONBOX_BASE_DIR);
-        if (base==null) base = entity.getConfig(BrooklynConfigKeys.BROOKLYN_DATA_DIR);
-        if (base==null) base = machine.getConfig(BrooklynConfigKeys.BROOKLYN_DATA_DIR);
-        if (base==null) base = entity.getManagementContext().getConfig().getConfig(BrooklynConfigKeys.BROOKLYN_DATA_DIR);
-        if (base==null) base = "~/brooklyn-managed-processes";
-        if (base.equals("~")) base=".";
-        if (base.startsWith("~/")) base = "."+base.substring(1);
-
-        String resolvedBase = null;
-        if (entity.getConfig(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION) || machine.getConfig(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION)) {
-            if (log.isDebugEnabled()) log.debug("Skipping on-box base dir resolution for "+entity+" at "+machine);
-            if (!Os.isAbsolutish(base)) base = "~/"+base;
-            resolvedBase = Os.tidyPath(base);
-        } else if (machine instanceof SshMachineLocation) {
-            SshMachineLocation ms = (SshMachineLocation)machine;
-            ProcessTaskWrapper<Integer> baseTask = SshEffectorTasks.ssh(
-                BashCommands.alternatives("mkdir -p \"${BASE_DIR}\"",
-                    BashCommands.chain(
-                        BashCommands.sudo("mkdir -p \"${BASE_DIR}\""),
-                        BashCommands.sudo("chown "+ms.getUser()+" \"${BASE_DIR}\""))),
-                "cd ~",
-                "cd ${BASE_DIR}",
-                "echo BASE_DIR_RESULT':'`pwd`:BASE_DIR_RESULT")
-                .environmentVariable("BASE_DIR", base)
-                .requiringExitCodeZero()
-                .summary("initializing on-box base dir "+base).newTask();
-            DynamicTasks.queueIfPossible(baseTask).orSubmitAsync(entity);
-            resolvedBase = Strings.getFragmentBetween(baseTask.block().getStdout(), "BASE_DIR_RESULT:", ":BASE_DIR_RESULT");
-        }
-        if (resolvedBase==null) {
-            if (!Os.isAbsolutish(base)) base = "~/"+base;
-            resolvedBase = Os.tidyPath(base);
-            log.warn("Could not resolve on-box directory for "+entity+" at "+machine+"; using "+resolvedBase+", though this may not be accurate at the target (and may fail shortly)");
-        }
-        entity.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, resolvedBase);
-        entity.setConfig(ON_BOX_BASE_DIR_RESOLVED, true);
-        return resolvedBase;
-    }
-
-    protected void checkLocationParametersCompatible(MachineLocation oldLoc, MachineLocation newLoc, String paramSummary,
-            Object oldParam, Object newParam) {
-        if (oldParam==null || newParam==null || !oldParam.equals(newParam))
-            throw new IllegalStateException("Cannot start "+entity()+" in "+newLoc+" as it has already been started with incompatible location "+oldLoc+" " +
-                    "("+paramSummary+" not compatible: "+oldParam+" / "+newParam+"); "+newLoc+" may require manual removal.");
-    }
-
-    /**
-     * Default pre-start hooks.
-     * <p>
-     * Can be extended by subclasses if needed.
-     */
-    protected void preStartCustom(MachineLocation machine) {
-        ConfigToAttributes.apply(entity());
-
-        // Opportunity to block startup until other dependent components are available
-        Object val = entity().getConfig(SoftwareProcess.START_LATCH);
-        if (val != null) log.debug("{} finished waiting for start-latch; continuing...", entity(), val);
-    }
-
-    protected Map<String, Object> obtainProvisioningFlags(final MachineProvisioningLocation<?> location) {
-        if (entity() instanceof ProvidesProvisioningFlags) {
-            return ((ProvidesProvisioningFlags)entity()).obtainProvisioningFlags(location).getAllConfig();
-        }
-        return MutableMap.<String, Object>of();
-    }
-
-    protected abstract String startProcessesAtMachine(final Supplier<MachineLocation> machineS);
-
-    protected void postStartAtMachineAsync() {
-        DynamicTasks.queue("post-start", new PostStartTask());
-    }
-
-    private class PostStartTask implements Runnable {
-        public void run() {
-            postStartCustom();
-        }
-    }
-
-    /**
-     * Default post-start hooks.
-     * <p>
-     * Can be extended by subclasses, and typically will wait for confirmation of start.
-     * The service not set to running until after this. Also invoked following a restart.
-     */
-    protected void postStartCustom() {
-        // nothing by default
-    }
-
-    /**
-     * whether when 'auto' mode is specified, the machine should be stopped when the restart effector is called
-     * <p>
-     * with {@link MachineLifecycleEffectorTasks}, a machine will always get created on restart if there wasn't one already
-     * (unlike certain subclasses which might attempt a shortcut process-level restart)
-     * so there is no reason for default behaviour of restart to throw away a provisioned machine,
-     * hence default impl returns <code>false</code>.
-     * <p>
-     * if it is possible to tell that a machine is unhealthy, or if {@link #restart(ConfigBag)} is overridden,
-     * then it might be appropriate to return <code>true</code> here.
-     */
-    protected boolean getDefaultRestartStopsMachine() {
-        return false;
-    }
-
-    /**
-     * Default restart implementation for an entity.
-     * <p>
-     * Stops processes if possible, then starts the entity again.
-     */
-    public void restart(ConfigBag parameters) {
-        ServiceStateLogic.setExpectedState(entity(), Lifecycle.STOPPING);
-
-        RestartMachineMode isRestartMachine = parameters.get(RestartSoftwareParameters.RESTART_MACHINE_TYPED);
-        if (isRestartMachine==null)
-            isRestartMachine=RestartMachineMode.AUTO;
-        if (isRestartMachine==RestartMachineMode.AUTO)
-            isRestartMachine = getDefaultRestartStopsMachine() ? RestartMachineMode.TRUE : RestartMachineMode.FALSE;
-
-        // Calling preStopCustom without a corresponding postStopCustom invocation
-        // doesn't look right so use a separate callback pair; Also depending on the arguments
-        // stop() could be called which will call the {pre,post}StopCustom on its own.
-        DynamicTasks.queue("pre-restart", new PreRestartTask());
-
-        if (isRestartMachine==RestartMachineMode.FALSE) {
-            DynamicTasks.queue("stopping (process)", new StopProcessesAtMachineTask());
-        } else {
-            DynamicTasks.queue("stopping (machine)", new StopMachineTask());
-        }
-
-        DynamicTasks.queue("starting", new StartInLocationsTask());
-        restartChildren(parameters);
-        DynamicTasks.queue("post-restart", new PostRestartTask());
-
-        DynamicTasks.waitForLast();
-        ServiceStateLogic.setExpectedState(entity(), Lifecycle.RUNNING);
-    }
-
-    private class PreRestartTask implements Runnable {
-        @Override
-        public void run() {
-            preRestartCustom();
-        }
-    }
-    private class PostRestartTask implements Runnable {
-        @Override
-        public void run() {
-            postRestartCustom();
-        }
-    }
-    private class StartInLocationsTask implements Runnable {
-        @Override
-        public void run() {
-            // startInLocations will look up the location, and provision a machine if necessary
-            // (if it remembered the provisioning location)
-            ServiceStateLogic.setExpectedState(entity(), Lifecycle.STARTING);
-            startInLocations(null);
-        }
-    }
-
-    protected void restartChildren(ConfigBag parameters) {
-        // TODO should we consult ChildStartableMode?
-
-        Boolean isRestartChildren = parameters.get(RestartSoftwareParameters.RESTART_CHILDREN);
-        if (isRestartChildren==null || !isRestartChildren) {
-            return;
-        }
-
-        if (isRestartChildren) {
-            DynamicTasks.queue(StartableMethods.restartingChildren(entity(), parameters));
-            return;
-        }
-
-        throw new IllegalArgumentException("Invalid value '"+isRestartChildren+"' for "+RestartSoftwareParameters.RESTART_CHILDREN.getName());
-    }
-
-    /**
-     * Default stop implementation for an entity.
-     * <p>
-     * Aborts if already stopped, otherwise sets state {@link Lifecycle#STOPPING} then
-     * invokes {@link #preStopCustom()}, {@link #stopProcessesAtMachine()}, then finally
-     * {@link #stopAnyProvisionedMachines()} and sets state {@link Lifecycle#STOPPED}.
-     * If no errors were encountered call {@link #postStopCustom()} at the end.
-     */
-    public void stop(ConfigBag parameters) {
-        doStop(parameters, new StopAnyProvisionedMachinesTask());
-    }
-
-    /**
-     * As {@link #stop} but calling {@link #suspendAnyProvisionedMachines} rather than
-     * {@link #stopAnyProvisionedMachines}.
-     */
-    public void suspend(ConfigBag parameters) {
-        doStop(parameters, new SuspendAnyProvisionedMachinesTask());
-    }
-
-    protected void doStop(ConfigBag parameters, Callable<StopMachineDetails<Integer>> stopTask) {
-        preStopConfirmCustom();
-
-        log.info("Stopping {} in {}", entity(), entity().getLocations());
-
-        StopMode stopMachineMode = getStopMachineMode(parameters);
-        StopMode stopProcessMode = parameters.get(StopSoftwareParameters.STOP_PROCESS_MODE);
-
-        DynamicTasks.queue("pre-stop", new PreStopCustomTask());
-
-        Maybe<MachineLocation> machine = Machines.findUniqueMachineLocation(entity().getLocations());
-        Task<String> stoppingProcess = null;
-        if (canStop(stopProcessMode, entity())) {
-            stoppingProcess = DynamicTasks.queue("stopping (process)", new StopProcessesAtMachineTask());
-        }
-
-        Task<StopMachineDetails<Integer>> stoppingMachine = null;
-        if (canStop(stopMachineMode, machine.isAbsent())) {
-            // Release this machine (even if error trying to stop process - we rethrow that after)
-            stoppingMachine = DynamicTasks.queue("stopping (machine)", stopTask);
-
-            DynamicTasks.drain(entity().getConfig(STOP_PROCESS_TIMEOUT), false);
-
-            // shutdown the machine if stopping process fails or takes too long
-            synchronized (stoppingMachine) {
-                // task also used as mutex by DST when it submits it; ensure it only submits once!
-                if (!stoppingMachine.isSubmitted()) {
-                    // force the stoppingMachine task to run by submitting it here
-                    StringBuilder msg = new StringBuilder("Submitting machine stop early in background for ").append(entity());
-                    if (stoppingProcess == null) {
-                        msg.append(". Process stop skipped, pre-stop not finished?");
-                    } else {
-                        msg.append(" because process stop has ").append(
-                                (stoppingProcess.isDone() ? "finished abnormally" : "not finished"));
-                    }
-                    log.warn(msg.toString());
-                    Entities.submit(entity(), stoppingMachine);
-                }
-            }
-        }
-
-        try {
-            // This maintains previous behaviour of silently squashing any errors on the stoppingProcess task if the
-            // stoppingMachine exits with a nonzero value
-            boolean checkStopProcesses = (stoppingProcess != null && (stoppingMachine == null || stoppingMachine.get().value == 0));
-
-            if (checkStopProcesses) {
-                // TODO we should test for destruction above, not merely successful "stop", as things like localhost and ssh won't be destroyed
-                DynamicTasks.waitForLast();
-                if (machine.isPresent()) {
-                    // throw early errors *only if* there is a machine and we have not destroyed it
-                    stoppingProcess.get();
-                }
-            }
-        } catch (Throwable e) {
-            ServiceStateLogic.setExpectedState(entity(), Lifecycle.ON_FIRE);
-            Exceptions.propagate(e);
-        }
-        entity().setAttribute(SoftwareProcess.SERVICE_UP, false);
-        ServiceStateLogic.setExpectedState(entity(), Lifecycle.STOPPED);
-
-        DynamicTasks.queue("post-stop", new PostStopCustomTask());
-
-        if (log.isDebugEnabled()) log.debug("Stopped software process entity "+entity());
-    }
-
-    private class StopAnyProvisionedMachinesTask implements Callable<StopMachineDetails<Integer>> {
-        public StopMachineDetails<Integer> call() {
-            return stopAnyProvisionedMachines();
-        }
-    }
-
-    private class SuspendAnyProvisionedMachinesTask implements Callable<StopMachineDetails<Integer>> {
-        public StopMachineDetails<Integer> call() {
-            return suspendAnyProvisionedMachines();
-        }
-    }
-
-    private class StopProcessesAtMachineTask implements Callable<String> {
-        public String call() {
-            DynamicTasks.markInessential();
-            stopProcessesAtMachine();
-            DynamicTasks.waitForLast();
-            return "Stop processes completed with no errors.";
-        }
-    }
-
-    private class StopMachineTask implements Callable<String> {
-        public String call() {
-            DynamicTasks.markInessential();
-            stop(ConfigBag.newInstance().configure(StopSoftwareParameters.STOP_MACHINE_MODE, StopMode.IF_NOT_STOPPED));
-            DynamicTasks.waitForLast();
-            return "Stop of machine completed with no errors.";
-        }
-    }
-
-    private class PreStopCustomTask implements Callable<String> {
-        public String call() {
-            if (entity().getAttribute(SoftwareProcess.SERVICE_STATE_ACTUAL) == Lifecycle.STOPPED) {
-                log.debug("Skipping stop of entity " + entity() + " when already stopped");
-                return "Already stopped";
-            }
-            ServiceStateLogic.setExpectedState(entity(), Lifecycle.STOPPING);
-            entity().setAttribute(SoftwareProcess.SERVICE_UP, false);
-            preStopCustom();
-            return null;
-        }
-    }
-
-    private class PostStopCustomTask implements Callable<Void> {
-        public Void call() {
-            postStopCustom();
-            return null;
-        }
-    }
-
-    public static StopMode getStopMachineMode(ConfigBag parameters) {
-        final StopMode stopMachineMode = parameters.get(StopSoftwareParameters.STOP_MACHINE_MODE);
-        return stopMachineMode;
-    }
-
-    public static boolean canStop(StopMode stopMode, Entity entity) {
-        boolean isEntityStopped = entity.getAttribute(SoftwareProcess.SERVICE_STATE_ACTUAL)==Lifecycle.STOPPED;
-        return canStop(stopMode, isEntityStopped);
-    }
-
-    protected static boolean canStop(StopMode stopMode, boolean isStopped) {
-        return stopMode == StopMode.ALWAYS ||
-                stopMode == StopMode.IF_NOT_STOPPED && !isStopped;
-    }
-
-    /** 
-     * Override to check whether stop can be executed.
-     * Throw if stop should be aborted.
-     */
-    protected void preStopConfirmCustom() {
-        // nothing needed here
-    }
-
-    protected void preStopCustom() {
-        // nothing needed here
-    }
-
-    protected void postStopCustom() {
-        // nothing needed here
-    }
-
-    protected void preRestartCustom() {
-        // nothing needed here
-    }
-
-    protected void postRestartCustom() {
-        // nothing needed here
-    }
-
-    public static class StopMachineDetails<T> implements Serializable {
-        private static final long serialVersionUID = 3256747214315895431L;
-        final String message;
-        final T value;
-        protected StopMachineDetails(String message, T value) {
-            this.message = message;
-            this.value = value;
-        }
-        @Override
-        public String toString() {
-            return message;
-        }
-    }
-
-    /**
-     * Return string message of result.
-     * <p>
-     * Can run synchronously or not, caller will submit/queue as needed, and will block on any submitted tasks.
-     */
-    protected abstract String stopProcessesAtMachine();
-
-    /**
-     * Stop and release the {@link MachineLocation} the entity is provisioned at.
-     * <p>
-     * Can run synchronously or not, caller will submit/queue as needed, and will block on any submitted tasks.
-     */
-    protected StopMachineDetails<Integer> stopAnyProvisionedMachines() {
-        @SuppressWarnings("unchecked")
-        MachineProvisioningLocation<MachineLocation> provisioner = entity().getAttribute(SoftwareProcess.PROVISIONING_LOCATION);
-
-        if (Iterables.isEmpty(entity().getLocations())) {
-            log.debug("No machine decommissioning necessary for "+entity()+" - no locations");
-            return new StopMachineDetails<Integer>("No machine decommissioning necessary - no locations", 0);
-        }
-
-        // Only release this machine if we ourselves provisioned it (e.g. it might be running other services)
-        if (provisioner==null) {
-            log.debug("No machine decommissioning necessary for "+entity()+" - did not provision");
-            return new StopMachineDetails<Integer>("No machine decommissioning necessary - did not provision", 0);
-        }
-
-        Location machine = getLocation(null);
-        if (!(machine instanceof MachineLocation)) {
-            log.debug("No decommissioning necessary for "+entity()+" - not a machine location ("+machine+")");
-            return new StopMachineDetails<Integer>("No machine decommissioning necessary - not a machine ("+machine+")", 0);
-        }
-        
-        clearEntityLocationAttributes(machine);
-        provisioner.release((MachineLocation)machine);
-
-        return new StopMachineDetails<Integer>("Decommissioned "+machine, 1);
-    }
-
-    /**
-     * Suspend the {@link MachineLocation} the entity is provisioned at.
-     * <p>
-     * Expects the entity's {@link SoftwareProcess#PROVISIONING_LOCATION provisioner} to be capable of
-     * {@link SuspendsMachines suspending machines}.
-     *
-     * @throws java.lang.UnsupportedOperationException if the entity's provisioner cannot suspend machines.
-     * @see MachineManagementMixins.SuspendsMachines
-     */
-    protected StopMachineDetails<Integer> suspendAnyProvisionedMachines() {
-        @SuppressWarnings("unchecked")
-        MachineProvisioningLocation<MachineLocation> provisioner = entity().getAttribute(SoftwareProcess.PROVISIONING_LOCATION);
-
-        if (Iterables.isEmpty(entity().getLocations())) {
-            log.debug("No machine decommissioning necessary for " + entity() + " - no locations");
-            return new StopMachineDetails<>("No machine suspend necessary - no locations", 0);
-        }
-
-        // Only release this machine if we ourselves provisioned it (e.g. it might be running other services)
-        if (provisioner == null) {
-            log.debug("No machine decommissioning necessary for " + entity() + " - did not provision");
-            return new StopMachineDetails<>("No machine suspend necessary - did not provision", 0);
-        }
-
-        Location machine = getLocation(null);
-        if (!(machine instanceof MachineLocation)) {
-            log.debug("No decommissioning necessary for " + entity() + " - not a machine location (" + machine + ")");
-            return new StopMachineDetails<>("No machine suspend necessary - not a machine (" + machine + ")", 0);
-        }
-
-        if (!(provisioner instanceof SuspendsMachines)) {
-            log.debug("Location provisioner ({}) cannot suspend machines", provisioner);
-            throw new UnsupportedOperationException("Location provisioner cannot suspend machines: " + provisioner);
-        }
-
-        clearEntityLocationAttributes(machine);
-        SuspendsMachines.class.cast(provisioner).suspendMachine(MachineLocation.class.cast(machine));
-
-        return new StopMachineDetails<>("Suspended " + machine, 1);
-    }
-
-    /**
-     * Nulls the attached entity's hostname, address, subnet hostname and subnet address sensors
-     * and removes the given machine from its locations.
-     */
-    protected void clearEntityLocationAttributes(Location machine) {
-        entity().removeLocations(ImmutableList.of(machine));
-        entity().setAttribute(Attributes.HOSTNAME, null);
-        entity().setAttribute(Attributes.ADDRESS, null);
-        entity().setAttribute(Attributes.SUBNET_HOSTNAME, null);
-        entity().setAttribute(Attributes.SUBNET_ADDRESS, null);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/software/ProvidesProvisioningFlags.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/software/ProvidesProvisioningFlags.java b/software/base/src/main/java/brooklyn/entity/software/ProvidesProvisioningFlags.java
deleted file mode 100644
index 3e47919..0000000
--- a/software/base/src/main/java/brooklyn/entity/software/ProvidesProvisioningFlags.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software;
-
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-
-import com.google.common.annotations.Beta;
-
-/** Marker interface for an entity which supplies custom machine provisioning flags;
- * used e.g. in {@link MachineLifecycleEffectorTasks}.
- * @since 0.6.0 */
-@Beta
-public interface ProvidesProvisioningFlags {
-
-    public ConfigBag obtainProvisioningFlags(MachineProvisioningLocation<?> location);
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/software/SshEffectorTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/software/SshEffectorTasks.java b/software/base/src/main/java/brooklyn/entity/software/SshEffectorTasks.java
deleted file mode 100644
index bf1cf52..0000000
--- a/software/base/src/main/java/brooklyn/entity/software/SshEffectorTasks.java
+++ /dev/null
@@ -1,336 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software;
-
-import java.util.List;
-import java.util.Map;
-
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.config.StringConfigMap;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.config.ConfigUtils;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.effector.core.EffectorBody;
-import org.apache.brooklyn.effector.core.EffectorTasks;
-import org.apache.brooklyn.effector.core.EffectorTasks.EffectorTaskFactory;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
-import org.apache.brooklyn.location.basic.LocationInternal;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.internal.ssh.SshTool;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.core.task.ssh.SshFetchTaskFactory;
-import org.apache.brooklyn.util.core.task.ssh.SshFetchTaskWrapper;
-import org.apache.brooklyn.util.core.task.ssh.SshPutTaskFactory;
-import org.apache.brooklyn.util.core.task.ssh.SshPutTaskWrapper;
-import org.apache.brooklyn.util.core.task.ssh.SshTasks;
-import org.apache.brooklyn.util.core.task.ssh.internal.AbstractSshExecTaskFactory;
-import org.apache.brooklyn.util.core.task.ssh.internal.PlainSshExecTaskFactory;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskFactory;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.apache.brooklyn.util.ssh.BashCommands;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Function;
-import com.google.common.collect.Maps;
-
-/**
- * Conveniences for generating {@link Task} instances to perform SSH activities.
- * <p>
- * If the {@link SshMachineLocation machine} is not specified directly it
- * will be inferred from the {@link Entity} context of either the {@link Effector}
- * or the current {@link Task}.
- * 
- * @see SshTasks
- * @since 0.6.0
- */
-@Beta
-public class SshEffectorTasks {
-
-    private static final Logger log = LoggerFactory.getLogger(SshEffectorTasks.class);
-    
-    public static final ConfigKey<Boolean> IGNORE_ENTITY_SSH_FLAGS = ConfigKeys.newBooleanConfigKey("ignoreEntitySshFlags",
-        "Whether to ignore any ssh flags (behaviour constraints) set on the entity or location " +
-        "where this is running, using only flags explicitly specified", false);
-    
-    /** like {@link EffectorBody} but providing conveniences when in a {@link SoftwareProcess}
-     * (or other entity with a single machine location) */
-    public abstract static class SshEffectorBody<T> extends EffectorBody<T> {
-        
-        /** convenience for accessing the machine */
-        public SshMachineLocation machine() {
-            return EffectorTasks.getSshMachine(entity());
-        }
-
-        /** convenience for generating an {@link PlainSshExecTaskFactory} which can be further customised if desired, and then (it must be explicitly) queued */
-        public ProcessTaskFactory<Integer> ssh(String ...commands) {
-            return new SshEffectorTaskFactory<Integer>(commands).machine(machine());
-        }
-    }
-
-    /** variant of {@link PlainSshExecTaskFactory} which fulfills the {@link EffectorTaskFactory} signature so can be used directly as an impl for an effector,
-     * also injects the machine automatically; can also be used outwith effector contexts, and machine is still injected if it is
-     * run from inside a task at an entity with a single SshMachineLocation */
-    public static class SshEffectorTaskFactory<RET> extends AbstractSshExecTaskFactory<SshEffectorTaskFactory<RET>,RET> implements EffectorTaskFactory<RET> {
-
-        public SshEffectorTaskFactory(String ...commands) {
-            super(commands);
-        }
-        public SshEffectorTaskFactory(SshMachineLocation machine, String ...commands) {
-            super(machine, commands);
-        }
-        @Override
-        public ProcessTaskWrapper<RET> newTask(Entity entity, Effector<RET> effector, ConfigBag parameters) {
-            markDirty();
-            if (summary==null) summary(effector.getName()+" (ssh)");
-            machine(EffectorTasks.getSshMachine(entity));
-            return newTask();
-        }
-        @Override
-        public synchronized ProcessTaskWrapper<RET> newTask() {
-            Entity entity = BrooklynTaskTags.getTargetOrContextEntity(Tasks.current());
-            if (machine==null) {
-                if (log.isDebugEnabled())
-                    log.debug("Using an ssh task not in an effector without any machine; will attempt to infer the machine: "+this);
-                if (entity!=null)
-                    machine(EffectorTasks.getSshMachine(entity));
-            }
-            applySshFlags(getConfig(), entity, getMachine());
-            return super.newTask();
-        }
-        
-        @Override
-        public <T2> SshEffectorTaskFactory<T2> returning(ScriptReturnType type) {
-            return (SshEffectorTaskFactory<T2>) super.<T2>returning(type);
-        }
-
-        @Override
-        public SshEffectorTaskFactory<Boolean> returningIsExitCodeZero() {
-            return (SshEffectorTaskFactory<Boolean>) super.returningIsExitCodeZero();
-        }
-
-        public SshEffectorTaskFactory<String> requiringZeroAndReturningStdout() {
-            return (SshEffectorTaskFactory<String>) super.requiringZeroAndReturningStdout();
-        }
-        
-        public <RET2> SshEffectorTaskFactory<RET2> returning(Function<ProcessTaskWrapper<?>, RET2> resultTransformation) {
-            return (SshEffectorTaskFactory<RET2>) super.returning(resultTransformation);
-        }
-    }
-    
-    public static class SshPutEffectorTaskFactory extends SshPutTaskFactory implements EffectorTaskFactory<Void> {
-        public SshPutEffectorTaskFactory(String remoteFile) {
-            super(remoteFile);
-        }
-        public SshPutEffectorTaskFactory(SshMachineLocation machine, String remoteFile) {
-            super(machine, remoteFile);
-        }
-        @Override
-        public SshPutTaskWrapper newTask(Entity entity, Effector<Void> effector, ConfigBag parameters) {
-            machine(EffectorTasks.getSshMachine(entity));
-            applySshFlags(getConfig(), entity, getMachine());
-            return super.newTask();
-        }
-        @Override
-        public SshPutTaskWrapper newTask() {
-            Entity entity = BrooklynTaskTags.getTargetOrContextEntity(Tasks.current());
-            if (machine==null) {
-                if (log.isDebugEnabled())
-                    log.debug("Using an ssh put task not in an effector without any machine; will attempt to infer the machine: "+this);
-                if (entity!=null) {
-                    machine(EffectorTasks.getSshMachine(entity));
-                }
-
-            }
-            applySshFlags(getConfig(), entity, getMachine());
-            return super.newTask();
-        }
-    }
-
-    public static class SshFetchEffectorTaskFactory extends SshFetchTaskFactory implements EffectorTaskFactory<String> {
-        public SshFetchEffectorTaskFactory(String remoteFile) {
-            super(remoteFile);
-        }
-        public SshFetchEffectorTaskFactory(SshMachineLocation machine, String remoteFile) {
-            super(machine, remoteFile);
-        }
-        @Override
-        public SshFetchTaskWrapper newTask(Entity entity, Effector<String> effector, ConfigBag parameters) {
-            machine(EffectorTasks.getSshMachine(entity));
-            applySshFlags(getConfig(), entity, getMachine());
-            return super.newTask();
-        }
-        @Override
-        public SshFetchTaskWrapper newTask() {
-            Entity entity = BrooklynTaskTags.getTargetOrContextEntity(Tasks.current());
-            if (machine==null) {
-                if (log.isDebugEnabled())
-                    log.debug("Using an ssh fetch task not in an effector without any machine; will attempt to infer the machine: "+this);
-                if (entity!=null)
-                    machine(EffectorTasks.getSshMachine(entity));
-            }
-            applySshFlags(getConfig(), entity, getMachine());
-            return super.newTask();
-        }
-    }
-
-    public static SshEffectorTaskFactory<Integer> ssh(String ...commands) {
-        return new SshEffectorTaskFactory<Integer>(commands);
-    }
-
-    public static SshEffectorTaskFactory<Integer> ssh(List<String> commands) {
-        return ssh(commands.toArray(new String[commands.size()]));
-    }
-
-    public static SshPutTaskFactory put(String remoteFile) {
-        return new SshPutEffectorTaskFactory(remoteFile);
-    }
-
-    public static SshFetchEffectorTaskFactory fetch(String remoteFile) {
-        return new SshFetchEffectorTaskFactory(remoteFile);
-    }
-
-    /** task which returns 0 if pid is running */
-    public static SshEffectorTaskFactory<Integer> codePidRunning(Integer pid) {
-        return ssh("ps -p "+pid).summary("PID "+pid+" is-running check (exit code)").allowingNonZeroExitCode();
-    }
-    
-    /** task which fails if the given PID is not running */
-    public static SshEffectorTaskFactory<?> requirePidRunning(Integer pid) {
-        return codePidRunning(pid).summary("PID "+pid+" is-running check (required)").requiringExitCodeZero("Process with PID "+pid+" is required to be running");
-    }
-
-    /** as {@link #codePidRunning(Integer)} but returning boolean */
-    public static SshEffectorTaskFactory<Boolean> isPidRunning(Integer pid) {
-        return codePidRunning(pid).summary("PID "+pid+" is-running check (boolean)").returning(new Function<ProcessTaskWrapper<?>, Boolean>() {
-            public Boolean apply(@Nullable ProcessTaskWrapper<?> input) { return Integer.valueOf(0).equals(input.getExitCode()); }
-        });
-    }
-
-
-    /** task which returns 0 if pid in the given file is running;
-     * method accepts wildcards so long as they match a single file on the remote end
-     * <p>
-     * returns 1 if no matching file, 
-     * 1 if matching file but no matching process,
-     * and 2 if 2+ matching files */
-    public static SshEffectorTaskFactory<Integer> codePidFromFileRunning(final String pidFile) {
-        return ssh(BashCommands.chain(
-                // this fails, but isn't an error
-                BashCommands.requireTest("-f "+pidFile, "The PID file "+pidFile+" does not exist."),
-                // this fails and logs an error picked up later
-                BashCommands.requireTest("`ls "+pidFile+" | wc -w` -eq 1", "ERROR: there are multiple matching PID files"),
-                // this fails and logs an error picked up later
-                BashCommands.require("cat "+pidFile, "ERROR: the PID file "+pidFile+" cannot be read (permissions?)."),
-                // finally check the process
-                "ps -p `cat "+pidFile+"`")).summary("PID file "+pidFile+" is-running check (exit code)")
-                .allowingNonZeroExitCode()
-                .addCompletionListener(new Function<ProcessTaskWrapper<?>,Void>() {
-                    public Void apply(ProcessTaskWrapper<?> input) {
-                        if (input.getStderr().contains("ERROR:"))
-                            throw new IllegalStateException("Invalid or inaccessible PID filespec: "+pidFile);
-                        return null;
-                    }
-                });
-    }
-    
-    /** task which fails if the pid in the given file is not running (or if there is no such PID file);
-     * method accepts wildcards so long as they match a single file on the remote end (fails if 0 or 2+ matching files) */
-    public static SshEffectorTaskFactory<?> requirePidFromFileRunning(String pidFile) {
-        return codePidFromFileRunning(pidFile)
-                .summary("PID file "+pidFile+" is-running check (required)")
-                .requiringExitCodeZero("Process with PID from file "+pidFile+" is required to be running");
-    }
-
-    /** as {@link #codePidFromFileRunning(String)} but returning boolean */
-    public static SshEffectorTaskFactory<Boolean> isPidFromFileRunning(String pidFile) {
-        return codePidFromFileRunning(pidFile).summary("PID file "+pidFile+" is-running check (boolean)").
-                returning(new Function<ProcessTaskWrapper<?>, Boolean>() {
-                    public Boolean apply(@Nullable ProcessTaskWrapper<?> input) { return ((Integer)0).equals(input.getExitCode()); }
-                });
-    }
-
-    /** extracts the values for the main brooklyn.ssh.config.* config keys (i.e. those declared in ConfigKeys) 
-     * as declared on the entity, and inserts them in a map using the unprefixed state, for ssh.
-     * <p>
-     * currently this is computed for each call, which may be wasteful, but it is reliable in the face of config changes.
-     * we could cache the Map.  note that we do _not_ cache (or even own) the SshTool; 
-     * the SshTool is created or re-used by the SshMachineLocation making use of these properties */
-    @Beta
-    public static Map<String, Object> getSshFlags(Entity entity, Location optionalLocation) {
-        ConfigBag allConfig = ConfigBag.newInstance();
-        
-        StringConfigMap globalConfig = ((EntityInternal)entity).getManagementContext().getConfig();
-        allConfig.putAll(globalConfig.getAllConfig());
-        
-        if (optionalLocation!=null)
-            allConfig.putAll(((LocationInternal)optionalLocation).config().getBag());
-        
-        allConfig.putAll(((EntityInternal)entity).getAllConfig());
-        
-        Map<String, Object> result = Maps.newLinkedHashMap();
-        for (String keyS : allConfig.getAllConfig().keySet()) {
-            if (keyS.startsWith(SshTool.BROOKLYN_CONFIG_KEY_PREFIX)) {
-                ConfigKey<?> key = ConfigKeys.newConfigKey(Object.class, keyS);
-                
-                Object val = allConfig.getStringKey(keyS);
-                
-                /*
-                 * NOV 2013 changing this to rely on config above being inserted in the right order,
-                 * so entity config will be preferred over location, and location over global.
-                 * If that is consistent then remove the lines below.
-                 * (We can also accept null entity and so combine with SshTasks.getSshFlags.)
-                 */
-                
-//                // have to use raw config to test whether the config is set
-//                Object val = ((EntityInternal)entity).getConfigMap().getRawConfig(key);
-//                if (val!=null) {
-//                    val = entity.getConfig(key);
-//                } else {
-//                    val = globalConfig.getRawConfig(key);
-//                    if (val!=null) val = globalConfig.getConfig(key);
-//                }
-//                if (val!=null) {
-                    result.put(ConfigUtils.unprefixedKey(SshTool.BROOKLYN_CONFIG_KEY_PREFIX, key).getName(), val);
-//                }
-            }
-        }
-        return result;
-    }
-
-    private static void applySshFlags(ConfigBag config, Entity entity, Location machine) {
-        if (entity!=null) {
-            if (!config.get(IGNORE_ENTITY_SSH_FLAGS)) {
-                config.putIfAbsent(getSshFlags(entity, machine));
-            }
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/software/StaticSensor.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/software/StaticSensor.java b/software/base/src/main/java/brooklyn/entity/software/StaticSensor.java
deleted file mode 100644
index 05a92ed..0000000
--- a/software/base/src/main/java/brooklyn/entity/software/StaticSensor.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software;
-
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.effector.core.AddSensor;
-import org.apache.brooklyn.sensor.enricher.Propagator;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.core.task.ValueResolver;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Supplier;
-
-/** 
- * Provides an initializer/feed which simply sets a given value.
- * <p>
- * {@link Task}/{@link Supplier} values are resolved when written,
- * unlike config values which are resolved on each read.
- * <p>
- * This supports a {@link StaticSensor#SENSOR_PERIOD} 
- * which can be useful if the supplied value is such a function.
- * However when the source is another sensor,
- * consider using {@link Propagator} which listens for changes instead. */
-public class StaticSensor<T> extends AddSensor<T> {
-
-    private static final Logger log = LoggerFactory.getLogger(StaticSensor.class);
-    
-    public static final ConfigKey<Object> STATIC_VALUE = ConfigKeys.newConfigKey(Object.class, "static.value");
-
-    private final Object value;
-
-    public StaticSensor(ConfigBag params) {
-        super(params);
-        value = params.get(STATIC_VALUE);
-    }
-
-    @SuppressWarnings("unchecked")
-    @Override
-    public void apply(EntityLocal entity) {
-        super.apply(entity);
-        
-        Maybe<T> v = Tasks.resolving(value).as((Class<T>)sensor.getType()).timeout(ValueResolver.PRETTY_QUICK_WAIT).getMaybe();
-        if (v.isPresent()) {
-            log.debug(this+" setting sensor "+sensor+" to "+v.get());
-            entity.setAttribute(sensor, v.get());
-        } else {
-            log.debug(this+" not setting sensor "+sensor+"; cannot resolve "+value);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/software/http/HttpRequestSensor.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/software/http/HttpRequestSensor.java b/software/base/src/main/java/brooklyn/entity/software/http/HttpRequestSensor.java
deleted file mode 100644
index b2c68a6..0000000
--- a/software/base/src/main/java/brooklyn/entity/software/http/HttpRequestSensor.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software.http;
-
-import java.net.URI;
-
-import net.minidev.json.JSONObject;
-
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.effector.core.AddSensor;
-import org.apache.brooklyn.sensor.feed.http.HttpFeed;
-import org.apache.brooklyn.sensor.feed.http.HttpPollConfig;
-import org.apache.brooklyn.sensor.feed.http.HttpValueFunctions;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.software.java.JmxAttributeSensor;
-import brooklyn.entity.software.ssh.SshCommandSensor;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Functions;
-import com.google.common.base.Supplier;
-
-/**
- * Configurable {@link org.apache.brooklyn.api.entity.EntityInitializer} which adds an HTTP sensor feed to retrieve the
- * {@link JSONObject} from a JSON response in order to populate the sensor with the data at the {@code jsonPath}.
- *
- * @see SshCommandSensor
- * @see JmxAttributeSensor
- */
-@Beta
-public final class HttpRequestSensor<T> extends AddSensor<T> {
-
-    private static final Logger LOG = LoggerFactory.getLogger(HttpRequestSensor.class);
-
-    public static final ConfigKey<String> SENSOR_URI = ConfigKeys.newStringConfigKey("uri", "HTTP URI to poll for JSON");
-    public static final ConfigKey<String> JSON_PATH = ConfigKeys.newStringConfigKey("jsonPath", "JSON path to select in HTTP response; default $", "$");
-    public static final ConfigKey<String> USERNAME = ConfigKeys.newStringConfigKey("username", "Username for HTTP request, if required");
-    public static final ConfigKey<String> PASSWORD = ConfigKeys.newStringConfigKey("password", "Password for HTTP request, if required");
-
-    protected final Supplier<URI> uri;
-    protected final String jsonPath;
-    protected final String username;
-    protected final String password;
-
-    public HttpRequestSensor(final ConfigBag params) {
-        super(params);
-
-        uri = new Supplier<URI>() {
-            @Override
-            public URI get() {
-                return URI.create(params.get(SENSOR_URI));
-            }
-        };
-        jsonPath = params.get(JSON_PATH);
-        username = params.get(USERNAME);
-        password = params.get(PASSWORD);
-    }
-
-    @Override
-    public void apply(final EntityLocal entity) {
-        super.apply(entity);
-
-        if (LOG.isDebugEnabled()) {
-            LOG.debug("Adding HTTP JSON sensor {} to {}", name, entity);
-        }
-
-        HttpPollConfig<T> pollConfig = new HttpPollConfig<T>(sensor)
-                .checkSuccess(HttpValueFunctions.responseCodeEquals(200))
-                .onFailureOrException(Functions.constant((T) null))
-                .onSuccess(HttpValueFunctions.<T>jsonContentsFromPath(jsonPath))
-                .period(period);
-
-        HttpFeed.builder().entity(entity)
-                .baseUri(uri)
-                .credentialsIfNotNull(username, password)
-                .poll(pollConfig)
-                .build();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/software/java/JmxAttributeSensor.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/software/java/JmxAttributeSensor.java b/software/base/src/main/java/brooklyn/entity/software/java/JmxAttributeSensor.java
deleted file mode 100644
index d66b67b..0000000
--- a/software/base/src/main/java/brooklyn/entity/software/java/JmxAttributeSensor.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software.java;
-
-import java.util.concurrent.Callable;
-
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
-
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.effector.core.AddSensor;
-import org.apache.brooklyn.sensor.core.DependentConfiguration;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.time.Duration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.java.UsesJmx;
-import brooklyn.entity.software.http.HttpRequestSensor;
-import brooklyn.entity.software.ssh.SshCommandSensor;
-import brooklyn.event.feed.jmx.JmxAttributePollConfig;
-import brooklyn.event.feed.jmx.JmxFeed;
-import brooklyn.event.feed.jmx.JmxHelper;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Functions;
-import com.google.common.base.Preconditions;
-
-/**
- * Configurable {@link org.apache.brooklyn.api.entity.EntityInitializer} which adds a JMX sensor feed to retrieve an
- * <code>attribute</code> from a JMX <code>objectName</code>.
- *
- * @see SshCommandSensor
- * @see HttpRequestSensor
- */
-@Beta
-public final class JmxAttributeSensor<T> extends AddSensor<T> {
-
-    private static final Logger LOG = LoggerFactory.getLogger(JmxAttributeSensor.class);
-
-    public static final ConfigKey<String> OBJECT_NAME = ConfigKeys.newStringConfigKey("objectName", "JMX object name for sensor lookup");
-    public static final ConfigKey<String> ATTRIBUTE = ConfigKeys.newStringConfigKey("attribute", "JMX attribute to poll in object");
-    public static final ConfigKey<Object> DEFAULT_VALUE = ConfigKeys.newConfigKey(Object.class, "defaultValue", "Default value for sensor; normally null");
-
-    protected final String objectName;
-    protected final String attribute;
-    protected final Object defaultValue;
-
-    public JmxAttributeSensor(final ConfigBag params) {
-        super(params);
- 
-        objectName = Preconditions.checkNotNull(params.get(OBJECT_NAME), "objectName");
-        attribute = Preconditions.checkNotNull(params.get(ATTRIBUTE), "attribute");
-        defaultValue = params.get(DEFAULT_VALUE);
-
-        try {
-            ObjectName.getInstance(objectName);
-        } catch (MalformedObjectNameException mone) {
-            throw new IllegalArgumentException("Malformed JMX object name: " + objectName, mone);
-        }
-    }
-
-    @Override
-    public void apply(final EntityLocal entity) {
-        super.apply(entity);
-
-        if (entity instanceof UsesJmx) {
-            if (LOG.isDebugEnabled()) {
-                LOG.debug("Submitting task to add JMX sensor {} to {}", name, entity);
-            }
-
-            Task<Integer> jmxPortTask = DependentConfiguration.attributeWhenReady(entity, UsesJmx.JMX_PORT);
-            Task<JmxFeed> jmxFeedTask = Tasks.<JmxFeed>builder()
-                    .description("Add JMX feed")
-                    .body(new Callable<JmxFeed>() {
-                        @Override
-                        public JmxFeed call() throws Exception {
-                            JmxHelper helper = new JmxHelper(entity);
-                            Duration period = entity.getConfig(SENSOR_PERIOD);
-
-                            JmxFeed feed = JmxFeed.builder()
-                                    .entity(entity)
-                                    .period(period)
-                                    .helper(helper)
-                                    .pollAttribute(new JmxAttributePollConfig<T>(sensor)
-                                            .objectName(objectName)
-                                            .attributeName(attribute)
-                                            .onFailureOrException(Functions.<T>constant((T) defaultValue)))
-                                    .build();
-                           return feed;
-                        }
-                    })
-                    .build();
-            DynamicTasks.submit(Tasks.sequential("Add JMX Sensor " + sensor.getName(), jmxPortTask, jmxFeedTask), entity);
-        } else {
-            throw new IllegalStateException(String.format("Entity %s does not support JMX", entity));
-        }
-
-        // TODO add entity shutdown hook to stop JmxFeed
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/software/ssh/SshCommandEffector.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/software/ssh/SshCommandEffector.java b/software/base/src/main/java/brooklyn/entity/software/ssh/SshCommandEffector.java
deleted file mode 100644
index 4c3dcbe..0000000
--- a/software/base/src/main/java/brooklyn/entity/software/ssh/SshCommandEffector.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software.ssh;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.effector.ParameterType;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.effector.core.AddEffector;
-import org.apache.brooklyn.effector.core.EffectorBody;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.effector.core.Effectors.EffectorBuilder;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.text.Strings;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.software.SshEffectorTasks;
-import brooklyn.entity.software.SshEffectorTasks.SshEffectorTaskFactory;
-
-import com.google.common.base.Preconditions;
-
-public final class SshCommandEffector extends AddEffector {
-    
-    public static final ConfigKey<String> EFFECTOR_COMMAND = ConfigKeys.newStringConfigKey("command");
-    public static final ConfigKey<String> EFFECTOR_EXECUTION_DIR = SshCommandSensor.SENSOR_EXECUTION_DIR;
-    
-    public SshCommandEffector(ConfigBag params) {
-        super(newEffectorBuilder(params).build());
-    }
-    
-    public SshCommandEffector(Map<String,String> params) {
-        this(ConfigBag.newInstance(params));
-    }
-
-    public static EffectorBuilder<String> newEffectorBuilder(ConfigBag params) {
-        EffectorBuilder<String> eff = AddEffector.newEffectorBuilder(String.class, params);
-        eff.impl(new Body(eff.buildAbstract(), params));
-        return eff;
-    }
-
-
-    protected static class Body extends EffectorBody<String> {
-        private final Effector<?> effector;
-        private final String command;
-        private final String executionDir;
-
-        public Body(Effector<?> eff, ConfigBag params) {
-            this.effector = eff;
-            this.command = Preconditions.checkNotNull(params.get(EFFECTOR_COMMAND), "command must be supplied when defining this effector");
-            this.executionDir = params.get(EFFECTOR_EXECUTION_DIR);
-            // TODO could take a custom "env" aka effectorShellEnv
-        }
-
-        @Override
-        public String call(ConfigBag params) {
-            String command = this.command;
-            
-            command = SshCommandSensor.makeCommandExecutingInDirectory(command, executionDir, entity());
-            
-            MutableMap<String, String> env = MutableMap.of();
-            // first set all declared parameters, including default values
-            for (ParameterType<?> param: effector.getParameters()) {
-                env.addIfNotNull(param.getName(), Strings.toString( params.get(Effectors.asConfigKey(param)) ));
-            }
-            
-            // then set things from the entities defined shell environment, if applicable
-            env.putAll(Strings.toStringMap(entity().getConfig(SoftwareProcess.SHELL_ENVIRONMENT), ""));
-            
-            // if we wanted to resolve the surrounding environment in real time -- see above
-//            Map<String,Object> paramsResolved = (Map<String, Object>) Tasks.resolveDeepValue(effectorShellEnv, Map.class, entity().getExecutionContext());
-            
-            // finally set the parameters we've been passed; this will repeat declared parameters but to no harm,
-            // it may pick up additional values (could be a flag defining whether this is permitted or not)
-            env.putAll(Strings.toStringMap(params.getAllConfig()));
-            
-            SshEffectorTaskFactory<String> t = SshEffectorTasks.ssh(command)
-                .requiringZeroAndReturningStdout()
-                .summary("effector "+effector.getName())
-                .environmentVariables(env);
-            return queue(t).get();
-        }
-        
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/software/ssh/SshCommandSensor.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/software/ssh/SshCommandSensor.java b/software/base/src/main/java/brooklyn/entity/software/ssh/SshCommandSensor.java
deleted file mode 100644
index fa51664..0000000
--- a/software/base/src/main/java/brooklyn/entity/software/ssh/SshCommandSensor.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software.ssh;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.EntityInitializer;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.effector.core.AddSensor;
-import org.apache.brooklyn.sensor.feed.ssh.SshFeed;
-import org.apache.brooklyn.sensor.feed.ssh.SshPollConfig;
-import org.apache.brooklyn.sensor.feed.ssh.SshValueFunctions;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.flags.TypeCoercions;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.text.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.software.http.HttpRequestSensor;
-import brooklyn.entity.software.java.JmxAttributeSensor;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Function;
-import com.google.common.base.Functions;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Supplier;
-
-/** 
- * Configurable {@link EntityInitializer} which adds an SSH sensor feed running the <code>command</code> supplied
- * in order to populate the sensor with the indicated <code>name</code>. Note that the <code>targetType</code> is ignored,
- * and always set to {@link String}.
- *
- * @see HttpRequestSensor
- * @see JmxAttributeSensor
- */
-@Beta
-public final class SshCommandSensor<T> extends AddSensor<T> {
-
-    private static final Logger LOG = LoggerFactory.getLogger(SshCommandSensor.class);
-
-    public static final ConfigKey<String> SENSOR_COMMAND = ConfigKeys.newStringConfigKey("command", "SSH command to execute for sensor");
-    public static final ConfigKey<String> SENSOR_EXECUTION_DIR = ConfigKeys.newStringConfigKey("executionDir", "Directory where the command should run; "
-        + "if not supplied, executes in the entity's run dir (or home dir if no run dir is defined); "
-        + "use '~' to always execute in the home dir, or 'custom-feed/' to execute in a custom-feed dir relative to the run dir");
-
-    protected final String command;
-    protected final String executionDir;
-
-    public SshCommandSensor(final ConfigBag params) {
-        super(params);
-
-        // TODO create a supplier for the command string to support attribute embedding
-        command = Preconditions.checkNotNull(params.get(SENSOR_COMMAND), "command");
-        
-        executionDir = params.get(SENSOR_EXECUTION_DIR);
-    }
-
-    @Override
-    public void apply(final EntityLocal entity) {
-        super.apply(entity);
-
-        if (LOG.isDebugEnabled()) {
-            LOG.debug("Adding SSH sensor {} to {}", name, entity);
-        }
-
-        Supplier<Map<String,String>> envSupplier = new Supplier<Map<String,String>>() {
-            @Override
-            public Map<String, String> get() {
-                return MutableMap.copyOf(Strings.toStringMap(entity.getConfig(SoftwareProcess.SHELL_ENVIRONMENT), ""));
-            }
-        };
-
-        Supplier<String> commandSupplier = new Supplier<String>() {
-            @Override
-            public String get() {
-                return makeCommandExecutingInDirectory(command, executionDir, entity);
-            }
-        };
-
-        SshPollConfig<T> pollConfig = new SshPollConfig<T>(sensor)
-                .period(period)
-                .env(envSupplier)
-                .command(commandSupplier)
-                .checkSuccess(SshValueFunctions.exitStatusEquals(0))
-                .onFailureOrException(Functions.constant((T) null))
-                .onSuccess(Functions.compose(new Function<String, T>() {
-                        @Override
-                        public T apply(String input) {
-                            return TypeCoercions.coerce(input, getType(type));
-                        }}, SshValueFunctions.stdout()));
-
-        SshFeed.builder()
-                .entity(entity)
-                .onlyIfServiceUp()
-                .poll(pollConfig)
-                .build();
-    }
-
-    static String makeCommandExecutingInDirectory(String command, String executionDir, EntityLocal entity) {
-        String finalCommand = command;
-        String execDir = executionDir;
-        if (Strings.isBlank(execDir)) {
-            // default to run dir
-            execDir = entity.getAttribute(SoftwareProcess.RUN_DIR);
-            // if no run dir, default to home
-            if (Strings.isBlank(execDir)) {
-                execDir = "~";
-            }
-        } else if (!Os.isAbsolutish(execDir)) {
-            // relative paths taken wrt run dir
-            String runDir = entity.getAttribute(SoftwareProcess.RUN_DIR);
-            if (!Strings.isBlank(runDir)) {
-                execDir = Os.mergePaths(runDir, execDir);
-            }
-        }
-        if (!"~".equals(execDir)) {
-            finalCommand = "mkdir -p '"+execDir+"' && cd '"+execDir+"' && "+finalCommand;
-        }
-        return finalCommand;
-    }
-
-}



[11/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/AbstractSoftlayerLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/AbstractSoftlayerLiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/AbstractSoftlayerLiveTest.java
new file mode 100644
index 0000000..9080e51
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/AbstractSoftlayerLiveTest.java
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.text.StringShortener;
+import org.apache.brooklyn.util.text.Strings;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.base.CaseFormat;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+/**
+ * Runs a test with many different distros and versions.
+ */
+public abstract class AbstractSoftlayerLiveTest {
+    
+    public static final String PROVIDER = "softlayer";
+    public static final int MAX_TAG_LENGTH = 20;
+    public static final int MAX_VM_NAME_LENGTH = 30;
+
+    protected BrooklynProperties brooklynProperties;
+    protected ManagementContext ctx;
+    
+    protected TestApplication app;
+    protected Location jcloudsLocation;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        List<String> propsToRemove = ImmutableList.of("imageId", "imageDescriptionRegex", "imageNameRegex", "inboundPorts", "hardwareId", "minRam");
+
+        // Don't let any defaults from brooklyn.properties (except credentials) interfere with test
+        brooklynProperties = BrooklynProperties.Factory.newDefault();
+        for (String propToRemove : propsToRemove) {
+            for (String propVariant : ImmutableList.of(propToRemove, CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propToRemove))) {
+                brooklynProperties.remove("brooklyn.locations.jclouds."+PROVIDER+"."+propVariant);
+                brooklynProperties.remove("brooklyn.locations."+propVariant);
+                brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+"."+propVariant);
+                brooklynProperties.remove("brooklyn.jclouds."+propVariant);
+            }
+        }
+
+        // Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can cause "stdin: is not a tty")
+        brooklynProperties.remove("brooklyn.ssh.config.scriptHeader");
+        
+        ctx = new LocalManagementContext(brooklynProperties);
+        app = ApplicationBuilder.newManagedApp(TestApplication.class, ctx);
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (app != null) Entities.destroyAll(app.getManagementContext());
+    }
+
+    @Test(groups = {"Live"})
+    public void test_Default() throws Exception {
+        runTest(ImmutableMap.<String,Object>of());
+    }
+
+    @Test(groups = {"Live"})
+    public void test_Ubuntu_12_0_4() throws Exception {
+        // Image: {id=UBUNTU_12_64, providerId=UBUNTU_12_64, os={family=ubuntu, version=12.04, description=Ubuntu / Ubuntu / 12.04.0-64 Minimal, is64Bit=true}, description=UBUNTU_12_64, status=AVAILABLE, loginUser=root}
+        runTest(ImmutableMap.<String,Object>of("imageId", "UBUNTU_12_64"));
+    }
+
+    @Test(groups = {"Live"})
+    public void test_Centos_6_0() throws Exception {
+      // Image: {id=CENTOS_6_64, providerId=CENTOS_6_64, os={family=centos, version=6.5, description=CentOS / CentOS / 6.5-64 LAMP for Bare Metal, is64Bit=true}, description=CENTOS_6_64, status=AVAILABLE, loginUser=root}
+        runTest(ImmutableMap.<String,Object>of("imageId", "CENTOS_6_64"));
+    }
+    
+    protected void runTest(Map<String,?> flags) throws Exception {
+        StringShortener shortener = Strings.shortener().separator("-");
+        shortener.canTruncate(getClass().getSimpleName(), MAX_TAG_LENGTH);
+        Map<String,?> allFlags = MutableMap.<String,Object>builder()
+                .put("tags", ImmutableList.of(shortener.getStringOfMaxLength(MAX_TAG_LENGTH)))
+                .put("vmNameMaxLength", MAX_VM_NAME_LENGTH)
+                .putAll(flags)
+                .build();
+        jcloudsLocation = ctx.getLocationRegistry().resolve(PROVIDER, allFlags);
+
+        doTest(jcloudsLocation);
+    }
+    
+    protected abstract void doTest(Location loc) throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java
new file mode 100644
index 0000000..1879e4b
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import java.io.File;
+import java.util.List;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynCluster;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode.ExistingFileBehaviour;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.javalang.JavaClassNames;
+import org.apache.brooklyn.util.net.Networking;
+import org.apache.brooklyn.util.os.Os;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+
+import com.google.common.base.Predicates;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+
+public class BrooklynClusterIntegrationTest extends BrooklynAppUnitTestSupport {
+
+    private static final Logger LOG = LoggerFactory.getLogger(BrooklynNodeIntegrationTest.class);
+
+    private File pseudoBrooklynPropertiesFile;
+    private File pseudoBrooklynCatalogFile;
+    private File persistenceDir;
+    private LocalhostMachineProvisioningLocation loc;
+    private List<LocalhostMachineProvisioningLocation> locs;
+
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        pseudoBrooklynPropertiesFile = Os.newTempFile("brooklynnode-test", ".properties");
+        pseudoBrooklynPropertiesFile.delete();
+
+        pseudoBrooklynCatalogFile = Os.newTempFile("brooklynnode-test", ".catalog");
+        pseudoBrooklynCatalogFile.delete();
+
+        loc = app.newLocalhostProvisioningLocation();
+        locs = ImmutableList.of(loc);
+    }
+
+    @AfterMethod(alwaysRun=true)
+    @Override
+    public void tearDown() throws Exception {
+        try {
+            super.tearDown();
+        } finally {
+            if (pseudoBrooklynPropertiesFile != null) pseudoBrooklynPropertiesFile.delete();
+            if (pseudoBrooklynCatalogFile != null) pseudoBrooklynCatalogFile.delete();
+            if (persistenceDir != null) Os.deleteRecursively(persistenceDir);
+        }
+    }
+
+    @Test(groups="Integration")
+    public void testCanStartAndStop() throws Exception {
+        BrooklynCluster cluster = app.createAndManageChild(EntitySpec.create(BrooklynCluster.class)
+                .configure(BrooklynCluster.INITIAL_SIZE, 1)
+                .configure(BrooklynNode.WEB_CONSOLE_BIND_ADDRESS, Networking.ANY_NIC)
+                .configure(BrooklynNode.ON_EXISTING_PROPERTIES_FILE, ExistingFileBehaviour.DO_NOT_USE));
+        app.start(locs);
+        Entity brooklynNode = Iterables.find(cluster.getMembers(), Predicates.instanceOf(BrooklynNode.class));
+        LOG.info("started "+app+" containing "+cluster+" for "+JavaClassNames.niceClassAndMethod());
+
+        EntityTestUtils.assertAttributeEqualsEventually(cluster, BrooklynNode.SERVICE_UP, true);
+        EntityTestUtils.assertAttributeEqualsEventually(brooklynNode, BrooklynNode.SERVICE_UP, true);
+
+        cluster.stop();
+        EntityTestUtils.assertAttributeEquals(cluster, BrooklynNode.SERVICE_UP, false);
+    }    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java
new file mode 100644
index 0000000..948a42a
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java
@@ -0,0 +1,632 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
+import java.io.File;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.net.URI;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.objs.proxy.EntityProxyImpl;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynEntityMirror;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNodeImpl;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNodeSshDriver;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode.DeployBlueprintEffector;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode.ExistingFileBehaviour;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode.StopNodeAndKillAppsEffector;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.StopSoftwareParameters.StopMode;
+import org.apache.brooklyn.entity.stock.BasicApplication;
+import org.apache.brooklyn.entity.stock.BasicApplicationImpl;
+import org.apache.brooklyn.sensor.feed.http.JsonFunctions;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.test.HttpTestUtils;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.http.HttpTool;
+import org.apache.brooklyn.util.core.http.HttpToolResponse;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.guava.Functionals;
+import org.apache.brooklyn.util.javalang.JavaClassNames;
+import org.apache.brooklyn.util.net.Networking;
+import org.apache.brooklyn.util.net.Urls;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.HttpClient;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.basic.Locations;
+import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+import com.google.common.base.Charsets;
+import com.google.common.base.Function;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+import com.google.common.io.Files;
+
+/**
+ * This test needs to able to access the binary artifact in order to run.
+ * The default behaviour is to take this from maven, which works pretty well if you're downloading from hosted maven.
+ * <p>
+ * This class has been updated so that it does not effect or depend on the contents of ~/.brooklyn/brooklyn.properties .
+ * <p>
+ * If you wish to supply your own version (useful if testing changes locally!), you'll need to force download of this file.
+ * The simplest way is to install:
+ * <ul>
+ * <li>file://$HOME/.brooklyn/repository/BrooklynNode/${VERSION}/BrooklynNode-${VERSION}.tar.gz - for snapshot versions (filename is default format due to lack of filename in sonatype inferencing; 
+ *     note on case-sensitive systems it might have to be all in lower case!)
+ * <li>file://$HOME/.brooklyn/repository/BrooklynNode/${VERSION}/brooklyn-${VERSION}-dist.tar.gz - for release versions, filename should match that in maven central
+ * </ul>
+ * In both cases, remember that you may also need to wipe the local apps cache ($BROOKLYN_DATA_DIR/installs/BrooklynNode).
+ * The following commands may be useful:
+ * <p>
+ * <code>
+ * cp ~/.m2/repository/org/apache/brooklyn/brooklyn-dist/0.7.0-SNAPSHOT/brooklyn-dist-0.7.0-SNAPSHOT-dist.tar.gz ~/.brooklyn/repository/BrooklynNode/0.7.0-SNAPSHOT/BrooklynNode-0.7.0-SNAPSHOT.tar.gz
+ * rm -rf /tmp/brooklyn-`whoami`/installs/BrooklynNode*
+ * </code>
+ */
+public class BrooklynNodeIntegrationTest extends BrooklynAppUnitTestSupport {
+
+    private static final Logger log = LoggerFactory.getLogger(BrooklynNodeIntegrationTest.class);
+    
+    private File pseudoBrooklynPropertiesFile;
+    private File pseudoBrooklynCatalogFile;
+    private File persistenceDir;
+    private LocalhostMachineProvisioningLocation loc;
+    private List<LocalhostMachineProvisioningLocation> locs;
+
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        pseudoBrooklynPropertiesFile = Os.newTempFile("brooklynnode-test", ".properties");
+        pseudoBrooklynPropertiesFile.delete();
+
+        pseudoBrooklynCatalogFile = Os.newTempFile("brooklynnode-test", ".catalog");
+        pseudoBrooklynCatalogFile.delete();
+
+        loc = app.newLocalhostProvisioningLocation();
+        locs = ImmutableList.of(loc);
+    }
+
+    @AfterMethod(alwaysRun=true)
+    @Override
+    public void tearDown() throws Exception {
+        try {
+            super.tearDown();
+        } finally {
+            if (pseudoBrooklynPropertiesFile != null) pseudoBrooklynPropertiesFile.delete();
+            if (pseudoBrooklynCatalogFile != null) pseudoBrooklynCatalogFile.delete();
+            if (persistenceDir != null) Os.deleteRecursively(persistenceDir);
+        }
+    }
+
+    protected EntitySpec<BrooklynNode> newBrooklynNodeSpecForTest() {
+        // poor man's way to output which test is running
+        log.info("Creating entity spec for "+JavaClassNames.callerNiceClassAndMethod(1));
+        
+        return EntitySpec.create(BrooklynNode.class)
+                .configure(BrooklynNode.WEB_CONSOLE_BIND_ADDRESS, Networking.ANY_NIC)
+                .configure(BrooklynNode.ON_EXISTING_PROPERTIES_FILE, ExistingFileBehaviour.DO_NOT_USE);
+        
+        /* yaml equivalent, for testing:
+
+location: localhost
+services:
+- type: brooklyn.entity.brooklynnode.BrooklynNode
+  bindAddress: 127.0.0.1
+  onExistingProperties: do_not_use
+
+# some other options
+  enabledHttpProtocols: [ https ]
+  managementPassword: s3cr3t
+  brooklynLocalPropertiesContents: |
+    brooklyn.webconsole.security.https.required=true
+    brooklyn.webconsole.security.users=admin
+    brooklyn.webconsole.security.user.admin.password=s3cr3t
+    brooklyn.location.localhost.enabled=false
+
+         */
+    }
+
+    @Test(groups="Integration")
+    public void testCanStartAndStop() throws Exception {
+        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest());
+        app.start(locs);
+        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
+
+        EntityTestUtils.assertAttributeEqualsEventually(brooklynNode, BrooklynNode.SERVICE_UP, true);
+
+        brooklynNode.stop();
+        EntityTestUtils.assertAttributeEquals(brooklynNode, BrooklynNode.SERVICE_UP, false);
+    }
+
+    @Test(groups="Integration")
+    public void testSetsGlobalBrooklynPropertiesFromContents() throws Exception {
+        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
+                .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_REMOTE_PATH, pseudoBrooklynPropertiesFile.getAbsolutePath())
+                .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_CONTENTS, "abc=def"));
+        app.start(locs);
+        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
+
+        assertEquals(Files.readLines(pseudoBrooklynPropertiesFile, Charsets.UTF_8), ImmutableList.of("abc=def"));
+    }
+
+    @Test(groups="Integration")
+    public void testSetsLocalBrooklynPropertiesFromContents() throws Exception {
+        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
+                .configure(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_REMOTE_PATH, pseudoBrooklynPropertiesFile.getAbsolutePath())
+                .configure(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_CONTENTS, "abc=def"));
+        app.start(locs);
+        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
+
+        assertEquals(Files.readLines(pseudoBrooklynPropertiesFile, Charsets.UTF_8), ImmutableList.of("abc=def"));
+    }
+
+    @Test(groups="Integration")
+    public void testSetsBrooklynPropertiesFromUri() throws Exception {
+        File brooklynPropertiesSourceFile = File.createTempFile("brooklynnode-test", ".properties");
+        Files.write("abc=def", brooklynPropertiesSourceFile, Charsets.UTF_8);
+
+        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
+                .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_REMOTE_PATH, pseudoBrooklynPropertiesFile.getAbsolutePath())
+                .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_URI, brooklynPropertiesSourceFile.toURI().toString()));
+        app.start(locs);
+        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
+
+        assertEquals(Files.readLines(pseudoBrooklynPropertiesFile, Charsets.UTF_8), ImmutableList.of("abc=def"));
+    }
+
+    @Test(groups="Integration")
+    public void testSetsBrooklynCatalogFromContents() throws Exception {
+        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
+                .configure(BrooklynNode.BROOKLYN_CATALOG_REMOTE_PATH, pseudoBrooklynCatalogFile.getAbsolutePath())
+                .configure(BrooklynNode.BROOKLYN_CATALOG_CONTENTS, "<catalog/>"));
+        app.start(locs);
+        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
+
+        assertEquals(Files.readLines(pseudoBrooklynCatalogFile, Charsets.UTF_8), ImmutableList.of("<catalog/>"));
+    }
+
+    @Test(groups="Integration")
+    public void testSetsBrooklynCatalogFromUri() throws Exception {
+        File brooklynCatalogSourceFile = File.createTempFile("brooklynnode-test", ".catalog");
+        Files.write("abc=def", brooklynCatalogSourceFile, Charsets.UTF_8);
+
+        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
+                .configure(BrooklynNode.BROOKLYN_CATALOG_REMOTE_PATH, pseudoBrooklynCatalogFile.getAbsolutePath())
+                .configure(BrooklynNode.BROOKLYN_CATALOG_URI, brooklynCatalogSourceFile.toURI().toString()));
+        app.start(locs);
+        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
+
+        assertEquals(Files.readLines(pseudoBrooklynCatalogFile, Charsets.UTF_8), ImmutableList.of("abc=def"));
+    }
+
+    @Test(groups="Integration")
+    public void testCopiesResources() throws Exception {
+        File sourceFile = File.createTempFile("brooklynnode-test", ".properties");
+        Files.write("abc=def", sourceFile, Charsets.UTF_8);
+        File tempDir = Files.createTempDir();
+        File expectedFile = new File(tempDir, "myfile.txt");
+
+        try {
+            BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
+                    .configure(BrooklynNode.RUN_DIR, tempDir.getAbsolutePath())
+                    .configure(BrooklynNode.COPY_TO_RUNDIR, ImmutableMap.of(sourceFile.getAbsolutePath(), "${RUN}/myfile.txt")));
+            app.start(locs);
+            log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
+
+            assertEquals(Files.readLines(expectedFile, Charsets.UTF_8), ImmutableList.of("abc=def"));
+        } finally {
+            expectedFile.delete();
+            tempDir.delete();
+            sourceFile.delete();
+        }
+    }
+
+    @Test(groups="Integration")
+    public void testCopiesClasspathEntriesInConfigKey() throws Exception {
+        String content = "abc=def";
+        File classpathEntry1 = File.createTempFile("first", ".properties");
+        File classpathEntry2 = File.createTempFile("second", ".properties");
+        Files.write(content, classpathEntry1, Charsets.UTF_8);
+        Files.write(content, classpathEntry2, Charsets.UTF_8);
+        File tempDir = Files.createTempDir();
+        File expectedFile1 = new File(new File(tempDir, "lib"), classpathEntry1.getName());
+        File expectedFile2 = new File(new File(tempDir, "lib"), classpathEntry2.getName());
+
+        try {
+            BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
+                    .configure(BrooklynNode.RUN_DIR, tempDir.getAbsolutePath())
+                    .configure(BrooklynNode.CLASSPATH, ImmutableList.of(classpathEntry1.getAbsolutePath(), classpathEntry2.getAbsolutePath()))
+                    );
+            app.start(locs);
+            log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
+
+            assertEquals(Files.readLines(expectedFile1, Charsets.UTF_8), ImmutableList.of(content));
+            assertEquals(Files.readLines(expectedFile2, Charsets.UTF_8), ImmutableList.of(content));
+        } finally {
+            expectedFile1.delete();
+            expectedFile2.delete();
+            tempDir.delete();
+            classpathEntry1.delete();
+            classpathEntry2.delete();
+        }
+    }
+
+    @Test(groups="Integration")
+    public void testCopiesClasspathEntriesInBrooklynProperties() throws Exception {
+        String content = "abc=def";
+        File classpathEntry1 = File.createTempFile("first", ".properties");
+        File classpathEntry2 = File.createTempFile("second", ".properties");
+        Files.write(content, classpathEntry1, Charsets.UTF_8);
+        Files.write(content, classpathEntry2, Charsets.UTF_8);
+        File tempDir = Files.createTempDir();
+        File expectedFile1 = new File(new File(tempDir, "lib"), classpathEntry1.getName());
+        File expectedFile2 = new File(new File(tempDir, "lib"), classpathEntry2.getName());
+
+        try {
+            String propName = BrooklynNode.CLASSPATH.getName();
+            String propValue = classpathEntry1.toURI().toString() + "," + classpathEntry2.toURI().toString();
+            ((BrooklynProperties)app.getManagementContext().getConfig()).put(propName, propValue);
+    
+            BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
+                    .configure(BrooklynNode.RUN_DIR, tempDir.getAbsolutePath())
+                    );
+            app.start(locs);
+            log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
+
+            assertEquals(Files.readLines(expectedFile1, Charsets.UTF_8), ImmutableList.of(content));
+            assertEquals(Files.readLines(expectedFile2, Charsets.UTF_8), ImmutableList.of(content));
+        } finally {
+            expectedFile1.delete();
+            expectedFile2.delete();
+            tempDir.delete();
+            classpathEntry1.delete();
+            classpathEntry2.delete();
+        }
+    }
+    
+    // TODO test that the classpath set above is actually used
+
+    @Test(groups="Integration")
+    public void testSetsBrooklynWebConsolePort() throws Exception {
+        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
+                .configure(BrooklynNode.HTTP_PORT, PortRanges.fromString("45000+")));
+        app.start(locs);
+        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
+
+        Integer httpPort = brooklynNode.getAttribute(BrooklynNode.HTTP_PORT);
+        URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI);
+        assertTrue(httpPort >= 45000 && httpPort < 54100, "httpPort="+httpPort);
+        assertEquals((Integer)webConsoleUri.getPort(), httpPort);
+        HttpTestUtils.assertHttpStatusCodeEquals(webConsoleUri.toString(), 200, 401);
+    }
+
+    @Test(groups="Integration")
+    public void testStartsAppOnStartup() throws Exception {
+        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
+                .configure(BrooklynNode.APP, BasicApplicationImpl.class.getName()));
+        app.start(locs);
+        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
+
+        URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI);
+        waitForApps(webConsoleUri, 1);
+        String apps = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications");
+        List<String> appType = parseJsonList(apps, ImmutableList.of("spec", "type"), String.class);
+        assertEquals(appType, ImmutableList.of(BasicApplication.class.getName()));
+    }
+
+    protected static void waitForApps(String webConsoleUri) {
+        HttpTestUtils.assertHttpStatusCodeEquals(webConsoleUri+"/v1/applications", 200, 403);
+        HttpTestUtils.assertHttpStatusCodeEventuallyEquals(webConsoleUri+"/v1/applications", 200);
+    }
+
+    // TODO Should introduce startup stages and let the client select which stage it expects to be complete
+    protected void waitForApps(final URI webConsoleUri, final int num) {
+        waitForApps(webConsoleUri.toString());
+        
+        // e.g. [{"id":"UnBqPcqg","spec":{"name":"Application (UnBqPcqg)","type":"brooklyn.entity.basic.BasicApplication","locations":["pOL4NtiW"]},"status":"RUNNING","links":{"self":"/v1/applications/UnBqPcqg","entities":"/v1/applications/UnBqPcqg/entities"}}]
+        Asserts.succeedsEventually(new Runnable() {
+            @Override
+            public void run() {
+                //Wait all apps to become managed
+                String appsContent = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications");
+                List<String> appIds = parseJsonList(appsContent, ImmutableList.of("id"), String.class);
+                assertEquals(appIds.size(), num);
+                
+                // and then to start
+                List<String> statuses = parseJsonList(appsContent, ImmutableList.of("status"), String.class);
+                for (String status : statuses) {
+                    assertEquals(status, Lifecycle.RUNNING.toString().toUpperCase());
+                }
+            }});
+    }
+
+    @Test(groups="Integration")
+    public void testStartsAppViaEffector() throws Exception {
+        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest());
+        app.start(locs);
+        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
+        
+        // note there is also a test for this in DeployApplication
+        final URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI);
+        waitForApps(webConsoleUri.toString());
+
+        final String id = brooklynNode.invoke(BrooklynNode.DEPLOY_BLUEPRINT, ConfigBag.newInstance()
+            .configure(DeployBlueprintEffector.BLUEPRINT_TYPE, BasicApplication.class.getName())
+            .getAllConfig()).get();
+        
+        String apps = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications");
+        List<String> appType = parseJsonList(apps, ImmutableList.of("spec", "type"), String.class);
+        assertEquals(appType, ImmutableList.of(BasicApplication.class.getName()));
+        
+        HttpTestUtils.assertContentEventuallyMatches(
+            webConsoleUri.toString()+"/v1/applications/"+id+"/entities/"+id+"/sensors/service.state",
+            "\"?(running|RUNNING)\"?");
+    }
+    
+    @Test(groups="Integration")
+    public void testUsesLocation() throws Exception {
+        String brooklynPropertiesContents = 
+            "brooklyn.location.named.mynamedloc=localhost:(name=myname)\n"+
+                //force lat+long so test will work when offline
+                "brooklyn.location.named.mynamedloc.latitude=123\n"+ 
+                "brooklyn.location.named.mynamedloc.longitude=45.6\n";
+
+        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
+            .configure(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_CONTENTS, brooklynPropertiesContents)
+            .configure(BrooklynNode.APP, BasicApplicationImpl.class.getName())
+            .configure(BrooklynNode.LOCATIONS, "named:mynamedloc"));
+        app.start(locs);
+        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
+
+        URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI);
+        waitForApps(webConsoleUri, 1);
+
+        // Check that "mynamedloc" has been picked up from the brooklyn.properties
+        String locsContent = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/locations");
+        List<String> locNames = parseJsonList(locsContent, ImmutableList.of("name"), String.class);
+        assertTrue(locNames.contains("mynamedloc"), "locNames="+locNames);
+
+        // Find the id of the concrete location instance of the app
+        String appsContent = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications");
+        List<String[]> appLocationIds = parseJsonList(appsContent, ImmutableList.of("spec", "locations"), String[].class);
+        String appLocationId = Iterables.getOnlyElement(appLocationIds)[0];  // app.getManagementContext().getLocationRegistry()
+
+        // Check that the concrete location is of the required type
+        String locatedLocationsContent = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/locations/usage/LocatedLocations");
+        assertEquals(parseJson(locatedLocationsContent, ImmutableList.of(appLocationId, "name"), String.class), "myname");
+        assertEquals(parseJson(locatedLocationsContent, ImmutableList.of(appLocationId, "longitude"), Double.class), 45.6, 0.00001);
+    }
+
+    @Test(groups="Integration")
+    public void testAuthenticationAndHttps() throws Exception {
+        String adminPassword = "p4ssw0rd";
+        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
+            .configure(BrooklynNode.ENABLED_HTTP_PROTOCOLS, ImmutableList.of("https"))
+            .configure(BrooklynNode.MANAGEMENT_PASSWORD, adminPassword)
+            .configure(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_CONTENTS,
+                Strings.lines(
+                    "brooklyn.webconsole.security.https.required=true",
+                    "brooklyn.webconsole.security.users=admin",
+                    "brooklyn.webconsole.security.user.admin.password="+adminPassword,
+                    "brooklyn.location.localhost.enabled=false") )
+            );
+        app.start(locs);
+        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
+
+        URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI);
+        Assert.assertTrue(webConsoleUri.toString().startsWith("https://"), "web console not https: "+webConsoleUri);
+        Integer httpsPort = brooklynNode.getAttribute(BrooklynNode.HTTPS_PORT);
+        Assert.assertTrue(httpsPort!=null && httpsPort >= 8443 && httpsPort <= 8500);
+        Assert.assertTrue(webConsoleUri.toString().contains(""+httpsPort), "web console not using right https port ("+httpsPort+"): "+webConsoleUri);
+        HttpTestUtils.assertHttpStatusCodeEquals(webConsoleUri.toString(), 401);
+
+        HttpClient http = HttpTool.httpClientBuilder()
+            .trustAll()
+            .uri(webConsoleUri)
+            .laxRedirect(true)
+            .credentials(new UsernamePasswordCredentials("admin", adminPassword))
+            .build();
+        HttpToolResponse response = HttpTool.httpGet(http, webConsoleUri, MutableMap.<String,String>of());
+        Assert.assertEquals(response.getResponseCode(), 200);
+    }
+
+    @Test(groups="Integration")
+    public void testStopPlainThrowsException() throws Exception {
+        BrooklynNode brooklynNode = setUpBrooklynNodeWithApp();
+
+        // Not using annotation with `expectedExceptions = PropagatedRuntimeException.class` because want to 
+        // ensure exception comes from stop. On jenkins, was seeing setUpBrooklynNodeWithApp fail in 
+        // testStopAndKillAppsEffector; so can't tell if this method was really passing!
+        try {
+            brooklynNode.stop();
+            fail("Expected "+brooklynNode+" stop to fail, because has app");
+        } catch (Exception e) {
+            IllegalStateException ise = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
+            if (ise != null && ise.toString().contains("Can't stop instance with running applications")) {
+                // success
+            } else {
+                throw e;
+            }
+        } finally {
+            try {
+                brooklynNode.invoke(BrooklynNode.STOP_NODE_AND_KILL_APPS, ImmutableMap.of(StopNodeAndKillAppsEffector.TIMEOUT.getName(), Duration.THIRTY_SECONDS)).getUnchecked();
+            } catch (Exception e) {
+                log.warn("Error in stopNodeAndKillApps for "+brooklynNode+" (continuing)", e);
+            }
+        }
+    }
+
+    @Test(groups="Integration")
+    public void testStopAndKillAppsEffector() throws Exception {
+        createNodeAndExecStopEffector(BrooklynNode.STOP_NODE_AND_KILL_APPS);
+    }
+
+    @Test(groups="Integration")
+    public void testStopButLeaveAppsEffector() throws Exception {
+        createNodeAndExecStopEffector(BrooklynNode.STOP_NODE_BUT_LEAVE_APPS);
+    }
+    
+    @Test(groups="Integration")
+    public void testStopAndRestartProcess() throws Exception {
+        persistenceDir = Files.createTempDir();
+        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
+                .configure(BrooklynNode.EXTRA_LAUNCH_PARAMETERS, "--persist auto --persistenceDir "+persistenceDir.getAbsolutePath())
+                .configure(BrooklynNode.APP, BasicApplicationImpl.class.getName()));
+        app.start(locs);
+        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
+        File pidFile = new File(getDriver(brooklynNode).getPidFile());
+        URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI);
+
+        waitForApps(webConsoleUri, 1);
+
+        // Stop just the process; will not have unmanaged entity unless machine was being terminated 
+        brooklynNode.invoke(BrooklynNode.STOP, ImmutableMap.<String, Object>of(
+                BrooklynNode.StopSoftwareParameters.STOP_MACHINE_MODE.getName(), StopMode.NEVER,
+                BrooklynNode.StopSoftwareParameters.STOP_PROCESS_MODE.getName(), StopMode.ALWAYS)).getUnchecked();
+
+        assertTrue(Entities.isManaged(brooklynNode));
+        assertFalse(isPidRunning(pidFile), "pid in "+pidFile+" still running");
+        
+        // Clear the startup app so it's not started second time, in addition to the rebind state
+        // TODO remove this once the startup app is created only if no previous persistence state
+        brooklynNode.config().set(BrooklynNode.APP, (String)null);
+        ((EntityLocal)brooklynNode).setAttribute(BrooklynNode.APP, null);
+        
+        // Restart the process; expect persisted state to have been restored, so apps still known about
+        brooklynNode.invoke(BrooklynNode.RESTART, ImmutableMap.<String, Object>of(
+                BrooklynNode.RestartSoftwareParameters.RESTART_MACHINE.getName(), "false")).getUnchecked();
+
+        waitForApps(webConsoleUri.toString());
+        String apps = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications");
+        List<String> appType = parseJsonList(apps, ImmutableList.of("spec", "type"), String.class);
+        assertEquals(appType, ImmutableList.of(BasicApplication.class.getName()));
+    }
+
+    private void createNodeAndExecStopEffector(Effector<?> eff) throws Exception {
+        BrooklynNode brooklynNode = setUpBrooklynNodeWithApp();
+        File pidFile = new File(getDriver(brooklynNode).getPidFile());
+        assertTrue(isPidRunning(pidFile));
+        
+        brooklynNode.invoke(eff, Collections.<String, Object>emptyMap()).getUnchecked();
+
+        // Note can't use driver.isRunning to check shutdown; can't invoke scripts on an unmanaged entity
+        EntityTestUtils.assertAttributeEquals(brooklynNode, BrooklynNode.SERVICE_UP, false);
+        
+        // unmanaged if the machine is destroyed - ie false on localhost (this test by default), but true in the cloud 
+//        assertFalse(Entities.isManaged(brooklynNode));
+        
+        assertFalse(isPidRunning(pidFile), "pid in "+pidFile+" still running");
+    }
+
+    private boolean isPidRunning(File pidFile) throws Exception {
+        SshMachineLocation machine = loc.obtain();
+        try {
+            int result = machine.execScript("check-pid", ImmutableList.of(
+                    "test -f "+pidFile+" || exit 1",
+                    "ps -p `cat "+pidFile+"`"));
+            return result == 0;
+        } finally {
+            loc.release(machine);
+            Locations.unmanage(machine);
+        }
+    }
+    
+    private BrooklynNodeSshDriver getDriver(BrooklynNode brooklynNode) {
+        try {
+            EntityProxyImpl entityProxy = (EntityProxyImpl)Proxy.getInvocationHandler(brooklynNode);
+            Method getDriver = BrooklynNodeImpl.class.getMethod("getDriver");
+            return (BrooklynNodeSshDriver)entityProxy.invoke(brooklynNode, getDriver, new Object[]{});
+        } catch (Throwable e) {
+            throw Exceptions.propagate(e);
+        }
+    }
+
+    private BrooklynNode setUpBrooklynNodeWithApp() throws InterruptedException,
+            ExecutionException {
+        BrooklynNode brooklynNode = app.createAndManageChild(EntitySpec.create(BrooklynNode.class)
+                .configure(BrooklynNode.NO_WEB_CONSOLE_AUTHENTICATION, Boolean.TRUE));
+        app.start(locs);
+        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
+
+        EntityTestUtils.assertAttributeEqualsEventually(brooklynNode, BrooklynNode.SERVICE_UP, true);
+
+        String baseUrl = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI).toString();
+        waitForApps(baseUrl);
+        
+        final String id = brooklynNode.invoke(BrooklynNode.DEPLOY_BLUEPRINT, ConfigBag.newInstance()
+                .configure(DeployBlueprintEffector.BLUEPRINT_TYPE, BasicApplication.class.getName())
+                .getAllConfig()).get();
+
+        String entityUrl = Urls.mergePaths(baseUrl, "v1/applications/", id, "entities", id);
+        
+        Entity mirror = brooklynNode.addChild(EntitySpec.create(BrooklynEntityMirror.class)
+                .configure(BrooklynEntityMirror.MIRRORED_ENTITY_URL, entityUrl)
+                .configure(BrooklynEntityMirror.MIRRORED_ENTITY_ID, id));
+        Entities.manage(mirror);
+
+        assertEquals(brooklynNode.getChildren().size(), 1);
+        return brooklynNode;
+    }
+
+    private <T> T parseJson(String json, List<String> elements, Class<T> clazz) {
+        Function<String, T> func = Functionals.chain(
+                JsonFunctions.asJson(),
+                JsonFunctions.walk(elements),
+                JsonFunctions.cast(clazz));
+        return func.apply(json);
+    }
+
+    private <T> List<T> parseJsonList(String json, List<String> elements, Class<T> clazz) {
+        Function<String, List<T>> func = Functionals.chain(
+                JsonFunctions.asJson(),
+                JsonFunctions.forEach(Functionals.chain(
+                        JsonFunctions.walk(elements),
+                        JsonFunctions.cast(clazz))));
+        return func.apply(json);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeTest.java
new file mode 100644
index 0000000..60d2c6b
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeTest.java
@@ -0,0 +1,141 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
+import java.util.List;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.entity.drivers.downloads.DownloadResolver;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNodeImpl;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNodeSshDriver;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.trait.Startable;
+import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.collections.MutableSet;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableMap;
+
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+public class BrooklynNodeTest {
+
+    // TODO Need test for copying/setting classpath
+    
+    private TestApplication app;
+    private SshMachineLocation loc;
+    
+    public static class SlowStopBrooklynNode extends BrooklynNodeImpl {
+        public SlowStopBrooklynNode() {}
+        
+        @Override
+        protected void postStop() {
+            super.postStop();
+            
+            //Make sure UnmanageTask will wait for the STOP effector to complete.
+            Time.sleep(Duration.FIVE_SECONDS);
+        }
+        
+    }
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        app = TestApplication.Factory.newManagedInstanceForTests();
+        loc = new SshMachineLocation(MutableMap.of("address", "localhost"));
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (app != null) Entities.destroyAll(app.getManagementContext());
+    }
+    
+    @Test
+    public void testGeneratesCorrectSnapshotDownload() throws Exception {
+        String version = "0.0.1-SNAPSHOT";
+        String expectedUrl = "https://repository.apache.org/service/local/artifact/maven/redirect?r=snapshots&g=org.apache.brooklyn&v="+version+"&a=brooklyn-dist&c=dist&e=tar.gz";
+        runTestGeneratesCorrectDownloadUrl(version, expectedUrl);
+    }
+    
+    @Test
+    public void testGeneratesCorrectReleaseDownload() throws Exception {
+        String version = "0.0.1";
+        String expectedUrl = "http://search.maven.org/remotecontent?filepath=org/apache/brooklyn/brooklyn-dist/"+version+"/brooklyn-dist-"+version+"-dist.tar.gz";
+        runTestGeneratesCorrectDownloadUrl(version, expectedUrl);
+    }
+    
+    private void runTestGeneratesCorrectDownloadUrl(String version, String expectedUrl) throws Exception {
+        // TODO Using BrooklynNodeImpl directly, because want to instantiate a BroolynNodeSshDriver.
+        //      Really want to make that easier to test, without going through "wrong" code path for creating entity.
+        BrooklynNodeImpl entity = new BrooklynNodeImpl();
+        entity.setConfig(BrooklynNode.SUGGESTED_VERSION, version);
+        entity.setParent(app);
+        Entities.manage(entity);
+        ConfigToAttributes.apply(entity);
+        BrooklynNodeSshDriver driver = new BrooklynNodeSshDriver(entity, loc);
+        
+        DownloadResolver resolver = Entities.newDownloader(driver);
+        List<String> urls = resolver.getTargets();
+        
+        System.out.println("urls="+urls);
+        assertTrue(urls.contains(expectedUrl), "urls="+urls);
+    }
+    
+    @Test(groups = "Integration")
+    public void testUnmanageOnStop() throws Exception {
+        final BrooklynNode node = app.addChild(EntitySpec.create(BrooklynNode.class).impl(SlowStopBrooklynNode.class));
+        Entities.manage(node);
+        assertTrue(Entities.isManaged(node), "Entity " + node + " must be managed.");
+        node.invoke(Startable.STOP, ImmutableMap.<String,Object>of()).asTask().getUnchecked();
+        //The UnmanageTask will unblock after the STOP effector completes, so we are competing with it here.
+        Asserts.succeedsEventually(new Runnable() {
+            @Override
+            public void run() {
+                assertFalse(Entities.isManaged(node));
+            }
+        });
+    }
+    
+
+    @Test
+    public void testCanStartSameNode() throws Exception {
+        // not very interesting as do not have REST when run in this project
+        // but test BrooklynNodeRestTest in downstream project does
+        BrooklynNode bn = app.createAndManageChild(EntitySpec.create(BrooklynNode.class, SameBrooklynNodeImpl.class));
+        bn.start(MutableSet.<Location>of());
+        
+        Assert.assertEquals(bn.getAttribute(Attributes.SERVICE_UP), (Boolean)true);
+        // no URI
+        Assert.assertNull(bn.getAttribute(BrooklynNode.WEB_CONSOLE_URI));
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/CallbackEntityHttpClient.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/CallbackEntityHttpClient.java b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/CallbackEntityHttpClient.java
new file mode 100644
index 0000000..c933b9d
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/CallbackEntityHttpClient.java
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.entity.brooklynnode.EntityHttpClient;
+import org.apache.brooklyn.util.core.http.HttpToolResponse;
+import org.apache.brooklyn.util.core.http.HttpTool.HttpClientBuilder;
+import org.apache.http.HttpStatus;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+
+import com.google.common.base.Function;
+import com.google.common.base.Predicate;
+
+public class CallbackEntityHttpClient implements EntityHttpClient {
+    public static class Request {
+        private Entity entity;
+        private String method;
+        private String path;
+        private Map<String, String> params;
+        public Request(Entity entity, String method, String path, Map<String, String> params) {
+            this.entity = entity;
+            this.method = method;
+            this.path = path;
+            this.params = params;
+        }
+        public Entity getEntity() {
+            return entity;
+        }
+        public String getMethod() {
+            return method;
+        }
+        public String getPath() {
+            return path;
+        }
+        public Map<String, String> getParams() {
+            return params;
+        }
+    }
+    private Function<Request, String> callback;
+    private Entity entity;
+
+    public CallbackEntityHttpClient(Entity entity, Function<Request, String> callback) {
+        this.entity = entity;
+        this.callback = callback;
+    }
+
+    @Override
+    public HttpClientBuilder getHttpClientForBrooklynNode() {
+        throw new IllegalStateException("Method call not expected");
+    }
+
+    @Override
+    public HttpToolResponse get(String path) {
+        String result = callback.apply(new Request(entity, HttpGet.METHOD_NAME, path, Collections.<String, String>emptyMap()));
+        return new HttpToolResponse(HttpStatus.SC_OK, null, result.getBytes(), 0, 0, 0);
+    }
+
+    @Override
+    public HttpToolResponse post(String path, Map<String, String> headers, byte[] body) {
+        throw new IllegalStateException("Method call not expected");
+    }
+
+    @Override
+    public HttpToolResponse post(String path, Map<String, String> headers, Map<String, String> formParams) {
+        String result = callback.apply(new Request(entity, HttpPost.METHOD_NAME, path, formParams));
+        return new HttpToolResponse(HttpStatus.SC_OK, Collections.<String, List<String>>emptyMap(), result.getBytes(), 0, 0, 0);
+    }
+    
+    @Override
+    public HttpToolResponse delete(String path, Map<String, String> headers) {
+        throw new IllegalStateException("Method call not expected");
+    }
+
+    @Override
+    public EntityHttpClient responseSuccess(Predicate<Integer> successPredicate) {
+        throw new IllegalStateException("Method call not expected");
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/MockBrooklynNode.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/MockBrooklynNode.java b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/MockBrooklynNode.java
new file mode 100644
index 0000000..fcc939f
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/MockBrooklynNode.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import java.util.Collection;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+import org.apache.brooklyn.entity.brooklynnode.EntityHttpClient;
+import org.apache.brooklyn.entity.brooklynnode.CallbackEntityHttpClient.Request;
+import org.apache.brooklyn.entity.brooklynnode.effector.SetHighAvailabilityModeEffectorBody;
+import org.apache.brooklyn.entity.brooklynnode.effector.SetHighAvailabilityPriorityEffectorBody;
+import org.apache.brooklyn.entity.core.AbstractEntity;
+import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
+
+import com.google.common.base.Function;
+import com.google.common.reflect.TypeToken;
+
+public class MockBrooklynNode extends AbstractEntity implements BrooklynNode {
+    @SuppressWarnings("serial")
+    public static final ConfigKey<Function<Request, String>> HTTP_CLIENT_CALLBACK = ConfigKeys.newConfigKey(new TypeToken<Function<Request, String>>(){}, "httpClientCallback");
+    public static final AttributeSensor<Integer> HA_PRIORITY = new BasicAttributeSensor<Integer>(Integer.class, "priority");
+    
+    @Override
+    public void init() {
+        super.init();
+        getMutableEntityType().addEffector(SetHighAvailabilityPriorityEffectorBody.SET_HIGH_AVAILABILITY_PRIORITY);
+        getMutableEntityType().addEffector(SetHighAvailabilityModeEffectorBody.SET_HIGH_AVAILABILITY_MODE);
+        setAttribute(HA_PRIORITY, 0);
+    }
+
+    @Override
+    public EntityHttpClient http() {
+        return new CallbackEntityHttpClient(this, getConfig(HTTP_CLIENT_CALLBACK));
+    }
+
+    @Override
+    public void start(Collection<? extends Location> locations) {
+    }
+
+    @Override
+    public void stop() {
+    }
+
+    @Override
+    public void restart() {
+    }
+
+    @Override
+    public void populateServiceNotUpDiagnostics() {
+        // no-op
+    }    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/SameBrooklynNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/SameBrooklynNodeImpl.java b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/SameBrooklynNodeImpl.java
new file mode 100644
index 0000000..84d2c33
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/SameBrooklynNodeImpl.java
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import java.net.URI;
+import java.util.Collection;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+import org.apache.brooklyn.entity.brooklynnode.EntityHttpClient;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNodeImpl.DeployBlueprintEffectorBody;
+import org.apache.brooklyn.entity.core.AbstractEntity;
+import org.apache.brooklyn.sensor.feed.http.HttpFeed;
+import org.apache.brooklyn.sensor.feed.http.HttpPollConfig;
+import org.apache.brooklyn.sensor.feed.http.HttpValueFunctions;
+
+/** Implementation of BrooklynNode which just presents the node where this is running, for convenience;
+ * 
+ *  start/stop/restart have no effect; 
+ *  sensors are connected;
+ *  deploy blueprint assumes that a REST endpoint is available */
+public class SameBrooklynNodeImpl extends AbstractEntity implements BrooklynNode {
+    
+    private HttpFeed httpFeed;
+
+    @Override
+    public void start(Collection<? extends Location> locations) {
+        connectSensors();
+    }
+
+    @Override
+    public void stop() {
+        disconnectSensors();
+    }
+
+    @Override
+    public void restart() {
+        return;
+    }
+
+    
+    @Override
+    public void init() {
+        super.init();
+        getMutableEntityType().addEffector(DeployBlueprintEffectorBody.DEPLOY_BLUEPRINT);
+    }
+    
+    protected void connectSensors() {
+        URI webConsoleUri = getManagementContext().getManagementNodeUri().orNull();
+        setAttribute(WEB_CONSOLE_URI, webConsoleUri);
+
+        if (webConsoleUri != null) {
+            httpFeed = HttpFeed.builder()
+                    .entity(this)
+                    .period(200)
+                    .baseUri(webConsoleUri)
+                    .credentialsIfNotNull(getConfig(MANAGEMENT_USER), getConfig(MANAGEMENT_PASSWORD))
+                    .poll(new HttpPollConfig<Boolean>(SERVICE_UP)
+                            .onSuccess(HttpValueFunctions.responseCodeEquals(200))
+                            .setOnFailureOrException(false))
+                    .build();
+
+        } else {
+            setAttribute(SERVICE_UP, true);
+        }
+    }
+    
+    protected void disconnectSensors() {
+        if (httpFeed != null) httpFeed.stop();
+    }
+
+    @Override
+    public EntityHttpClient http() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void populateServiceNotUpDiagnostics() {
+        // no-op
+    }    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/SelectMasterEffectorTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/SelectMasterEffectorTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/SelectMasterEffectorTest.java
new file mode 100644
index 0000000..60cc6e9
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/brooklynnode/SelectMasterEffectorTest.java
@@ -0,0 +1,259 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.Callable;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.entity.Group;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynCluster;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynClusterImpl;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynCluster.SelectMasterEffector;
+import org.apache.brooklyn.entity.brooklynnode.CallbackEntityHttpClient.Request;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.group.DynamicCluster;
+import org.apache.brooklyn.sensor.feed.AttributePollHandler;
+import org.apache.brooklyn.sensor.feed.DelegatingPollHandler;
+import org.apache.brooklyn.sensor.feed.Poller;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.http.client.methods.HttpPost;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Function;
+import com.google.common.base.Objects;
+import com.google.common.collect.ImmutableMap;
+
+public class SelectMasterEffectorTest extends BrooklynAppUnitTestSupport {
+    private static final Logger LOG = LoggerFactory.getLogger(BrooklynClusterImpl.class);
+
+    protected BrooklynCluster cluster;
+    protected HttpCallback http; 
+    protected Poller<Void> poller;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        super.setUp();
+
+        // because the effector calls wait for a state change, use a separate thread to drive that 
+        poller = new Poller<Void>((EntityLocal)app, false);
+        poller.scheduleAtFixedRate(
+            new Callable<Void>() {
+                @Override
+                public Void call() throws Exception {
+                    masterFailoverIfNeeded();
+                    return null;
+                }
+            },
+            new DelegatingPollHandler<Void>(Collections.<AttributePollHandler<? super Void>>emptyList()),
+            Duration.millis(20));
+        poller.start();
+    }
+
+    @Override
+    protected void setUpApp() {
+        super.setUpApp();
+        http = new HttpCallback();
+        cluster = app.createAndManageChild(EntitySpec.create(BrooklynCluster.class)
+            .location(app.newLocalhostProvisioningLocation())
+            .configure(BrooklynCluster.MEMBER_SPEC, EntitySpec.create(BrooklynNode.class)
+                .impl(MockBrooklynNode.class)
+                .configure(MockBrooklynNode.HTTP_CLIENT_CALLBACK, http)));
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        poller.stop();
+        super.tearDown();
+    }
+
+    @Test
+    public void testInvalidNewMasterIdFails() {
+        try {
+            selectMaster(cluster, "1234");
+            fail("Non-existend entity ID provided.");
+        } catch (Exception e) {
+            assertTrue(e.toString().contains("1234 is not an ID of brooklyn node in this cluster"));
+        }
+    }
+
+    @Test(groups="Integration") // because slow, due to sensor feeds
+    public void testSelectMasterAfterChange() {
+        List<Entity> nodes = makeTwoNodes();
+        EntityTestUtils.assertAttributeEqualsEventually(cluster, BrooklynCluster.MASTER_NODE, (BrooklynNode)nodes.get(0));
+
+        selectMaster(cluster, nodes.get(1).getId());
+        checkMaster(cluster, nodes.get(1));
+    }
+
+    @Test
+    public void testFindMaster() {
+        List<Entity> nodes = makeTwoNodes();
+        Assert.assertEquals(((BrooklynClusterImpl)Entities.deproxy(cluster)).findMasterChild(), nodes.get(0));
+    }
+    
+    @Test(groups="Integration") // because slow, due to sensor feeds
+    public void testSelectMasterFailsAtChangeState() {
+        http.setFailAtStateChange(true);
+
+        List<Entity> nodes = makeTwoNodes();
+        
+        EntityTestUtils.assertAttributeEqualsEventually(cluster, BrooklynCluster.MASTER_NODE, (BrooklynNode)nodes.get(0));
+
+        try {
+            selectMaster(cluster, nodes.get(1).getId());
+            fail("selectMaster should have failed");
+        } catch (Exception e) {
+            // expected
+        }
+        checkMaster(cluster, nodes.get(0));
+    }
+
+    private List<Entity> makeTwoNodes() {
+        List<Entity> nodes = MutableList.copyOf(cluster.resizeByDelta(2));
+        setManagementState(nodes.get(0), ManagementNodeState.MASTER);
+        setManagementState(nodes.get(1), ManagementNodeState.HOT_STANDBY);
+        return nodes;
+    }
+
+    private void checkMaster(Group cluster, Entity node) {
+        assertEquals(node.getAttribute(BrooklynNode.MANAGEMENT_NODE_STATE), ManagementNodeState.MASTER);
+        assertEquals(cluster.getAttribute(BrooklynCluster.MASTER_NODE), node);
+        for (Entity member : cluster.getMembers()) {
+            if (member != node) {
+                assertEquals(member.getAttribute(BrooklynNode.MANAGEMENT_NODE_STATE), ManagementNodeState.HOT_STANDBY);
+            }
+            assertEquals((int)member.getAttribute(MockBrooklynNode.HA_PRIORITY), 0);
+        }
+    }
+
+    private static class HttpCallback implements Function<CallbackEntityHttpClient.Request, String> {
+        private enum State {
+            INITIAL,
+            PROMOTED
+        }
+        private State state = State.INITIAL;
+        private boolean failAtStateChange;
+
+        @Override
+        public String apply(Request input) {
+            if ("/v1/server/ha/state".equals(input.getPath())) {
+                if (failAtStateChange) {
+                    throw new RuntimeException("Testing failure at changing node state");
+                }
+
+                checkRequest(input, HttpPost.METHOD_NAME, "/v1/server/ha/state", "mode", "HOT_STANDBY");
+                Entity entity = input.getEntity();
+                EntityTestUtils.assertAttributeEquals(entity, BrooklynNode.MANAGEMENT_NODE_STATE, ManagementNodeState.MASTER);
+                EntityTestUtils.assertAttributeEquals(entity, MockBrooklynNode.HA_PRIORITY, 0);
+
+                setManagementState(entity, ManagementNodeState.HOT_STANDBY);
+
+                return "MASTER";
+            } else {
+                switch(state) {
+                case INITIAL:
+                    checkRequest(input, HttpPost.METHOD_NAME, "/v1/server/ha/priority", "priority", "1");
+                    state = State.PROMOTED;
+                    setPriority(input.getEntity(), Integer.parseInt(input.getParams().get("priority")));
+                    return "0";
+                case PROMOTED:
+                    checkRequest(input, HttpPost.METHOD_NAME, "/v1/server/ha/priority", "priority", "0");
+                    state = State.INITIAL;
+                    setPriority(input.getEntity(), Integer.parseInt(input.getParams().get("priority")));
+                    return "1";
+                default: throw new IllegalStateException("Illegal call at state " + state + ". Request = " + input.getMethod() + " " + input.getPath());
+                }
+            }
+        }
+
+        public void checkRequest(Request input, String methodName, String path, String key, String value) {
+            if (!input.getMethod().equals(methodName) || !input.getPath().equals(path)) {
+                throw new IllegalStateException("Request doesn't match expected state. Expected = " + input.getMethod() + " " + input.getPath() + ". " +
+                        "Actual = " + methodName + " " + path);
+            }
+
+            String inputValue = input.getParams().get(key);
+            if(!Objects.equal(value, inputValue)) {
+                throw new IllegalStateException("Request doesn't match expected parameter " + methodName + " " + path + ". Parameter " + key + 
+                    " expected = " + value + ", actual = " + inputValue);
+            }
+        }
+
+        public void setFailAtStateChange(boolean failAtStateChange) {
+            this.failAtStateChange = failAtStateChange;
+        }
+
+    }
+
+    private void masterFailoverIfNeeded() {
+        if (!Entities.isManaged(cluster)) return;
+        if (cluster.getAttribute(BrooklynCluster.MASTER_NODE) == null) {
+            Collection<Entity> members = cluster.getMembers();
+            if (members.size() > 0) {
+                for (Entity member : members) {
+                    if (member.getAttribute(MockBrooklynNode.HA_PRIORITY) == 1) {
+                        masterFailover(member);
+                        return;
+                    }
+                }
+                masterFailover(members.iterator().next());
+            }
+        }
+    }
+
+    private void masterFailover(Entity member) {
+        LOG.debug("Master failover to " + member);
+        setManagementState(member, ManagementNodeState.MASTER);
+        EntityTestUtils.assertAttributeEqualsEventually(cluster, BrooklynCluster.MASTER_NODE, (BrooklynNode)member);
+        return;
+    }
+
+    public static void setManagementState(Entity entity, ManagementNodeState state) {
+        ((EntityLocal)entity).setAttribute(BrooklynNode.MANAGEMENT_NODE_STATE, state);
+    }
+
+    public static void setPriority(Entity entity, int priority) {
+        ((EntityLocal)entity).setAttribute(MockBrooklynNode.HA_PRIORITY, priority);
+    }
+
+    private void selectMaster(DynamicCluster cluster, String id) {
+        app.getExecutionContext().submit(Effectors.invocation(cluster, BrooklynCluster.SELECT_MASTER, ImmutableMap.of(SelectMasterEffector.NEW_MASTER_ID.getName(), id))).asTask().getUnchecked();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefConfigsTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefConfigsTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefConfigsTest.java
new file mode 100644
index 0000000..6cc8e27
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefConfigsTest.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+import java.util.Set;
+
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.chef.ChefConfig;
+import org.apache.brooklyn.entity.chef.ChefConfigs;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.Test;
+
+public class ChefConfigsTest {
+
+    private TestApplication app = null;
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() {
+        if (app!=null) Entities.destroyAll(app.getManagementContext());
+        app = null;
+    }
+    
+    @Test
+    public void testAddToRunList() {
+        app = ApplicationBuilder.newManagedApp(TestApplication.class);
+        ChefConfigs.addToLaunchRunList(app, "a", "b");
+        Set<? extends String> runs = app.getConfig(ChefConfig.CHEF_LAUNCH_RUN_LIST);
+        Assert.assertEquals(runs.size(), 2, "runs="+runs);
+        Assert.assertTrue(runs.contains("a"));
+        Assert.assertTrue(runs.contains("b"));
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefLiveTestSupport.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefLiveTestSupport.java b/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefLiveTestSupport.java
new file mode 100644
index 0000000..5ea8315
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefLiveTestSupport.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
+import org.apache.brooklyn.entity.chef.ChefConfig;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.BeforeMethod;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.util.core.ResourceUtils;
+import org.apache.brooklyn.util.io.FileUtil;
+import org.apache.brooklyn.util.stream.InputStreamSupplier;
+
+import com.google.common.base.Throwables;
+import com.google.common.io.Files;
+
+public class ChefLiveTestSupport extends BrooklynAppLiveTestSupport {
+
+    private static final Logger log = LoggerFactory.getLogger(ChefLiveTestSupport.class);
+    
+    protected MachineProvisioningLocation<? extends SshMachineLocation> targetLocation;
+
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        
+        targetLocation = createLocation();
+    }
+
+    protected MachineProvisioningLocation<? extends SshMachineLocation> createLocation() {
+        return createLocation(mgmt);
+    }
+    
+    /** convenience for setting up a pre-built / fixed IP machine
+     * (because you might not want to set up Chef on localhost) 
+     * and ensuring tests against Chef use the same configured location 
+     **/
+    @SuppressWarnings("unchecked")
+    public static MachineProvisioningLocation<? extends SshMachineLocation> createLocation(ManagementContext mgmt) {
+        Location bestLocation = mgmt.getLocationRegistry().resolve("named:ChefTests", true, null).orNull();
+        if (bestLocation==null) {
+            log.info("using AWS for chef tests because named:ChefTests does not exist");
+            bestLocation = mgmt.getLocationRegistry().resolve("jclouds:aws-ec2:us-east-1");
+        }
+        if (bestLocation==null) {
+            throw new IllegalStateException("Need a location called named:ChefTests or AWS configured for these tests");
+        }
+        return (MachineProvisioningLocation<? extends SshMachineLocation>)bestLocation; 
+    }
+    
+    private static String defaultConfigFile = null; 
+    public synchronized static String installBrooklynChefHostedConfig() {
+        if (defaultConfigFile!=null) return defaultConfigFile;
+        File tempDir = Files.createTempDir();
+        ResourceUtils r = ResourceUtils.create(ChefServerTasksIntegrationTest.class);
+        try {
+            for (String f: new String[] { "knife.rb", "brooklyn-tests.pem", "brooklyn-validator.pem" }) {
+                String contents = r.getResourceAsString("classpath:///org/apache/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/"+f);
+                FileUtil.copyTo(InputStreamSupplier.fromString(contents).getInput(), new File(tempDir, f));
+            }
+        } catch (IOException e) {
+            throw Throwables.propagate(e);
+        }
+        File knifeConfig = new File(tempDir, "knife.rb");
+        defaultConfigFile = knifeConfig.getPath();
+        return defaultConfigFile;
+    }
+
+    public static void installBrooklynChefHostedConfig(Entity entity) {
+        ((EntityInternal)entity).setConfig(ChefConfig.KNIFE_CONFIG_FILE, ChefLiveTestSupport.installBrooklynChefHostedConfig());
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefServerTasksIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefServerTasksIntegrationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefServerTasksIntegrationTest.java
new file mode 100644
index 0000000..79c7be0
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/chef/ChefServerTasksIntegrationTest.java
@@ -0,0 +1,126 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.chef.ChefConfig;
+import org.apache.brooklyn.entity.chef.ChefServerTasks;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.apache.brooklyn.util.stream.StreamGobbler;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+/** Many tests expect knife on the path, but none require any configuration beyond that.
+ * They will use the Brooklyn registered account (which has been set up with mysql cookbooks and more).
+ * <p>
+ * Note this is a free account so cannot manage many nodes. 
+ * You can use the credentials in src/test/resources/hosted-chef-brooklyn-credentials/
+ * to log in and configure the settings for our tests using knife. You can also log in at:
+ * <p>
+ * https://manage.opscode.com/
+ * <p>
+ * with credentials for those with need to know (which is a lot of people, but not everyone
+ * with access to this github repo!).
+ * <p>
+ * You can easily set up your own new account, for free; download the starter kit and
+ * point {@link ChefConfig#KNIFE_CONFIG_FILE} at the knife.rb.
+ * <p>
+ * Note that if you are porting an existing machine to be managed by a new chef account, you may need to do the following:
+ * <p>
+ * ON management machine:
+ * <li>knife client delete HOST   # or bulk delete, but don't delete your validator! it is a PITA recreating and adding back all the permissions! 
+ * <li>knife node delete HOST
+ * <p>
+ * ON machine being managed:
+ * <li>rm -rf /{etc,var}/chef
+ * <p>
+ * Note also that some tests require a location  named:ChefLive  to be set up in your brooklyn.properties.
+ * This can be a cloud (but will require frequent chef-node pruning) or a permanently set-up machine.
+ **/
+public class ChefServerTasksIntegrationTest {
+
+    private static final Logger log = LoggerFactory.getLogger(ChefServerTasksIntegrationTest.class);
+    
+    protected TestApplication app;
+    protected ManagementContext mgmt;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setup() throws Exception {
+        app = ApplicationBuilder.newManagedApp(TestApplication.class);
+        mgmt = app.getManagementContext();
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (mgmt != null) Entities.destroyAll(mgmt);
+        mgmt = null;
+    }
+
+    /** @deprecated use {@link ChefLiveTestSupport} */
+    @Deprecated
+    public synchronized static String installBrooklynChefHostedConfig() {
+        return ChefLiveTestSupport.installBrooklynChefHostedConfig();
+    }
+    
+    @Test(groups="Integration")
+    @SuppressWarnings("resource")
+    public void testWhichKnife() throws IOException, InterruptedException {
+        // requires that knife is installed on the path of login shells
+        Process p = Runtime.getRuntime().exec(new String[] { "bash", "-l", "-c", "which knife" });
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        new StreamGobbler(p.getInputStream(), out, log).start();
+        new StreamGobbler(p.getErrorStream(), out, log).start();
+        log.info("bash -l -c 'which knife' gives exit code: "+p.waitFor());
+        Time.sleep(Duration.millis(1000));
+        log.info("output:\n"+out);
+        Assert.assertEquals(p.exitValue(), 0);
+    }
+
+    @Test(groups="Integration")
+    public void testKnifeWithoutConfig() {
+        // without config it shouldn't pass
+        // (assumes that knife global config is *not* installed on your machine)
+        ProcessTaskWrapper<Boolean> t = Entities.submit(app, ChefServerTasks.isKnifeInstalled());
+        log.info("isKnifeInstalled without config returned: "+t.get()+" ("+t.getExitCode()+")\n"+t.getStdout()+"\nERR:\n"+t.getStderr());
+        Assert.assertFalse(t.get());
+    }
+
+    @Test(groups="Integration")
+    public void testKnifeWithConfig() {
+        // requires that knife is installed on the path of login shells
+        // (creates the config in a temp space)
+        ChefLiveTestSupport.installBrooklynChefHostedConfig(app);
+        ProcessTaskWrapper<Boolean> t = Entities.submit(app, ChefServerTasks.isKnifeInstalled());
+        log.info("isKnifeInstalled *with* config returned: "+t.get()+" ("+t.getExitCode()+")\n"+t.getStdout()+"\nERR:\n"+t.getStderr());
+        Assert.assertTrue(t.get());
+    }
+
+}



[36/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/SoftwareProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/SoftwareProcessDriver.java b/software/base/src/main/java/brooklyn/entity/basic/SoftwareProcessDriver.java
deleted file mode 100644
index bd3d8b3..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/SoftwareProcessDriver.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import org.apache.brooklyn.api.entity.drivers.EntityDriver;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.entity.trait.Startable;
-
-/**
- * The {@link EntityDriver} for a {@link SoftwareProcess}.
- *
- * <p/>
- * In many cases it is cleaner to store entity lifecycle effectors (and sometimes other implementations) in a class to
- * which the entity delegates.  Classes implementing this interface provide this delegate, often inheriting utilities
- * specific to a particular transport (e.g. ssh) shared among many different entities.
- * <p/>
- * In this way, it is also possible for entities to cleanly support multiple mechanisms for start/stop and other methods.
- */
-public interface SoftwareProcessDriver extends EntityDriver {
-
-    /**
-     * The entity whose components we are controlling.
-     */
-    EntityLocal getEntity();
-
-    /**
-     * Whether the entity components have started.
-     */
-    boolean isRunning();
-
-    /**
-     * Rebinds the driver to a pre-existing software process.
-     */
-    void rebind();
-
-    /**
-     * Performs software start (or queues tasks to do this)
-     */
-    void start();
-
-    /**
-     * Performs software restart (or queues tasks to do this).
-     * Unlike stop/start implementations here are expected to update SERVICE_STATE for STOPPING and STARTING
-     * as appropriate (but framework will set RUNNING afterwards, after detecting it is running).
-     * @see Startable#restart()
-     */
-    void restart();
-
-    /**
-     * Performs software stop (or queues tasks to do this) 
-     * @see Startable#stop()
-     */
-    void stop();
-
-    /**
-     * Kills the process, ungracefully and immediately where possible (e.g. with `kill -9`).
-     */
-    void kill();
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/SoftwareProcessDriverLifecycleEffectorTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/SoftwareProcessDriverLifecycleEffectorTasks.java b/software/base/src/main/java/brooklyn/entity/basic/SoftwareProcessDriverLifecycleEffectorTasks.java
deleted file mode 100644
index 5ce7667..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/SoftwareProcessDriverLifecycleEffectorTasks.java
+++ /dev/null
@@ -1,262 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.mgmt.TaskAdaptable;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
-import org.apache.brooklyn.entity.trait.StartableMethods;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.text.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcess.ChildStartableMode;
-import brooklyn.entity.basic.SoftwareProcess.RestartSoftwareParameters;
-import brooklyn.entity.basic.SoftwareProcess.RestartSoftwareParameters.RestartMachineMode;
-import brooklyn.entity.software.MachineLifecycleEffectorTasks;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Supplier;
-
-/** Thin shim delegating to driver to do start/stop/restart, wrapping as tasks,
- * with common code pulled up to {@link MachineLifecycleEffectorTasks} for non-driver usage 
- * @since 0.6.0 */
-@Beta
-public class SoftwareProcessDriverLifecycleEffectorTasks extends MachineLifecycleEffectorTasks {
-    
-    private static final Logger log = LoggerFactory.getLogger(SoftwareProcessDriverLifecycleEffectorTasks.class);
-    
-    public void restart(ConfigBag parameters) {
-        RestartMachineMode isRestartMachine = parameters.get(RestartSoftwareParameters.RESTART_MACHINE_TYPED);
-        if (isRestartMachine==null) 
-            isRestartMachine=RestartMachineMode.AUTO;
-        if (isRestartMachine==RestartMachineMode.AUTO) 
-            isRestartMachine = getDefaultRestartStopsMachine() ? RestartMachineMode.TRUE : RestartMachineMode.FALSE; 
-
-        if (isRestartMachine==RestartMachineMode.TRUE) {
-            log.debug("restart of "+entity()+" requested be applied at machine level");
-            super.restart(parameters);
-            return;
-        }
-        
-        DynamicTasks.queue("pre-restart", new PreRestartTask());
-
-        log.debug("restart of "+entity()+" appears to have driver and hostname - doing driver-level restart");
-        entity().getDriver().restart();
-        
-        restartChildren(parameters);
-        
-        DynamicTasks.queue("post-restart", new PostRestartTask());
-    }
-
-    private class PreRestartTask implements Runnable {
-        @Override
-        public void run() {
-            preRestartCustom();
-        }
-    }
-
-    private class PostRestartTask implements Runnable {
-        @Override
-        public void run() {
-            postStartCustom();
-            postRestartCustom();
-            ServiceStateLogic.setExpectedState(entity(), Lifecycle.RUNNING);
-        }
-    }
-    
-    @Override
-    protected boolean getDefaultRestartStopsMachine() {
-        if (entity().getDriver() == null) {
-            log.debug("restart of "+entity()+" has no driver - doing machine-level restart");
-            return true;
-        }
-
-        if (Strings.isEmpty(entity().getAttribute(Attributes.HOSTNAME))) {
-            log.debug("restart of "+entity()+" has no hostname - doing machine-level restart");
-            return true;
-        }
-        
-        return false;
-    }
-    
-    @Override
-    protected SoftwareProcessImpl entity() {
-        return (SoftwareProcessImpl) super.entity();
-    }
-    
-    @Override
-    protected Map<String, Object> obtainProvisioningFlags(final MachineProvisioningLocation<?> location) {
-        return entity().obtainProvisioningFlags(location);
-    }
-     
-    @Override
-    protected void preStartCustom(MachineLocation machine) {
-        entity().initDriver(machine);
-
-        // Note: must only apply config-sensors after adding to locations and creating driver; 
-        // otherwise can't do things like acquire free port from location, or allowing driver to set up ports
-        super.preStartCustom(machine);
-        
-        entity().preStart();
-    }
-
-    /** returns how children startables should be handled (reporting none for efficiency if there are no children) */
-    protected ChildStartableMode getChildrenStartableModeEffective() {
-        if (entity().getChildren().isEmpty()) return ChildStartableMode.NONE;
-        ChildStartableMode result = entity().getConfig(SoftwareProcess.CHILDREN_STARTABLE_MODE);
-        if (result!=null) return result;
-        return ChildStartableMode.NONE;
-    }
-
-    @Override
-    protected String startProcessesAtMachine(final Supplier<MachineLocation> machineS) {
-        ChildStartableMode mode = getChildrenStartableModeEffective();
-        TaskAdaptable<?> children = null;
-        if (!mode.isDisabled) {
-            children = StartableMethods.startingChildren(entity(), machineS.get());
-            // submit rather than queue so it runs in parallel
-            // (could also wrap as parallel task with driver.start() -
-            // but only benefit is that child starts show as child task,
-            // rather than bg task, so not worth the code complexity)
-            if (!mode.isLate) Entities.submit(entity(), children);
-        }
-        
-        entity().getDriver().start();
-        String result = "Started with driver "+entity().getDriver();
-        
-        if (!mode.isDisabled) {
-            if (mode.isLate) {
-                DynamicTasks.waitForLast();
-                if (mode.isBackground) {
-                    Entities.submit(entity(), children);
-                } else {
-                    // when running foreground late, there is no harm here in queueing
-                    DynamicTasks.queue(children);
-                }
-            }
-            if (!mode.isBackground) children.asTask().getUnchecked();
-            result += "; children started "+mode;
-        }
-        return result;
-    }
-
-    @Override
-    protected void postStartCustom() {
-        entity().postDriverStart();
-        if (entity().connectedSensors) {
-            // many impls aren't idempotent - though they should be!
-            log.debug("skipping connecting sensors for "+entity()+" in driver-tasks postStartCustom because already connected (e.g. restarting)");
-        } else {
-            log.debug("connecting sensors for "+entity()+" in driver-tasks postStartCustom because already connected (e.g. restarting)");
-            entity().connectSensors();
-        }
-        entity().waitForServiceUp();
-        entity().postStart();
-    }
-    
-    @Override
-    protected void preStopConfirmCustom() {
-        super.preStopConfirmCustom();
-        
-        entity().preStopConfirmCustom();
-    }
-    
-    @Override
-    protected void preStopCustom() {
-        super.preStopCustom();
-        
-        entity().preStop();
-    }
-
-    @Override
-    protected void preRestartCustom() {
-        super.preRestartCustom();
-        
-        entity().preRestart();
-    }
-
-    @Override
-    protected void postRestartCustom() {
-        super.postRestartCustom();
-        
-        entity().postRestart();
-    }
-
-    @Override
-    protected String stopProcessesAtMachine() {
-        String result;
-        
-        ChildStartableMode mode = getChildrenStartableModeEffective();
-        TaskAdaptable<?> children = null;
-        Exception childException = null;
-        
-        if (!mode.isDisabled) {
-            children = StartableMethods.stoppingChildren(entity());
-            
-            if (mode.isBackground || !mode.isLate) Entities.submit(entity(), children);
-            else {
-                DynamicTasks.queue(children);
-                try {
-                    DynamicTasks.waitForLast();
-                } catch (Exception e) {
-                    childException = e;
-                }
-            }
-        }
-        
-        if (entity().getDriver() != null) { 
-            entity().getDriver().stop();
-            result = "Driver stop completed";
-        } else {
-            result = "No driver (nothing to do here)";
-        }
-
-        if (!mode.isDisabled && !mode.isBackground) {
-            try {
-                children.asTask().get();
-            } catch (Exception e) {
-                childException = e;
-                log.debug("Error stopping children; continuing and will rethrow if no other errors", e);
-            }            
-        }
-        
-        if (childException!=null)
-            throw new IllegalStateException(result+"; but error stopping child: "+childException, childException);
-
-        return result;
-    }
-    
-    @Override
-    protected void postStopCustom() {
-        super.postStopCustom();
-        
-        entity().postStop();
-    }
-
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/SoftwareProcessImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/SoftwareProcessImpl.java b/software/base/src/main/java/brooklyn/entity/basic/SoftwareProcessImpl.java
deleted file mode 100644
index bb9717e..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/SoftwareProcessImpl.java
+++ /dev/null
@@ -1,651 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import groovy.time.TimeDuration;
-
-import java.util.Collection;
-import java.util.Map;
-import java.util.Set;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.drivers.DriverDependentEntity;
-import org.apache.brooklyn.api.entity.drivers.EntityDriverManager;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.location.PortRange;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.api.sensor.EnricherSpec;
-import org.apache.brooklyn.api.sensor.SensorEvent;
-import org.apache.brooklyn.api.sensor.SensorEventListener;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.entity.core.AbstractEntity;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle.Transition;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic.ServiceNotUpLogic;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.location.cloud.CloudLocationConfig;
-import org.apache.brooklyn.sensor.enricher.AbstractEnricher;
-import org.apache.brooklyn.sensor.feed.function.FunctionFeed;
-import org.apache.brooklyn.sensor.feed.function.FunctionPollConfig;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.collections.MutableSet;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.flags.TypeCoercions;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.time.CountdownTimer;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-
-import com.google.common.base.Functions;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Sets;
-import com.google.common.reflect.TypeToken;
-
-/**
- * An {@link Entity} representing a piece of software which can be installed, run, and controlled.
- * A single such entity can only run on a single {@link MachineLocation} at a time (you can have multiple on the machine). 
- * It typically takes config keys for suggested versions, filesystem locations to use, and environment variables to set.
- * <p>
- * It exposes sensors for service state (Lifecycle) and status (String), and for host info, log file location.
- */
-public abstract class SoftwareProcessImpl extends AbstractEntity implements SoftwareProcess, DriverDependentEntity {
-    private static final Logger log = LoggerFactory.getLogger(SoftwareProcessImpl.class);
-    
-    private transient SoftwareProcessDriver driver;
-
-    /** @see #connectServiceUpIsRunning() */
-    private volatile FunctionFeed serviceProcessIsRunning;
-
-    protected boolean connectedSensors = false;
-    
-    public SoftwareProcessImpl() {
-        super(MutableMap.of(), null);
-    }
-    public SoftwareProcessImpl(Entity parent) {
-        this(MutableMap.of(), parent);
-    }
-    public SoftwareProcessImpl(Map properties) {
-        this(properties, null);
-    }
-    public SoftwareProcessImpl(Map properties, Entity parent) {
-        super(properties, parent);
-    }
-
-    protected void setProvisioningLocation(MachineProvisioningLocation val) {
-        if (getAttribute(PROVISIONING_LOCATION) != null) throw new IllegalStateException("Cannot change provisioning location: existing="+getAttribute(PROVISIONING_LOCATION)+"; new="+val);
-        setAttribute(PROVISIONING_LOCATION, val);
-    }
-    
-    protected MachineProvisioningLocation getProvisioningLocation() {
-        return getAttribute(PROVISIONING_LOCATION);
-    }
-    
-    @Override
-    public SoftwareProcessDriver getDriver() {
-        return driver;
-    }
-
-    protected SoftwareProcessDriver newDriver(MachineLocation loc){
-        EntityDriverManager entityDriverManager = getManagementContext().getEntityDriverManager();
-        return (SoftwareProcessDriver)entityDriverManager.build(this, loc);
-    }
-
-    protected MachineLocation getMachineOrNull() {
-        return Iterables.get(Iterables.filter(getLocations(), MachineLocation.class), 0, null);
-    }
-
-    @Override
-    public void init() {
-        super.init();
-        getLifecycleEffectorTasks().attachLifecycleEffectors(this);
-    }
-    
-    @Override
-    protected void initEnrichers() {
-        super.initEnrichers();
-        ServiceNotUpLogic.updateNotUpIndicator(this, SERVICE_PROCESS_IS_RUNNING, "No information yet on whether this service is running");
-        // add an indicator above so that if is_running comes through, the map is cleared and an update is guaranteed
-        addEnricher(EnricherSpec.create(UpdatingNotUpFromServiceProcessIsRunning.class).uniqueTag("service-process-is-running-updating-not-up"));
-        addEnricher(EnricherSpec.create(ServiceNotUpDiagnosticsCollector.class).uniqueTag("service-not-up-diagnostics-collector"));
-    }
-    
-    /**
-     * @since 0.8.0
-     */
-    protected static class ServiceNotUpDiagnosticsCollector extends AbstractEnricher implements SensorEventListener<Object> {
-        public ServiceNotUpDiagnosticsCollector() {
-        }
-        
-        @Override
-        public void setEntity(EntityLocal entity) {
-            super.setEntity(entity);
-            if (!(entity instanceof SoftwareProcess)) {
-                throw new IllegalArgumentException("Expected SoftwareProcess, but got entity "+entity);
-            }
-            subscribe(entity, Attributes.SERVICE_UP, this);
-            onUpdated();
-        }
-
-        @Override
-        public void onEvent(SensorEvent<Object> event) {
-            onUpdated();
-        }
-
-        protected void onUpdated() {
-            Boolean up = entity.getAttribute(SERVICE_UP);
-            if (up == null || up) {
-                entity.setAttribute(ServiceStateLogic.SERVICE_NOT_UP_DIAGNOSTICS, ImmutableMap.<String, Object>of());
-            } else {
-                ((SoftwareProcess)entity).populateServiceNotUpDiagnostics();
-            }
-        }
-    }
-    
-    @Override
-    public void populateServiceNotUpDiagnostics() {
-        if (getDriver() == null) {
-            ServiceStateLogic.updateMapSensorEntry(this, ServiceStateLogic.SERVICE_NOT_UP_DIAGNOSTICS, "driver", "No driver");
-            return;
-        }
-
-        Location loc = getDriver().getLocation();
-        if (loc instanceof SshMachineLocation) {
-            if (!((SshMachineLocation)loc).isSshable()) {
-                ServiceStateLogic.updateMapSensorEntry(
-                        this, 
-                        ServiceStateLogic.SERVICE_NOT_UP_DIAGNOSTICS, 
-                        "sshable", 
-                        "The machine for this entity does not appear to be sshable");
-            }
-            return;
-        }
-
-        boolean processIsRunning = getDriver().isRunning();
-        if (!processIsRunning) {
-            ServiceStateLogic.updateMapSensorEntry(
-                    this, 
-                    ServiceStateLogic.SERVICE_NOT_UP_DIAGNOSTICS, 
-                    SERVICE_PROCESS_IS_RUNNING.getName(), 
-                    "The software process for this entity does not appear to be running");
-        }
-    }
-
-    /** subscribes to SERVICE_PROCESS_IS_RUNNING and SERVICE_UP; the latter has no effect if the former is set,
-     * but to support entities which set SERVICE_UP directly we want to make sure that the absence of 
-     * SERVICE_PROCESS_IS_RUNNING does not trigger any not-up indicators */
-    protected static class UpdatingNotUpFromServiceProcessIsRunning extends AbstractEnricher implements SensorEventListener<Object> {
-        public UpdatingNotUpFromServiceProcessIsRunning() {}
-        
-        @Override
-        public void setEntity(EntityLocal entity) {
-            super.setEntity(entity);
-            subscribe(entity, SERVICE_PROCESS_IS_RUNNING, this);
-            subscribe(entity, Attributes.SERVICE_UP, this);
-            onUpdated();
-        }
-
-        @Override
-        public void onEvent(SensorEvent<Object> event) {
-            onUpdated();
-        }
-
-        protected void onUpdated() {
-            Boolean isRunning = entity.getAttribute(SERVICE_PROCESS_IS_RUNNING);
-            if (Boolean.FALSE.equals(isRunning)) {
-                ServiceNotUpLogic.updateNotUpIndicator(entity, SERVICE_PROCESS_IS_RUNNING, "The software process for this entity does not appear to be running");
-                return;
-            }
-            if (Boolean.TRUE.equals(isRunning)) {
-                ServiceNotUpLogic.clearNotUpIndicator(entity, SERVICE_PROCESS_IS_RUNNING);
-                return;
-            }
-            // no info on "isRunning"
-            Boolean isUp = entity.getAttribute(Attributes.SERVICE_UP);
-            if (Boolean.TRUE.equals(isUp)) {
-                // if service explicitly set up, then don't apply our rule
-                ServiceNotUpLogic.clearNotUpIndicator(entity, SERVICE_PROCESS_IS_RUNNING);
-                return;
-            }
-            // service not up, or no info
-            ServiceNotUpLogic.updateNotUpIndicator(entity, SERVICE_PROCESS_IS_RUNNING, "No information on whether this service is running");
-        }
-    }
-    
-    /**
-     * Called before driver.start; guarantees the driver will exist, and locations will have been set.
-     */
-    protected void preStart() {
-    }
-    
-    /**
-     * Called after driver.start(). Default implementation is to wait to confirm the driver 
-     * definitely started the process.
-     */
-    protected void postDriverStart() {
-        waitForEntityStart();
-    }
-
-    /**
-     * For binding to the running app (e.g. connecting sensors to registry). Will be called
-     * on start() and on rebind().
-     * <p>
-     * Implementations should be idempotent (ie tell whether sensors already connected),
-     * though the framework is pretty good about not calling when already connected. 
-     * TODO improve the framework's feed system to detect duplicate additions
-     */
-    protected void connectSensors() {
-        connectedSensors = true;
-    }
-
-    /**
-     * For connecting the {@link #SERVICE_UP} sensor to the value of the {@code getDriver().isRunning()} expression.
-     * <p>
-     * Should be called inside {@link #connectSensors()}.
-     *
-     * @see #disconnectServiceUpIsRunning()
-     */
-    protected void connectServiceUpIsRunning() {
-        serviceProcessIsRunning = FunctionFeed.builder()
-                .entity(this)
-                .period(Duration.FIVE_SECONDS)
-                .poll(new FunctionPollConfig<Boolean, Boolean>(SERVICE_PROCESS_IS_RUNNING)
-                        .suppressDuplicates(true)
-                        .onException(Functions.constant(Boolean.FALSE))
-                        .callable(new Callable<Boolean>() {
-                            public Boolean call() {
-                                return getDriver().isRunning();
-                            }
-                        }))
-                .build();
-    }
-
-    /**
-     * For disconnecting the {@link #SERVICE_UP} feed.
-     * <p>
-     * Should be called from {@link #disconnectSensors()}.
-     *
-     * @see #connectServiceUpIsRunning()
-     */
-    protected void disconnectServiceUpIsRunning() {
-        if (serviceProcessIsRunning != null) serviceProcessIsRunning.stop();
-        // set null so the SERVICE_UP enricher runs (possibly removing it), then remove so everything is removed
-        // TODO race because the is-running check may be mid-task
-        setAttribute(SERVICE_PROCESS_IS_RUNNING, null);
-        removeAttribute(SERVICE_PROCESS_IS_RUNNING);
-    }
-
-    /**
-     * Called after the rest of start has completed (after {@link #connectSensors()} and {@link #waitForServiceUp()})
-     */
-    protected void postStart() {
-    }
-    
-    protected void preStopConfirmCustom() {
-    }
-    
-    protected void preStop() {
-        // note asymmetry that disconnectSensors is done in the entity not the driver
-        // whereas on start the *driver* calls connectSensors, before calling postStart,
-        // ie waiting for the entity truly to be started before calling postStart;
-        // TODO feels like that confusion could be eliminated with a single place for pre/post logic!)
-        log.debug("disconnecting sensors for "+this+" in entity.preStop");
-        disconnectSensors();
-        
-        // Must set the serviceProcessIsRunning explicitly to false - we've disconnected the sensors
-        // so nothing else will.
-        // Otherwise, if restarted, there will be no change to serviceProcessIsRunning, so the
-        // serviceUpIndicators will not change, so serviceUp will not be reset.
-        // TODO Is there a race where disconnectSensors could leave a task of the feeds still running
-        // which could set serviceProcessIsRunning to true again before the task completes and the feed
-        // is fully terminated?
-        setAttribute(SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, false);
-    }
-
-    /**
-     * Called after the rest of stop has completed (after VM deprovisioned, but before state set to STOPPED)
-     */
-    protected void postStop() {
-    }
-
-    /**
-     * Called before driver.restart; guarantees the driver will exist, and locations will have been set.
-     */
-    protected void preRestart() {
-    }
-
-    protected void postRestart() {
-    }
-
-    /**
-     * For disconnecting from the running app. Will be called on stop.
-     */
-    protected void disconnectSensors() {
-        connectedSensors = false;
-    }
-
-    /**
-     * Called after this entity is fully rebound (i.e. it is fully managed).
-     */
-    protected void postRebind() {
-    }
-    
-    protected void callRebindHooks() {
-        Duration configuredMaxDelay = getConfig(MAXIMUM_REBIND_SENSOR_CONNECT_DELAY);
-        if (configuredMaxDelay == null || Duration.ZERO.equals(configuredMaxDelay)) {
-            connectSensors();
-        } else {
-            long delay = (long) (Math.random() * configuredMaxDelay.toMilliseconds());
-            log.debug("Scheduled reconnection of sensors on {} in {}ms", this, delay);
-            Timer timer = new Timer();
-            timer.schedule(new TimerTask() {
-                @Override public void run() {
-                    try {
-                        if (getManagementSupport().isNoLongerManaged()) {
-                            log.debug("Entity {} no longer managed; ignoring scheduled connect sensors on rebind", SoftwareProcessImpl.this);
-                            return;
-                        }
-                        connectSensors();
-                    } catch (Throwable e) {
-                        log.warn("Problem connecting sensors on rebind of "+SoftwareProcessImpl.this, e);
-                        Exceptions.propagateIfFatal(e);
-                    }
-                }
-            }, delay);
-        }
-        // don't wait here - it may be long-running, e.g. if remote entity has died, and we don't want to block rebind waiting or cause it to fail
-        // the service will subsequently show service not up and thus failure
-//        waitForServiceUp();
-    }
-
-    @Override 
-    public void onManagementStarting() {
-        super.onManagementStarting();
-        
-        Lifecycle state = getAttribute(SERVICE_STATE_ACTUAL);
-        if (state == null || state == Lifecycle.CREATED) {
-            // Expect this is a normal start() sequence (i.e. start() will subsequently be called)
-            setAttribute(SERVICE_UP, false);
-            ServiceStateLogic.setExpectedState(this, Lifecycle.CREATED);
-            // force actual to be created because this is expected subsequently
-            setAttribute(SERVICE_STATE_ACTUAL, Lifecycle.CREATED);
-        }
-    }
-    
-    @Override 
-    public void onManagementStarted() {
-        super.onManagementStarted();
-        
-        Lifecycle state = getAttribute(SERVICE_STATE_ACTUAL);
-        if (state != null && state != Lifecycle.CREATED) {
-            postRebind();
-        }
-    }
-    
-    @Override
-    public void rebind() {
-        //SERVICE_STATE_ACTUAL might be ON_FIRE due to a temporary condition (problems map non-empty)
-        //Only if the expected state is ON_FIRE then the entity has permanently failed.
-        Transition expectedState = getAttribute(SERVICE_STATE_EXPECTED);
-        if (expectedState == null || expectedState.getState() != Lifecycle.RUNNING) {
-            log.warn("On rebind of {}, not calling software process rebind hooks because expected state is {}", this, expectedState);
-            return;
-        }
-
-        Lifecycle actualState = getAttribute(SERVICE_STATE_ACTUAL);
-        if (actualState == null || actualState != Lifecycle.RUNNING) {
-            log.warn("Rebinding entity {}, even though actual state is {}. Expected state is {}", new Object[] {this, actualState, expectedState});
-        }
-
-        // e.g. rebinding to a running instance
-        // FIXME For rebind, what to do about things in STARTING or STOPPING state?
-        // FIXME What if location not set?
-        log.info("Rebind {} connecting to pre-running service", this);
-        
-        MachineLocation machine = getMachineOrNull();
-        if (machine != null) {
-            initDriver(machine);
-            driver.rebind();
-            if (log.isDebugEnabled()) log.debug("On rebind of {}, re-created driver {}", this, driver);
-        } else {
-            log.info("On rebind of {}, no MachineLocation found (with locations {}) so not generating driver",
-                    this, getLocations());
-        }
-        
-        callRebindHooks();
-    }
-    
-    public void waitForServiceUp() {
-        Duration timeout = getConfig(BrooklynConfigKeys.START_TIMEOUT);
-        waitForServiceUp(timeout);
-    }
-    public void waitForServiceUp(Duration duration) {
-        Entities.waitForServiceUp(this, duration);
-    }
-    public void waitForServiceUp(TimeDuration duration) {
-        waitForServiceUp(duration.toMilliseconds(), TimeUnit.MILLISECONDS);
-    }
-    public void waitForServiceUp(long duration, TimeUnit units) {
-        Entities.waitForServiceUp(this, Duration.of(duration, units));
-    }
-
-    protected Map<String,Object> obtainProvisioningFlags(MachineProvisioningLocation location) {
-        ConfigBag result = ConfigBag.newInstance(location.getProvisioningFlags(ImmutableList.of(getClass().getName())));
-        result.putAll(getConfig(PROVISIONING_PROPERTIES));
-        if (result.get(CloudLocationConfig.INBOUND_PORTS) == null) {
-            Collection<Integer> ports = getRequiredOpenPorts();
-            Object requiredPorts = result.get(CloudLocationConfig.ADDITIONAL_INBOUND_PORTS);
-            if (requiredPorts instanceof Integer) {
-                ports.add((Integer) requiredPorts);
-            } else if (requiredPorts instanceof Iterable) {
-                for (Object o : (Iterable<?>) requiredPorts) {
-                    if (o instanceof Integer) ports.add((Integer) o);
-                }
-            }
-            if (ports != null && ports.size() > 0) result.put(CloudLocationConfig.INBOUND_PORTS, ports);
-        }
-        result.put(LocationConfigKeys.CALLER_CONTEXT, this);
-        return result.getAllConfigMutable();
-    }
-
-    /** returns the ports that this entity wants to use;
-     * default implementation returns {@link SoftwareProcess#REQUIRED_OPEN_LOGIN_PORTS} plus first value 
-     * for each {@link org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey} config key {@link PortRange}
-     * plus any ports defined with a config keys ending in {@code .port}.
-     */
-    protected Collection<Integer> getRequiredOpenPorts() {
-        Set<Integer> ports = MutableSet.copyOf(getConfig(REQUIRED_OPEN_LOGIN_PORTS));
-        Map<ConfigKey<?>, ?> allConfig = config().getBag().getAllConfigAsConfigKeyMap();
-        Set<ConfigKey<?>> configKeys = Sets.newHashSet(allConfig.keySet());
-        configKeys.addAll(getEntityType().getConfigKeys());
-
-        /* TODO: This won't work if there's a port collision, which will cause the corresponding port attribute
-           to be incremented until a free port is found. In that case the entity will use the free port, but the
-           firewall will open the initial port instead. Mostly a problem for SameServerEntity, localhost location.
-         */
-        for (ConfigKey<?> k: configKeys) {
-            Object value;
-            if (PortRange.class.isAssignableFrom(k.getType()) || k.getName().matches(".*\\.port")) {
-                value = config().get(k);
-            } else {
-                // config().get() will cause this to block until all config has been resolved
-                // using config().getRaw(k) means that we won't be able to use e.g. 'http.port: $brooklyn:component("x").attributeWhenReady("foo")'
-                // but that's unlikely to be used
-                Maybe<Object> maybeValue = config().getRaw(k);
-                value = maybeValue.isPresent() ? maybeValue.get() : null;
-            }
-
-            Maybe<PortRange> maybePortRange = TypeCoercions.tryCoerce(value, new TypeToken<PortRange>() {});
-
-            if (maybePortRange.isPresentAndNonNull()) {
-                PortRange p = maybePortRange.get();
-                if (p != null && !p.isEmpty()) ports.add(p.iterator().next());
-            }
-        }        
-        
-        log.debug("getRequiredOpenPorts detected default {} for {}", ports, this);
-        return ports;
-    }
-
-    protected void initDriver(MachineLocation machine) {
-        SoftwareProcessDriver newDriver = doInitDriver(machine);
-        if (newDriver == null) {
-            throw new UnsupportedOperationException("cannot start "+this+" on "+machine+": no driver available");
-        }
-        driver = newDriver;
-    }
-
-    /**
-     * Creates the driver (if does not already exist or needs replaced for some reason). Returns either the existing driver
-     * or a new driver. Must not return null.
-     */
-    protected SoftwareProcessDriver doInitDriver(MachineLocation machine) {
-        if (driver!=null) {
-            if ((driver instanceof AbstractSoftwareProcessDriver) && machine.equals(((AbstractSoftwareProcessDriver)driver).getLocation())) {
-                return driver; //just reuse
-            } else {
-                log.warn("driver/location change is untested for {} at {}; changing driver and continuing", this, machine);
-                return newDriver(machine);
-            }
-        } else {
-            return newDriver(machine);
-        }
-    }
-    
-    // TODO Find a better way to detect early death of process.
-    public void waitForEntityStart() {
-        if (log.isDebugEnabled()) log.debug("waiting to ensure {} doesn't abort prematurely", this);
-        Duration startTimeout = getConfig(START_TIMEOUT);
-        CountdownTimer timer = startTimeout.countdownTimer();
-        boolean isRunningResult = false;
-        long delay = 100;
-        Exception firstFailure = null;
-        while (!isRunningResult && !timer.isExpired()) {
-            Time.sleep(delay);
-            try {
-                isRunningResult = driver.isRunning();
-                if (log.isDebugEnabled()) log.debug("checked {}, 'is running' returned: {}", this, isRunningResult);
-            } catch (Exception  e) {
-                Exceptions.propagateIfFatal(e);
-
-                isRunningResult = false;
-                if (driver != null) {
-                    String msg = "checked " + this + ", 'is running' threw an exception; logging subsequent exceptions at debug level";
-                    if (firstFailure == null) {
-                        log.error(msg, e);
-                    } else {
-                        log.debug(msg, e);
-                    }
-                } else {
-                    // provide extra context info, as we're seeing this happen in strange circumstances
-                    log.error(this+" concurrent start and shutdown detected", e);
-                }
-                if (firstFailure == null) {
-                    firstFailure = e;
-                }
-            }
-            // slow exponential delay -- 1.1^N means after 40 tries and 50s elapsed, it reaches the max of 5s intervals
-            // TODO use Repeater 
-            delay = Math.min(delay*11/10, 5000);
-        }
-        if (!isRunningResult) {
-            String msg = "Software process entity "+this+" did not pass is-running check within "+
-                    "the required "+startTimeout+" limit ("+timer.getDurationElapsed().toStringRounded()+" elapsed)";
-            if (firstFailure != null) {
-                msg += "; check failed at least once with exception: " + firstFailure.getMessage() + ", see logs for details";
-            }
-            log.warn(msg+" (throwing)");
-            ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
-            throw new IllegalStateException(msg, firstFailure);
-        }
-    }
-
-    /**
-     * If custom behaviour is required by sub-classes, consider overriding {@link #preStart()} or {@link #postStart()})}.
-     * Also consider adding additional work via tasks, executed using {@link DynamicTasks#queue(String, Callable)}.
-     */
-    @Override
-    public final void start(final Collection<? extends Location> locations) {
-        if (DynamicTasks.getTaskQueuingContext() != null) {
-            getLifecycleEffectorTasks().start(locations);
-        } else {
-            Task<?> task = Tasks.builder().name("start (sequential)").body(new Runnable() { public void run() { getLifecycleEffectorTasks().start(locations); } }).build();
-            Entities.submit(this, task).getUnchecked();
-        }
-    }
-
-    /**
-     * If custom behaviour is required by sub-classes, consider overriding  {@link #preStop()} or {@link #postStop()}.
-     * Also consider adding additional work via tasks, executed using {@link DynamicTasks#queue(String, Callable)}.
-     */
-    @Override
-    public final void stop() {
-        // TODO There is a race where we set SERVICE_UP=false while sensor-adapter threads may still be polling.
-        // The other thread might reset SERVICE_UP to true immediately after we set it to false here.
-        // Deactivating adapters before setting SERVICE_UP reduces the race, and it is reduced further by setting
-        // SERVICE_UP to false at the end of stop as well.
-        
-        // Perhaps we should wait until all feeds have completed here, 
-        // or do a SERVICE_STATE check before setting SERVICE_UP to true in a feed (?).
-
-        if (DynamicTasks.getTaskQueuingContext() != null) {
-            getLifecycleEffectorTasks().stop(ConfigBag.EMPTY);
-        } else {
-            Task<?> task = Tasks.builder().name("stop").body(new Runnable() { public void run() { getLifecycleEffectorTasks().stop(ConfigBag.EMPTY); } }).build();
-            Entities.submit(this, task).getUnchecked();
-        }
-    }
-
-    /**
-     * If custom behaviour is required by sub-classes, consider overriding {@link #preRestart()} or {@link #postRestart()}.
-     * Also consider adding additional work via tasks, executed using {@link DynamicTasks#queue(String, Callable)}.
-     */
-    @Override
-    public final void restart() {
-        if (DynamicTasks.getTaskQueuingContext() != null) {
-            getLifecycleEffectorTasks().restart(ConfigBag.EMPTY);
-        } else {
-            Task<?> task = Tasks.builder().name("restart").body(new Runnable() { public void run() { getLifecycleEffectorTasks().restart(ConfigBag.EMPTY); } }).build();
-            Entities.submit(this, task).getUnchecked();
-        }
-    }
-    
-    protected SoftwareProcessDriverLifecycleEffectorTasks getLifecycleEffectorTasks() {
-        return getConfig(LIFECYCLE_EFFECTOR_TASKS);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcess.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcess.java b/software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcess.java
deleted file mode 100644
index 4049e0f..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcess.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import org.apache.brooklyn.api.catalog.Catalog;
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-
-/** 
- * A {@link SoftwareProcess} entity that runs commands from an archive.
- * <p>
- * Downloads and unpacks the archive indicated (optionally) then runs the management commands (scripts) indicated
- * (relative to the root of the archive if supplied, otherwise in a tmp working dir) to manage. Uses config keys
- * to identify the files or commands to use.
- * <p>
- * In the simplest mode, simply provide either:
- * <ul>
- * <li> an archive in {@link #DOWNLOAD_URL} containing a <code>./start.sh</code>
- * <li> a start command to invoke in {@link #LAUNCH_COMMAND}
- * </ul>
- * The only constraint is that the start command must write the PID into the file pointed to by the injected environment
- * variable {@code PID_FILE} unless one of the options below is supported.
- * <p>
- * The start command can be a complex bash command, downloading and unpacking files, and handling the {@code PID_FILE} requirement.
- * For example {@code export MY_PID_FILE=$PID_FILE ; ./my_start.sh} or {@code nohup ./start.sh & ; echo $! > $PID_FILE ; sleep 5}.
- * </pre>
- * You can supply both {@link #DOWNLOAD_URL} and {@link #LAUNCH_COMMAND} configuration as well..
- * <p>
- * In addition, you can supply an {@link #INSTALL_COMMAND} and / or a {@link #CUSTOMIZE_COMMAND} to reduce the complexity
- * of the {@link #LAUNCH_COMMAND}, and to avoid repeating actions that are unnecessary in subsequent launches.
- * <p>
- * By default the PID is used to stop the process using {@code kill} followed by {@code kill -9} if needed and restart
- * is implemented by stopping the process and then running {@link VanillaSoftwareProcessSshDriver#launch()}, but it is
- * possible to override this behavior through config keys:
- * <ul>
- * <li> A custom {@link #CHECK_RUNNING_COMMAND}
- * <li> A custom {@link #STOP_COMMAND}
- * <li> A different {@link SoftwareProcess#PID_FILE} to use
- * <li>
- */
-@Catalog(name="Vanilla Software Process", description="A software process configured with scripts, e.g. for launch, check-running and stop")
-@ImplementedBy(VanillaSoftwareProcessImpl.class)
-public interface VanillaSoftwareProcess extends AbstractVanillaProcess {
-    ConfigKey<String> LAUNCH_COMMAND = ConfigKeys.newConfigKeyWithDefault(AbstractVanillaProcess.LAUNCH_COMMAND, "./start.sh");
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcessDriver.java b/software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcessDriver.java
deleted file mode 100644
index aa98086..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcessDriver.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-public interface VanillaSoftwareProcessDriver extends SoftwareProcessDriver {
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcessImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcessImpl.java b/software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcessImpl.java
deleted file mode 100644
index e7a9f70..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcessImpl.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-
-public class VanillaSoftwareProcessImpl extends SoftwareProcessImpl implements VanillaSoftwareProcess {
-    @Override
-    public Class<?> getDriverInterface() {
-        return VanillaSoftwareProcessDriver.class;
-    }
-    @Override
-    protected void connectSensors() {
-        super.connectSensors();
-        connectServiceUpIsRunning();
-    }
-    @Override
-    protected void disconnectSensors() {
-        disconnectServiceUpIsRunning();
-        super.disconnectSensors();
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcessSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcessSshDriver.java b/software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcessSshDriver.java
deleted file mode 100644
index 4a85565..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcessSshDriver.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.drivers.downloads.DownloadResolver;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.entity.core.Entities;
-
-import brooklyn.entity.basic.lifecycle.ScriptHelper;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.file.ArchiveUtils;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.ssh.BashCommands;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.apache.brooklyn.util.text.Strings;
-
-public class VanillaSoftwareProcessSshDriver extends AbstractSoftwareProcessSshDriver implements VanillaSoftwareProcessDriver {
-
-    public VanillaSoftwareProcessSshDriver(EntityLocal entity, SshMachineLocation machine) {
-        super(entity, machine);
-    }
-
-    String downloadedFilename = null;
-
-    /** needed because the download url might be different! */
-    @Override
-    protected String getInstallLabelExtraSalt() {
-        Maybe<Object> url = getEntity().getConfigRaw(SoftwareProcess.DOWNLOAD_URL, true);
-        if (url.isAbsent()) return null;
-        // TODO a user-friendly hash would be nice, but tricky since we don't want it to be too long or contain path chars
-        return Identifiers.makeIdFromHash( url.get().hashCode() );
-    }
-    
-    @Override
-    public void install() {
-        Maybe<Object> url = getEntity().getConfigRaw(SoftwareProcess.DOWNLOAD_URL, true);
-        if (url.isPresentAndNonNull()) {
-            DownloadResolver resolver = Entities.newDownloader(this);
-            List<String> urls = resolver.getTargets();
-            downloadedFilename = resolver.getFilename();
-
-            List<String> commands = new LinkedList<String>();
-            commands.addAll(BashCommands.commandsToDownloadUrlsAs(urls, downloadedFilename));
-            commands.addAll(ArchiveUtils.installCommands(downloadedFilename));
-
-            int result = newScript(INSTALLING)
-                    .failOnNonZeroResultCode(false)
-                    .body.append(commands)
-                    .execute();
-            
-            if (result!=0) {
-                // could not install at remote machine; try resolving URL here and copying across
-                for (String urlI: urls) {
-                    result = ArchiveUtils.install(getMachine(), urlI, Urls.mergePaths(getInstallDir(), downloadedFilename));
-                    if (result==0) 
-                        break;
-                }
-                if (result != 0) 
-                    throw new IllegalStateException("Error installing archive: " + downloadedFilename);
-            }
-        }
-        
-        String installCommand = getEntity().getConfig(VanillaSoftwareProcess.INSTALL_COMMAND);
-        
-        if (Strings.isNonBlank(installCommand)) {
-            newScript(INSTALLING)
-                .failOnNonZeroResultCode()
-                .environmentVariablesReset(getShellEnvironment())
-                .body.append(installCommand)
-                .execute();
-        }
-    }
-
-    @Override
-    public void customize() {
-        if (downloadedFilename != null) {
-            newScript(CUSTOMIZING)
-                    .failOnNonZeroResultCode()
-                    // don't set vars yet -- it resolves dependencies (e.g. DB) which we don't want until we start
-                    .environmentVariablesReset()
-                    .body.append(ArchiveUtils.extractCommands(downloadedFilename, getInstallDir()))
-                    .execute();
-        }
-        
-        String customizeCommand = getEntity().getConfig(VanillaSoftwareProcess.CUSTOMIZE_COMMAND);
-        
-        if (Strings.isNonBlank(customizeCommand)) {
-            newScript(CUSTOMIZING)
-                .failOnNonZeroResultCode()
-                .body.append(customizeCommand)
-                .execute();
-        }
-    }
-
-    @Override
-    public Map<String, String> getShellEnvironment() {
-        return MutableMap.copyOf(super.getShellEnvironment()).add("PID_FILE", getPidFile());
-    }
-
-    public String getPidFile() {
-        // TODO see note in VanillaSoftwareProcess about PID_FILE as a config key
-        // if (getEntity().getConfigRaw(PID_FILE, includeInherited)) ...
-        return Os.mergePathsUnix(getRunDir(), PID_FILENAME);
-    }
-
-    @Override
-    public void launch() {
-        newScript(LAUNCHING)
-            .failOnNonZeroResultCode()
-            .body.append(getEntity().getConfig(VanillaSoftwareProcess.LAUNCH_COMMAND))
-            .execute();
-    }
-
-    @Override
-    public boolean isRunning() {
-        String customCommand = getEntity().getConfig(VanillaSoftwareProcess.CHECK_RUNNING_COMMAND);
-        ScriptHelper script = null;
-        if (customCommand == null) {
-            script = newScript(MutableMap.of(USE_PID_FILE, getPidFile()), CHECK_RUNNING);
-        } else {
-            // TODO: template substitutions?
-            script = newScript(CHECK_RUNNING).body.append(customCommand);
-        }
-        return script.execute() == 0;
-    }
-
-    @Override
-    public void stop() {
-        String customCommand = getEntity().getConfig(VanillaSoftwareProcess.STOP_COMMAND);
-        ScriptHelper script = null;
-        if (customCommand == null) {
-            script = newScript(MutableMap.of(USE_PID_FILE, getPidFile()), STOPPING);
-        } else {
-            // TODO: template substitutions?
-            script = newScript(STOPPING).body.append(customCommand);
-        }
-        script.execute();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/VanillaWindowsProcess.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/VanillaWindowsProcess.java b/software/base/src/main/java/brooklyn/entity/basic/VanillaWindowsProcess.java
deleted file mode 100644
index 3fce37f..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/VanillaWindowsProcess.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import java.util.Collection;
-
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.util.time.Duration;
-
-import com.google.common.collect.ImmutableSet;
-
-@ImplementedBy(VanillaWindowsProcessImpl.class)
-public interface VanillaWindowsProcess extends AbstractVanillaProcess {
-    // 3389 is RDP; 5985 is WinRM (3389 isn't used by Brooklyn, but useful for the end-user subsequently)
-    ConfigKey<Collection<Integer>> REQUIRED_OPEN_LOGIN_PORTS = ConfigKeys.newConfigKeyWithDefault(
-            SoftwareProcess.REQUIRED_OPEN_LOGIN_PORTS,
-            ImmutableSet.of(5985, 3389));
-    ConfigKey<String> PRE_INSTALL_POWERSHELL_COMMAND = ConfigKeys.newStringConfigKey("pre.install.powershell.command",
-            "powershell command to run during the pre-install phase");
-    ConfigKey<Boolean> PRE_INSTALL_REBOOT_REQUIRED = ConfigKeys.newBooleanConfigKey("pre.install.reboot.required",
-            "indicates that a reboot should be performed after the pre-install command is run", false);
-    ConfigKey<Boolean> INSTALL_REBOOT_REQUIRED = ConfigKeys.newBooleanConfigKey("install.reboot.required",
-            "indicates that a reboot should be performed after the install command is run", false);
-    ConfigKey<Boolean> CUSTOMIZE_REBOOT_REQUIRED = ConfigKeys.newBooleanConfigKey("customize.reboot.required",
-            "indicates that a reboot should be performed after the customize command is run", false);
-    ConfigKey<String> LAUNCH_POWERSHELL_COMMAND = ConfigKeys.newStringConfigKey("launch.powershell.command",
-            "command to run to launch the process");
-    ConfigKey<String> CHECK_RUNNING_POWERSHELL_COMMAND = ConfigKeys.newStringConfigKey("checkRunning.powershell.command",
-            "command to determine whether the process is running");
-    ConfigKey<String> STOP_POWERSHELL_COMMAND = ConfigKeys.newStringConfigKey("stop.powershell.command",
-            "command to run to stop the process");
-    ConfigKey<String> CUSTOMIZE_POWERSHELL_COMMAND = ConfigKeys.newStringConfigKey("customize.powershell.command",
-            "powershell command to run during the customization phase");
-    ConfigKey<String> INSTALL_POWERSHELL_COMMAND = ConfigKeys.newStringConfigKey("install.powershell.command",
-            "powershell command to run during the install phase");
-    ConfigKey<Duration> REBOOT_BEGUN_TIMEOUT = ConfigKeys.newDurationConfigKey("reboot.begun.timeout",
-            "duration to wait whilst waiting for a machine to begin rebooting, and thus become unavailable", Duration.TWO_MINUTES);
-    // TODO If automatic updates are enabled and there are updates waiting to be installed, thirty minutes may not be sufficient...
-    ConfigKey<Duration> REBOOT_COMPLETED_TIMEOUT = ConfigKeys.newDurationConfigKey("reboot.completed.timeout",
-            "duration to wait whilst waiting for a machine to finish rebooting, and thus to become available again", Duration.minutes(30));
-    
-    AttributeSensor<Integer> RDP_PORT = Sensors.newIntegerSensor("rdpPort");
-    AttributeSensor<Integer> WINRM_PORT = Sensors.newIntegerSensor("winrmPort");
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/VanillaWindowsProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/VanillaWindowsProcessDriver.java b/software/base/src/main/java/brooklyn/entity/basic/VanillaWindowsProcessDriver.java
deleted file mode 100644
index 7e9fd8c..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/VanillaWindowsProcessDriver.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-public interface VanillaWindowsProcessDriver extends SoftwareProcessDriver {
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/VanillaWindowsProcessImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/VanillaWindowsProcessImpl.java b/software/base/src/main/java/brooklyn/entity/basic/VanillaWindowsProcessImpl.java
deleted file mode 100644
index aaa6641..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/VanillaWindowsProcessImpl.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-
-public class VanillaWindowsProcessImpl extends SoftwareProcessImpl implements VanillaWindowsProcess {
-    @Override
-    public Class getDriverInterface() {
-        return VanillaWindowsProcessDriver.class;
-    }
-
-    @Override
-    protected void preStart() {
-        super.preStart();
-        setAttribute(RDP_PORT, 3389);
-        setAttribute(WINRM_PORT, 5985);
-    }
-    
-    @Override
-    protected void connectSensors() {
-        super.connectSensors();
-        connectServiceUpIsRunning();
-    }
-
-    @Override
-    protected void disconnectSensors() {
-        disconnectServiceUpIsRunning();
-        super.disconnectSensors();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/VanillaWindowsProcessWinRmDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/VanillaWindowsProcessWinRmDriver.java b/software/base/src/main/java/brooklyn/entity/basic/VanillaWindowsProcessWinRmDriver.java
deleted file mode 100644
index 2c952b0..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/VanillaWindowsProcessWinRmDriver.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.location.basic.WinRmMachineLocation;
-import org.apache.brooklyn.util.net.UserAndHostAndPort;
-
-public class VanillaWindowsProcessWinRmDriver extends AbstractSoftwareProcessWinRmDriver implements VanillaWindowsProcessDriver {
-
-    public VanillaWindowsProcessWinRmDriver(EntityLocal entity, WinRmMachineLocation location) {
-        super(entity, location);
-    }
-
-    @Override
-    public void start() {
-        WinRmMachineLocation machine = (WinRmMachineLocation) location;
-        UserAndHostAndPort winrmAddress = UserAndHostAndPort.fromParts(machine.getUser(), machine.getAddress().getHostName(), machine.config().get(WinRmMachineLocation.WINRM_PORT));
-        getEntity().setAttribute(Attributes.WINRM_ADDRESS, winrmAddress);
-
-        super.start();
-    }
-    
-    @Override
-    public void preInstall() {
-        super.preInstall();
-        executeCommand(VanillaWindowsProcess.PRE_INSTALL_COMMAND, VanillaWindowsProcess.PRE_INSTALL_POWERSHELL_COMMAND, true);
-        if (entity.getConfig(VanillaWindowsProcess.PRE_INSTALL_REBOOT_REQUIRED)) {
-            rebootAndWait();
-        }
-    }
-
-    @Override
-    public void install() {
-        // TODO: Follow install path of VanillaSoftwareProcessSshDriver
-        executeCommand(VanillaWindowsProcess.INSTALL_COMMAND, VanillaWindowsProcess.INSTALL_POWERSHELL_COMMAND, true);
-        if (entity.getConfig(VanillaWindowsProcess.INSTALL_REBOOT_REQUIRED)) {
-            rebootAndWait();
-        }
-    }
-
-    @Override
-    public void customize() {
-        // TODO: Follow customize path of VanillaSoftwareProcessSshDriver
-        executeCommand(VanillaWindowsProcess.CUSTOMIZE_COMMAND, VanillaWindowsProcess.CUSTOMIZE_POWERSHELL_COMMAND, true);
-        if (entity.getConfig(VanillaWindowsProcess.CUSTOMIZE_REBOOT_REQUIRED)) {
-            rebootAndWait();
-        }
-    }
-
-    @Override
-    public void launch() {
-        executeCommand(VanillaWindowsProcess.LAUNCH_COMMAND, VanillaWindowsProcess.LAUNCH_POWERSHELL_COMMAND, true);
-    }
-
-    @Override
-    public boolean isRunning() {
-        return executeCommand(VanillaWindowsProcess.CHECK_RUNNING_COMMAND,
-                VanillaWindowsProcess.CHECK_RUNNING_POWERSHELL_COMMAND, false).getStatusCode() == 0;
-    }
-
-    @Override
-    public void stop() {
-        executeCommand(VanillaWindowsProcess.STOP_COMMAND, VanillaWindowsProcess.STOP_POWERSHELL_COMMAND, true);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/lifecycle/NaiveScriptRunner.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/lifecycle/NaiveScriptRunner.java b/software/base/src/main/java/brooklyn/entity/basic/lifecycle/NaiveScriptRunner.java
deleted file mode 100644
index 1e5e901..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/lifecycle/NaiveScriptRunner.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic.lifecycle;
-
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.util.core.task.ssh.SshTasks;
-
-/** Marks something which can run scripts. Called "Naive" because it hides too much of the complexity,
- * about script execution and other ssh-related tasks (put, etc). The {@link SshTasks} approach seems better.
- * <p> 
- * Not gone so far as deprecating (yet, in 0.6.0) although we might.  Feedback welcome. 
- * @since 0.6.0 */
-public interface NaiveScriptRunner {
-
-    /** Runs a script and returns the result code */
-    int execute(List<String> script, String summaryForLogging);
-
-    /** Runs a script and returns the result code, supporting flags including:
-     *  out, err as output/error streams;
-     *  logPrefix, prefix string to put in log output;
-     *  env, map of environment vars to pass to shell environment */
-    @SuppressWarnings("rawtypes")
-    int execute(Map flags, List<String> script, String summaryForLogging);
-
-}


[39/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/TomcatAutoScalerPolicyTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/TomcatAutoScalerPolicyTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/TomcatAutoScalerPolicyTest.java
index d58bf73..9a2791a 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/TomcatAutoScalerPolicyTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/TomcatAutoScalerPolicyTest.java
@@ -36,7 +36,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.policy.autoscaling.AutoScalerPolicy;
 
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/WebAppConcurrentDeployTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/WebAppConcurrentDeployTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/WebAppConcurrentDeployTest.java
index 8a0dd08..474133e 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/WebAppConcurrentDeployTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/WebAppConcurrentDeployTest.java
@@ -27,7 +27,7 @@ import org.apache.http.client.HttpClient;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.api.location.LocationSpec;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/WebAppLiveIntegrationTest.groovy
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/WebAppLiveIntegrationTest.groovy b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/WebAppLiveIntegrationTest.groovy
index 01a17e7..2b6c2c9 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/WebAppLiveIntegrationTest.groovy
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/WebAppLiveIntegrationTest.groovy
@@ -27,6 +27,7 @@ import org.apache.brooklyn.api.location.Location
 import org.apache.brooklyn.core.internal.BrooklynProperties
 import org.apache.brooklyn.core.test.entity.TestApplicationImpl
 import org.apache.brooklyn.entity.core.Entities
+import org.apache.brooklyn.entity.software.base.SoftwareProcess
 import org.apache.brooklyn.entity.trait.Startable
 import org.apache.brooklyn.entity.webapp.jboss.JBoss6Server
 import org.apache.brooklyn.entity.webapp.jboss.JBoss6ServerImpl
@@ -34,7 +35,7 @@ import org.apache.brooklyn.entity.webapp.jboss.JBoss7Server
 import org.apache.brooklyn.entity.webapp.jboss.JBoss7ServerImpl
 import org.apache.brooklyn.entity.webapp.tomcat.TomcatServer
 import org.apache.brooklyn.entity.webapp.tomcat.TomcatServerImpl
-import org.apache.brooklyn.location.basic.BasicLocationRegistry
+import org.apache.brooklyn.location.core.BasicLocationRegistry
 import org.apache.brooklyn.test.TestUtils
 import org.apache.brooklyn.util.internal.TimeExtras
 import org.slf4j.Logger
@@ -44,8 +45,6 @@ import org.testng.annotations.BeforeMethod
 import org.testng.annotations.DataProvider
 import org.testng.annotations.Test
 
-import brooklyn.entity.basic.SoftwareProcess
-
 /**
  * This tests that we can run jboss entity on AWS.
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/ControlledDynamicWebAppClusterRebindIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/ControlledDynamicWebAppClusterRebindIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/ControlledDynamicWebAppClusterRebindIntegrationTest.java
index 5ce5f84..c8be35c 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/ControlledDynamicWebAppClusterRebindIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/ControlledDynamicWebAppClusterRebindIntegrationTest.java
@@ -47,7 +47,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/DynamicWebAppClusterRebindIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/DynamicWebAppClusterRebindIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/DynamicWebAppClusterRebindIntegrationTest.java
index 7ee8bcd..20a91b4 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/DynamicWebAppClusterRebindIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/DynamicWebAppClusterRebindIntegrationTest.java
@@ -44,7 +44,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerNonInheritingIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerNonInheritingIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerNonInheritingIntegrationTest.java
index f47a38b..1bb29e9 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerNonInheritingIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6ServerNonInheritingIntegrationTest.java
@@ -29,7 +29,7 @@ import org.apache.brooklyn.test.HttpTestUtils;
 import org.apache.brooklyn.test.TestResourceUnavailableException;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerNonInheritingIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerNonInheritingIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerNonInheritingIntegrationTest.java
index e01f3e0..2dd00c7 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerNonInheritingIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerNonInheritingIntegrationTest.java
@@ -27,7 +27,7 @@ import java.net.URI;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
 import org.apache.brooklyn.entity.core.Entities;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerRebindingIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerRebindingIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerRebindingIntegrationTest.java
index 58dc04d..830c7b9 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerRebindingIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7ServerRebindingIntegrationTest.java
@@ -39,7 +39,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBossServersMultiVersionWebAppFixtureIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBossServersMultiVersionWebAppFixtureIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBossServersMultiVersionWebAppFixtureIntegrationTest.java
index bda60b0..cd3ce60 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBossServersMultiVersionWebAppFixtureIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jboss/JBossServersMultiVersionWebAppFixtureIntegrationTest.java
@@ -25,7 +25,7 @@ import org.apache.brooklyn.entity.webapp.AbstractWebAppFixtureIntegrationTest;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcess;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 
 public class JBossServersMultiVersionWebAppFixtureIntegrationTest extends AbstractWebAppFixtureIntegrationTest {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jetty/JettyWebAppFixtureIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jetty/JettyWebAppFixtureIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jetty/JettyWebAppFixtureIntegrationTest.java
index 38f8eda..b7a1fe5 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jetty/JettyWebAppFixtureIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/jetty/JettyWebAppFixtureIntegrationTest.java
@@ -25,7 +25,7 @@ import org.apache.brooklyn.entity.webapp.AbstractWebAppFixtureIntegrationTest;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcess;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 
 public class JettyWebAppFixtureIntegrationTest extends AbstractWebAppFixtureIntegrationTest {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppFixtureIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppFixtureIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppFixtureIntegrationTest.java
index 898472f..1e21c09 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppFixtureIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppFixtureIntegrationTest.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.webapp.nodejs;
 
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSimpleIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSimpleIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSimpleIntegrationTest.java
index 91e2ec8..1373b93 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSimpleIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSimpleIntegrationTest.java
@@ -30,8 +30,8 @@ import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
 import org.jclouds.util.Throwables2;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.util.net.Networking;
 
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerWebAppFixtureIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerWebAppFixtureIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerWebAppFixtureIntegrationTest.java
index c6af8c0..f9d4ac1 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerWebAppFixtureIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat8ServerWebAppFixtureIntegrationTest.java
@@ -33,7 +33,7 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerDisableRetrieveUsageMetricsIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerDisableRetrieveUsageMetricsIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerDisableRetrieveUsageMetricsIntegrationTest.java
index 4d17684..76b3d71 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerDisableRetrieveUsageMetricsIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerDisableRetrieveUsageMetricsIntegrationTest.java
@@ -27,7 +27,7 @@ import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerWebAppFixtureIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerWebAppFixtureIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerWebAppFixtureIntegrationTest.java
index 43b3143..84e975f 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerWebAppFixtureIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServerWebAppFixtureIntegrationTest.java
@@ -42,7 +42,7 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Lists;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/ByonLocationsYamlTest.java
----------------------------------------------------------------------
diff --git a/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/ByonLocationsYamlTest.java b/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/ByonLocationsYamlTest.java
index 431fec1..edb774f 100644
--- a/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/ByonLocationsYamlTest.java
+++ b/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/ByonLocationsYamlTest.java
@@ -43,12 +43,12 @@ import com.google.common.collect.Iterables;
 import com.google.common.net.HostAndPort;
 
 import org.apache.brooklyn.location.access.PortForwardManager;
-import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.LocationPredicates;
-import org.apache.brooklyn.location.basic.Machines;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.location.basic.WinRmMachineLocation;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
 import org.apache.brooklyn.location.cloud.CloudLocationConfig;
+import org.apache.brooklyn.location.core.LocationPredicates;
+import org.apache.brooklyn.location.core.Machines;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.location.winrm.WinRmMachineLocation;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.util.net.UserAndHostAndPort;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptySoftwareProcessYamlTest.java
----------------------------------------------------------------------
diff --git a/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptySoftwareProcessYamlTest.java b/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptySoftwareProcessYamlTest.java
index 19ac3a2..f7b6daa 100644
--- a/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptySoftwareProcessYamlTest.java
+++ b/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptySoftwareProcessYamlTest.java
@@ -29,7 +29,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.Jsonya;
 
 @Test

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/LocationsYamlTest.java
----------------------------------------------------------------------
diff --git a/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/LocationsYamlTest.java b/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/LocationsYamlTest.java
index ef47d59..7c609b2 100644
--- a/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/LocationsYamlTest.java
+++ b/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/LocationsYamlTest.java
@@ -32,10 +32,10 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.MultiLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.core.MultiLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.text.Strings;
 
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/catalog/CatalogYamlLocationTest.java
----------------------------------------------------------------------
diff --git a/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/catalog/CatalogYamlLocationTest.java b/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/catalog/CatalogYamlLocationTest.java
index 9090075..2a82857 100644
--- a/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/catalog/CatalogYamlLocationTest.java
+++ b/usage/camp/src/test/java/org/apache/brooklyn/camp/brooklyn/catalog/CatalogYamlLocationTest.java
@@ -36,7 +36,7 @@ import org.apache.brooklyn.camp.brooklyn.AbstractYamlTest;
 import org.apache.brooklyn.core.catalog.CatalogPredicates;
 import org.apache.brooklyn.core.config.BasicConfigKey;
 import org.apache.brooklyn.core.mgmt.osgi.OsgiStandaloneTest;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.test.TestResourceUnavailableException;
 import org.apache.brooklyn.util.text.StringFunctions;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/cli/src/main/java/org/apache/brooklyn/cli/CloudExplorer.java
----------------------------------------------------------------------
diff --git a/usage/cli/src/main/java/org/apache/brooklyn/cli/CloudExplorer.java b/usage/cli/src/main/java/org/apache/brooklyn/cli/CloudExplorer.java
index bf3ca8d..a221afb 100644
--- a/usage/cli/src/main/java/org/apache/brooklyn/cli/CloudExplorer.java
+++ b/usage/cli/src/main/java/org/apache/brooklyn/cli/CloudExplorer.java
@@ -41,8 +41,8 @@ import org.jclouds.compute.options.TemplateOptions;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.api.location.LocationDefinition;
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
 import org.apache.brooklyn.location.cloud.CloudLocationConfig;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
 import org.apache.brooklyn.location.jclouds.JcloudsLocation;
 import org.apache.brooklyn.location.jclouds.JcloudsUtil;
 import org.apache.brooklyn.util.exceptions.FatalConfigurationRuntimeException;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/cli/src/main/java/org/apache/brooklyn/cli/Main.java
----------------------------------------------------------------------
diff --git a/usage/cli/src/main/java/org/apache/brooklyn/cli/Main.java b/usage/cli/src/main/java/org/apache/brooklyn/cli/Main.java
index e5a40a7..7dfdcf8 100644
--- a/usage/cli/src/main/java/org/apache/brooklyn/cli/Main.java
+++ b/usage/cli/src/main/java/org/apache/brooklyn/cli/Main.java
@@ -65,8 +65,8 @@ import org.apache.brooklyn.cli.ItemLister.ListAllCommand;
 import org.apache.brooklyn.core.BrooklynVersion;
 import org.apache.brooklyn.core.catalog.internal.CatalogInitialization;
 import org.apache.brooklyn.core.mgmt.ha.OsgiManager;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynPersistenceUtils;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynPersistenceUtils;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
 import org.apache.brooklyn.core.mgmt.rebind.transformer.CompoundTransformer;
 import org.apache.brooklyn.core.objs.BrooklynTypes;
 import org.apache.brooklyn.entity.core.AbstractApplication;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/cli/src/test/java/org/apache/brooklyn/cli/CliTest.java
----------------------------------------------------------------------
diff --git a/usage/cli/src/test/java/org/apache/brooklyn/cli/CliTest.java b/usage/cli/src/test/java/org/apache/brooklyn/cli/CliTest.java
index e64c95d..4528ebb 100644
--- a/usage/cli/src/test/java/org/apache/brooklyn/cli/CliTest.java
+++ b/usage/cli/src/test/java/org/apache/brooklyn/cli/CliTest.java
@@ -72,7 +72,7 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Splitter;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/launcher/src/main/java/org/apache/brooklyn/launcher/BrooklynLauncher.java
----------------------------------------------------------------------
diff --git a/usage/launcher/src/main/java/org/apache/brooklyn/launcher/BrooklynLauncher.java b/usage/launcher/src/main/java/org/apache/brooklyn/launcher/BrooklynLauncher.java
index b5d2eec..5ea82f7 100644
--- a/usage/launcher/src/main/java/org/apache/brooklyn/launcher/BrooklynLauncher.java
+++ b/usage/launcher/src/main/java/org/apache/brooklyn/launcher/BrooklynLauncher.java
@@ -61,12 +61,12 @@ import org.apache.brooklyn.core.mgmt.ha.ManagementPlaneSyncRecordPersisterToObje
 import org.apache.brooklyn.core.mgmt.internal.BrooklynShutdownHooks;
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynPersistenceUtils;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
 import org.apache.brooklyn.core.mgmt.rebind.PersistenceExceptionHandlerImpl;
 import org.apache.brooklyn.core.mgmt.rebind.RebindManagerImpl;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynMementoPersisterToObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynPersistenceUtils;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
 import org.apache.brooklyn.core.mgmt.rebind.transformer.CompoundTransformer;
 import org.apache.brooklyn.core.server.BrooklynServerConfig;
 import org.apache.brooklyn.core.server.BrooklynServerPaths;
@@ -89,8 +89,8 @@ import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 
 import org.apache.brooklyn.launcher.config.StopWhichAppsOnShutdown;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation.LocalhostMachine;
 import org.apache.brooklyn.rest.BrooklynWebConfig;
 import org.apache.brooklyn.rest.filter.BrooklynPropertiesSecurityFilter;
 import org.apache.brooklyn.rest.security.provider.BrooklynUserWithRandomPasswordSecurityProvider;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/launcher/src/main/java/org/apache/brooklyn/launcher/BrooklynWebServer.java
----------------------------------------------------------------------
diff --git a/usage/launcher/src/main/java/org/apache/brooklyn/launcher/BrooklynWebServer.java b/usage/launcher/src/main/java/org/apache/brooklyn/launcher/BrooklynWebServer.java
index 21621de..f6623b2 100644
--- a/usage/launcher/src/main/java/org/apache/brooklyn/launcher/BrooklynWebServer.java
+++ b/usage/launcher/src/main/java/org/apache/brooklyn/launcher/BrooklynWebServer.java
@@ -68,8 +68,8 @@ import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
 import org.apache.brooklyn.core.server.BrooklynServerPaths;
 import org.apache.brooklyn.core.server.BrooklynServiceAttributes;
 import org.apache.brooklyn.launcher.config.CustomResourceLocator;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.rest.BrooklynRestApi;
 import org.apache.brooklyn.rest.BrooklynWebConfig;
 import org.apache.brooklyn.rest.filter.BrooklynPropertiesSecurityFilter;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherHighAvailabilityTest.java
----------------------------------------------------------------------
diff --git a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherHighAvailabilityTest.java b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherHighAvailabilityTest.java
index 0d074ca..6bc2b02 100644
--- a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherHighAvailabilityTest.java
+++ b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherHighAvailabilityTest.java
@@ -25,8 +25,8 @@ import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
 import org.apache.brooklyn.api.mgmt.ha.ManagementPlaneSyncRecordPersister;
 import org.apache.brooklyn.core.internal.BrooklynProperties;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
 import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.launcher.BrooklynLauncher;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogTest.java
----------------------------------------------------------------------
diff --git a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogTest.java b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogTest.java
index 9904536..3f39a18 100644
--- a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogTest.java
+++ b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogTest.java
@@ -37,7 +37,7 @@ import com.google.common.io.Files;
 import org.apache.brooklyn.api.catalog.BrooklynCatalog;
 import org.apache.brooklyn.api.catalog.CatalogItem;
 import org.apache.brooklyn.core.catalog.internal.CatalogInitialization;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
 import org.apache.brooklyn.util.core.ResourceUtils;
 import org.apache.brooklyn.util.os.Os;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindTestFixture.java
----------------------------------------------------------------------
diff --git a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindTestFixture.java b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindTestFixture.java
index d368842..0e34942 100644
--- a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindTestFixture.java
+++ b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindTestFixture.java
@@ -24,9 +24,9 @@ import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.api.mgmt.ManagementContext;
 import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
 import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynMementoPersisterToObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
 import org.apache.brooklyn.core.server.BrooklynServerConfig;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
 import org.apache.brooklyn.core.test.entity.TestApplication;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindTestToFiles.java
----------------------------------------------------------------------
diff --git a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindTestToFiles.java b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindTestToFiles.java
index 1144932..9f072b2 100644
--- a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindTestToFiles.java
+++ b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindTestToFiles.java
@@ -22,9 +22,9 @@ import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.mgmt.ManagementContext;
 import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
 import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynMementoPersisterToObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.FileBasedObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.FileBasedObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
 import org.apache.brooklyn.core.server.BrooklynServerPaths;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.launcher.BrooklynLauncher;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindToCloudObjectStoreTest.java
----------------------------------------------------------------------
diff --git a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindToCloudObjectStoreTest.java b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindToCloudObjectStoreTest.java
index b2be7c6..dba30ac 100644
--- a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindToCloudObjectStoreTest.java
+++ b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindToCloudObjectStoreTest.java
@@ -22,8 +22,10 @@ import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.mgmt.ManagementContext;
 import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
 import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynMementoPersisterToObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.jclouds.BlobStoreTest;
+import org.apache.brooklyn.core.mgmt.persist.jclouds.JcloudsBlobStoreBasedObjectStore;
 import org.apache.brooklyn.core.server.BrooklynServerPaths;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
 import org.apache.brooklyn.core.test.entity.TestApplication;
@@ -37,9 +39,6 @@ import static org.testng.Assert.assertEquals;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.rebind.persister.jclouds.BlobStoreTest;
-import brooklyn.entity.rebind.persister.jclouds.JcloudsBlobStoreBasedObjectStore;
-
 @Test(groups="Live")
 public class BrooklynLauncherRebindToCloudObjectStoreTest extends BrooklynLauncherRebindTestFixture {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherTest.java
----------------------------------------------------------------------
diff --git a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherTest.java b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherTest.java
index c4f25f1..e25e1fd 100644
--- a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherTest.java
+++ b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherTest.java
@@ -59,7 +59,7 @@ import org.apache.brooklyn.util.text.Strings;
 import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.api.client.util.Preconditions;
 import com.google.common.base.Charsets;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/launcher/src/test/java/org/apache/brooklyn/launcher/blueprints/AbstractBlueprintTest.java
----------------------------------------------------------------------
diff --git a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/blueprints/AbstractBlueprintTest.java b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/blueprints/AbstractBlueprintTest.java
index 6e228bf..b757652 100644
--- a/usage/launcher/src/test/java/org/apache/brooklyn/launcher/blueprints/AbstractBlueprintTest.java
+++ b/usage/launcher/src/test/java/org/apache/brooklyn/launcher/blueprints/AbstractBlueprintTest.java
@@ -30,9 +30,9 @@ import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.mgmt.ManagementContext;
 import org.apache.brooklyn.camp.brooklyn.BrooklynCampPlatformLauncherAbstract;
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.mgmt.persist.FileBasedObjectStore;
 import org.apache.brooklyn.core.mgmt.rebind.RebindOptions;
 import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
-import org.apache.brooklyn.core.mgmt.rebind.persister.FileBasedObjectStore;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.lifecycle.Lifecycle;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedJBoss7ServerImpl.java
----------------------------------------------------------------------
diff --git a/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedJBoss7ServerImpl.java b/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedJBoss7ServerImpl.java
index c500473..775d39b 100644
--- a/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedJBoss7ServerImpl.java
+++ b/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedJBoss7ServerImpl.java
@@ -27,7 +27,7 @@ import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.webapp.jboss.JBoss7ServerImpl;
 import org.apache.brooklyn.entity.webapp.jboss.JBoss7SshDriver;
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.enricher.Enrichers;
 import org.apache.brooklyn.sensor.feed.function.FunctionFeed;
 import org.apache.brooklyn.sensor.feed.function.FunctionPollConfig;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedMySqlNodeImpl.java
----------------------------------------------------------------------
diff --git a/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedMySqlNodeImpl.java b/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedMySqlNodeImpl.java
index af7d7db..4638aea 100644
--- a/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedMySqlNodeImpl.java
+++ b/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedMySqlNodeImpl.java
@@ -27,7 +27,7 @@ import org.apache.brooklyn.entity.database.mysql.MySqlNode;
 import org.apache.brooklyn.entity.database.mysql.MySqlNodeImpl;
 import org.apache.brooklyn.entity.database.mysql.MySqlSshDriver;
 import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.function.FunctionFeed;
 import org.apache.brooklyn.sensor.feed.function.FunctionPollConfig;
 import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedNginxControllerImpl.java
----------------------------------------------------------------------
diff --git a/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedNginxControllerImpl.java b/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedNginxControllerImpl.java
index 0de4bbc..258da82 100644
--- a/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedNginxControllerImpl.java
+++ b/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedNginxControllerImpl.java
@@ -32,7 +32,7 @@ import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.entity.proxy.nginx.NginxControllerImpl;
 import org.apache.brooklyn.entity.proxy.nginx.NginxSshDriver;
 import org.apache.brooklyn.entity.proxy.nginx.UrlMapping;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
 import org.apache.brooklyn.sensor.feed.function.FunctionFeed;
 import org.apache.brooklyn.sensor.feed.function.FunctionPollConfig;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedTheeTierApp.java
----------------------------------------------------------------------
diff --git a/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedTheeTierApp.java b/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedTheeTierApp.java
index 7423322..fe5b499 100644
--- a/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedTheeTierApp.java
+++ b/usage/qa/src/main/java/org/apache/brooklyn/qa/load/SimulatedTheeTierApp.java
@@ -43,7 +43,7 @@ import org.apache.brooklyn.entity.webapp.WebAppService;
 import org.apache.brooklyn.entity.webapp.WebAppServiceConstants;
 import org.apache.brooklyn.entity.webapp.jboss.JBoss7Server;
 import org.apache.brooklyn.launcher.BrooklynLauncher;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.policy.autoscaling.AutoScalerPolicy;
 import org.apache.brooklyn.policy.enricher.HttpLatencyDetector;
 import org.apache.brooklyn.sensor.enricher.Enrichers;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/qa/src/test/java/org/apache/brooklyn/qa/load/LoadTest.java
----------------------------------------------------------------------
diff --git a/usage/qa/src/test/java/org/apache/brooklyn/qa/load/LoadTest.java b/usage/qa/src/test/java/org/apache/brooklyn/qa/load/LoadTest.java
index 80fd5a5..e8489aa 100644
--- a/usage/qa/src/test/java/org/apache/brooklyn/qa/load/LoadTest.java
+++ b/usage/qa/src/test/java/org/apache/brooklyn/qa/load/LoadTest.java
@@ -33,7 +33,7 @@ import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.api.mgmt.ManagementContext;
 import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.core.StartableApplication;
 import org.apache.brooklyn.entity.trait.Startable;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/ApplicationResourceIntegrationTest.java
----------------------------------------------------------------------
diff --git a/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/ApplicationResourceIntegrationTest.java b/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/ApplicationResourceIntegrationTest.java
index 04ab24c..c2b40c2 100644
--- a/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/ApplicationResourceIntegrationTest.java
+++ b/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/ApplicationResourceIntegrationTest.java
@@ -33,7 +33,7 @@ import org.testng.Assert;
 import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.BasicLocationRegistry;
+import org.apache.brooklyn.location.core.BasicLocationRegistry;
 import org.apache.brooklyn.api.entity.Application;
 import org.apache.brooklyn.api.mgmt.ManagementContext;
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiRestClientTest.java
----------------------------------------------------------------------
diff --git a/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiRestClientTest.java b/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiRestClientTest.java
index 808b5d3..6eb4f6c 100644
--- a/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiRestClientTest.java
+++ b/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiRestClientTest.java
@@ -31,7 +31,7 @@ import org.testng.Assert;
 import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.BasicLocationRegistry;
+import org.apache.brooklyn.location.core.BasicLocationRegistry;
 import org.apache.brooklyn.api.entity.Application;
 import org.apache.brooklyn.api.mgmt.ManagementContext;
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/rest-server/src/main/java/org/apache/brooklyn/rest/resources/LocationResource.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/main/java/org/apache/brooklyn/rest/resources/LocationResource.java b/usage/rest-server/src/main/java/org/apache/brooklyn/rest/resources/LocationResource.java
index 1a9783e..7d4275a 100644
--- a/usage/rest-server/src/main/java/org/apache/brooklyn/rest/resources/LocationResource.java
+++ b/usage/rest-server/src/main/java/org/apache/brooklyn/rest/resources/LocationResource.java
@@ -33,7 +33,7 @@ import org.apache.brooklyn.api.catalog.CatalogItem;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.api.location.LocationDefinition;
 import org.apache.brooklyn.core.catalog.internal.CatalogUtils;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
 import org.apache.brooklyn.rest.api.LocationApi;
 import org.apache.brooklyn.rest.domain.LocationSpec;
 import org.apache.brooklyn.rest.domain.LocationSummary;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/rest-server/src/main/java/org/apache/brooklyn/rest/resources/ServerResource.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/main/java/org/apache/brooklyn/rest/resources/ServerResource.java b/usage/rest-server/src/main/java/org/apache/brooklyn/rest/resources/ServerResource.java
index 3caad68..1cca2c7 100644
--- a/usage/rest-server/src/main/java/org/apache/brooklyn/rest/resources/ServerResource.java
+++ b/usage/rest-server/src/main/java/org/apache/brooklyn/rest/resources/ServerResource.java
@@ -55,9 +55,9 @@ import org.apache.brooklyn.core.BrooklynVersion;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.core.mgmt.entitlement.Entitlements;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynPersistenceUtils;
-import org.apache.brooklyn.core.mgmt.rebind.persister.FileBasedObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynPersistenceUtils;
+import org.apache.brooklyn.core.mgmt.persist.FileBasedObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.core.StartableApplication;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/rest-server/src/main/java/org/apache/brooklyn/rest/transform/LocationTransformer.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/main/java/org/apache/brooklyn/rest/transform/LocationTransformer.java b/usage/rest-server/src/main/java/org/apache/brooklyn/rest/transform/LocationTransformer.java
index 44a5b34..16c6c65 100644
--- a/usage/rest-server/src/main/java/org/apache/brooklyn/rest/transform/LocationTransformer.java
+++ b/usage/rest-server/src/main/java/org/apache/brooklyn/rest/transform/LocationTransformer.java
@@ -23,9 +23,9 @@ import java.util.Map;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.BasicLocationDefinition;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
-import org.apache.brooklyn.location.basic.LocationInternal;
+import org.apache.brooklyn.location.core.BasicLocationDefinition;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.api.location.LocationDefinition;
 import org.apache.brooklyn.api.mgmt.ManagementContext;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/rest-server/src/main/java/org/apache/brooklyn/rest/util/EntityLocationUtils.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/main/java/org/apache/brooklyn/rest/util/EntityLocationUtils.java b/usage/rest-server/src/main/java/org/apache/brooklyn/rest/util/EntityLocationUtils.java
index fb11271..a0cf857 100644
--- a/usage/rest-server/src/main/java/org/apache/brooklyn/rest/util/EntityLocationUtils.java
+++ b/usage/rest-server/src/main/java/org/apache/brooklyn/rest/util/EntityLocationUtils.java
@@ -24,7 +24,7 @@ import java.util.Map;
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
 
 public class EntityLocationUtils {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceTest.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceTest.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceTest.java
index d8a3052..a65dc15 100644
--- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceTest.java
+++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceTest.java
@@ -56,9 +56,9 @@ import com.sun.jersey.api.client.UniformInterfaceException;
 import com.sun.jersey.api.client.WebResource;
 import com.sun.jersey.core.util.MultivaluedMapImpl;
 
-import org.apache.brooklyn.location.basic.AbstractLocation;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
-import org.apache.brooklyn.location.basic.LocationInternal;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 import org.apache.brooklyn.location.geo.HostGeoInfo;
 import org.apache.brooklyn.api.entity.Application;
 import org.apache.brooklyn.api.internal.EntityLocal;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/LocationResourceTest.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/LocationResourceTest.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/LocationResourceTest.java
index 5d5f697..cb006fd 100644
--- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/LocationResourceTest.java
+++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/LocationResourceTest.java
@@ -43,7 +43,7 @@ import com.sun.jersey.api.client.ClientResponse;
 import com.sun.jersey.api.client.GenericType;
 
 import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 import org.apache.brooklyn.location.jclouds.JcloudsLocation;
 import org.apache.brooklyn.rest.domain.CatalogLocationSummary;
 import org.apache.brooklyn.rest.domain.LocationSummary;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/UsageResourceTest.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/UsageResourceTest.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/UsageResourceTest.java
index 6250992..54ef87d 100644
--- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/UsageResourceTest.java
+++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/UsageResourceTest.java
@@ -43,8 +43,8 @@ import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.entity.factory.ApplicationBuilder;
 import org.apache.brooklyn.entity.software.base.SoftwareProcessEntityTest;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.rest.domain.ApplicationSpec;
 import org.apache.brooklyn.rest.domain.EntitySpec;
 import org.apache.brooklyn.rest.domain.Status;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/rest-server/src/test/java/org/apache/brooklyn/rest/testing/BrooklynRestApiTest.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/testing/BrooklynRestApiTest.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/testing/BrooklynRestApiTest.java
index 15c8bb3..e0318c4 100644
--- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/testing/BrooklynRestApiTest.java
+++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/testing/BrooklynRestApiTest.java
@@ -36,7 +36,7 @@ import com.sun.jersey.test.framework.AppDescriptor;
 import com.sun.jersey.test.framework.JerseyTest;
 import com.sun.jersey.test.framework.LowLevelAppDescriptor;
 
-import org.apache.brooklyn.location.basic.BasicLocationRegistry;
+import org.apache.brooklyn.location.core.BasicLocationRegistry;
 import org.apache.brooklyn.rest.BrooklynRestApi;
 import org.apache.brooklyn.rest.BrooklynRestApiLauncherTest;
 import org.apache.brooklyn.rest.util.BrooklynRestResourceUtils;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/rest-server/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimpleEntity.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimpleEntity.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimpleEntity.java
index d5e608f..5ecf58d 100644
--- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimpleEntity.java
+++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimpleEntity.java
@@ -32,7 +32,7 @@ import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver
 import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/usage/rest-server/src/test/java/org/apache/brooklyn/rest/util/EntityLocationUtilsTest.java
----------------------------------------------------------------------
diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/util/EntityLocationUtilsTest.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/util/EntityLocationUtilsTest.java
index ace877b..d6cae27 100644
--- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/util/EntityLocationUtilsTest.java
+++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/util/EntityLocationUtilsTest.java
@@ -27,8 +27,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.AbstractLocation;
-import org.apache.brooklyn.location.basic.LocationInternal;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 import org.apache.brooklyn.location.geo.HostGeoInfo;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/utils/test-bundles/entities/src/main/java/org/apache/brooklyn/test/osgi/entities/SimpleLocation.java
----------------------------------------------------------------------
diff --git a/utils/test-bundles/entities/src/main/java/org/apache/brooklyn/test/osgi/entities/SimpleLocation.java b/utils/test-bundles/entities/src/main/java/org/apache/brooklyn/test/osgi/entities/SimpleLocation.java
index 48576c4..a474a03 100644
--- a/utils/test-bundles/entities/src/main/java/org/apache/brooklyn/test/osgi/entities/SimpleLocation.java
+++ b/utils/test-bundles/entities/src/main/java/org/apache/brooklyn/test/osgi/entities/SimpleLocation.java
@@ -20,7 +20,7 @@ package org.apache.brooklyn.test.osgi.entities;
 
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.location.basic.AbstractLocation;
+import org.apache.brooklyn.location.core.AbstractLocation;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
 public class SimpleLocation extends AbstractLocation {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreLocation.java
----------------------------------------------------------------------
diff --git a/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreLocation.java b/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreLocation.java
index 8af0a34..14c884d 100644
--- a/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreLocation.java
+++ b/utils/test-bundles/more-entities-v1/src/main/java/org/apache/brooklyn/test/osgi/entities/more/MoreLocation.java
@@ -19,7 +19,7 @@
 package org.apache.brooklyn.test.osgi.entities.more;
 
 
-import org.apache.brooklyn.location.basic.AbstractLocation;
+import org.apache.brooklyn.location.core.AbstractLocation;
 
 public class MoreLocation extends AbstractLocation {
 }


[62/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/AggregatingMachineProvisioningLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/AggregatingMachineProvisioningLocation.java b/core/src/main/java/org/apache/brooklyn/location/basic/AggregatingMachineProvisioningLocation.java
deleted file mode 100644
index 2898ea8..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/AggregatingMachineProvisioningLocation.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static com.google.common.base.Preconditions.checkState;
-
-import java.io.Closeable;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.apache.brooklyn.util.stream.Streams;
-
-import com.google.common.base.Objects;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-
-/**
- * Takes a list of other provisioners, and round-robins across them when obtaining a machine.
- */
-public class AggregatingMachineProvisioningLocation<T extends MachineLocation> extends AbstractLocation 
-        implements MachineProvisioningLocation<T>, Closeable {
-
-    private Object lock;
-    
-    @SetFromFlag
-    protected List<MachineProvisioningLocation<T>> provisioners;
-    
-    @SetFromFlag
-    protected Map<T, MachineProvisioningLocation<T>> inUse;
-
-    protected final AtomicInteger obtainCounter = new AtomicInteger();
-    
-    public AggregatingMachineProvisioningLocation() {
-        this(Maps.newLinkedHashMap());
-    }
-    
-    public AggregatingMachineProvisioningLocation(Map properties) {
-        super(properties);
-
-        if (isLegacyConstruction()) {
-            init();
-        }
-    }
-
-    @Override
-    public void init() {
-        super.init();
-    }
-    
-    @Override
-    public String toVerboseString() {
-        return Objects.toStringHelper(this).omitNullValues()
-                .add("id", getId()).add("name", getDisplayName())
-                .add("provisioners", provisioners)
-                .toString();
-    }
-
-    @Override
-    public AbstractLocation configure(Map<?,?> properties) {
-        if (lock == null) {
-            lock = new Object();
-            provisioners = Lists.<MachineProvisioningLocation<T>>newArrayList();
-            inUse = Maps.<T, MachineProvisioningLocation<T>>newLinkedHashMap();
-        }
-        return super.configure(properties);
-    }
-    
-    @Override
-    public AggregatingMachineProvisioningLocation<T> newSubLocation(Map<?,?> newFlags) {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
-    public void close() {
-        for (MachineProvisioningLocation<?> provisioner : provisioners) {
-            if (provisioner instanceof Closeable) {
-                Streams.closeQuietly((Closeable)provisioner);
-            }
-        }
-    }
-    
-    public T obtain() throws NoMachinesAvailableException {
-        return obtain(Maps.<String,Object>newLinkedHashMap());
-    }
-    
-    @Override
-    public T obtain(Map<?,?> flags) throws NoMachinesAvailableException {
-        checkState(provisioners.size() > 0, "no provisioners!");
-        int index = obtainCounter.getAndIncrement();
-        for (int i = 0; i < provisioners.size(); i++) {
-            MachineProvisioningLocation<T> provisioner = provisioners.get(index++ % provisioners.size());
-            try {
-                T machine = provisioner.obtain(flags);
-                inUse.put(machine, provisioner);
-                return machine;
-            } catch (NoMachinesAvailableException e) {
-                // move on; try next
-            }
-        }
-        throw new NoMachinesAvailableException("No machines available in "+toString());
-    }
-
-    @Override
-    public void release(T machine) {
-        MachineProvisioningLocation<T> provisioner = inUse.remove(machine);
-        if (provisioner != null) {
-            provisioner.release(machine);
-        } else {
-            throw new IllegalStateException("Request to release machine "+machine+", but this machine is not currently allocated");
-        }
-    }
-
-    @Override
-    public Map<String,Object> getProvisioningFlags(Collection<String> tags) {
-        return Maps.<String,Object>newLinkedHashMap();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/BasicHardwareDetails.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/BasicHardwareDetails.java b/core/src/main/java/org/apache/brooklyn/location/basic/BasicHardwareDetails.java
deleted file mode 100644
index 4393884..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/BasicHardwareDetails.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import javax.annotation.concurrent.Immutable;
-
-import com.google.common.base.Objects;
-
-import org.apache.brooklyn.api.location.HardwareDetails;
-
-@Immutable
-public class BasicHardwareDetails implements HardwareDetails {
-
-    private final Integer cpuCount;
-    private final Integer ram;
-
-    public BasicHardwareDetails(Integer cpuCount, Integer ram) {
-        this.cpuCount = cpuCount;
-        this.ram = ram;
-    }
-
-    @Override
-    public Integer getCpuCount() {
-        return cpuCount;
-    }
-
-    @Override
-    public Integer getRam() {
-        return ram;
-    }
-
-    @Override
-    public String toString() {
-        return Objects.toStringHelper(HardwareDetails.class)
-                .omitNullValues()
-                .add("cpuCount", cpuCount)
-                .add("ram", ram)
-                .toString();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/BasicLocationDefinition.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/BasicLocationDefinition.java b/core/src/main/java/org/apache/brooklyn/location/basic/BasicLocationDefinition.java
deleted file mode 100644
index cae2986..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/BasicLocationDefinition.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.location.LocationDefinition;
-import org.apache.brooklyn.util.text.Identifiers;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableMap;
-
-public class BasicLocationDefinition implements LocationDefinition {
-
-    private final String id;
-    private final String name;
-    private final String spec;
-    private final Map<String,Object> config;
-
-    public BasicLocationDefinition(String name, String spec, Map<String,? extends Object> config) {
-        this(Identifiers.makeRandomId(8), name, spec, config);
-    }
-    
-    public BasicLocationDefinition(String id, String name, String spec, Map<String,? extends Object> config) {      
-        this.id = Preconditions.checkNotNull(id);
-        this.name = name;
-        this.spec = Preconditions.checkNotNull(spec);
-        this.config = config==null ? ImmutableMap.<String, Object>of() : ImmutableMap.<String, Object>copyOf(config);
-    }
-
-    public String getId() {
-        return id;
-    }
-
-    public String getName() {
-        return name;
-    }
-    
-    public String getSpec() {
-        return spec;
-    }
-    
-    @Override
-    public Map<String, Object> getConfig() {
-        return config;
-    }
-    
-    @Override
-    public boolean equals(Object o) {
-        if (this==o) return true;
-        if ((o instanceof LocationDefinition) && id.equals(((LocationDefinition)o).getId())) return true;
-        return false;
-    }
-
-    @Override
-    public int hashCode() {
-        return id.hashCode();
-    }
-
-    @Override
-    public String toString() {
-        return "LocationDefinition{" +
-                "id='" + getId() + '\'' +
-                ", name='" + getName() + '\'' +
-                ", spec='" + getSpec() + '\'' +
-                ", config=" + getConfig() +
-                '}';
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/BasicLocationRegistry.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/BasicLocationRegistry.java b/core/src/main/java/org/apache/brooklyn/location/basic/BasicLocationRegistry.java
deleted file mode 100644
index 7f08e04..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/BasicLocationRegistry.java
+++ /dev/null
@@ -1,479 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.ServiceLoader;
-import java.util.Set;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.api.catalog.BrooklynCatalog;
-import org.apache.brooklyn.api.catalog.CatalogItem;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationDefinition;
-import org.apache.brooklyn.api.location.LocationRegistry;
-import org.apache.brooklyn.api.location.LocationResolver;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.config.ConfigMap;
-import org.apache.brooklyn.core.catalog.CatalogPredicates;
-import org.apache.brooklyn.core.config.ConfigPredicates;
-import org.apache.brooklyn.core.config.ConfigUtils;
-import org.apache.brooklyn.core.mgmt.internal.LocalLocationManager;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.guava.Maybe.Absent;
-import org.apache.brooklyn.util.javalang.JavaClassNames;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.apache.brooklyn.util.text.WildcardGlobs;
-import org.apache.brooklyn.util.text.StringEscapes.JavaStringEscapes;
-import org.apache.brooklyn.util.text.WildcardGlobs.PhraseTreatment;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Suppliers;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Sets;
-
-/**
- * See {@link LocationRegistry} for general description.
- * <p>
- * TODO The relationship between the catalog and the location registry is a bit messy.
- * For all existing code, the location registry is the definitive way to resolve
- * locations. 
- * <p>
- * Any location item added to the catalog must therefore be registered here.
- * Whenever an item is added to the catalog, it will automatically call 
- * {@link #updateDefinedLocation(CatalogItem)}. Similarly, when a location
- * is deleted from the catalog it will call {@link #removeDefinedLocation(CatalogItem)}.
- * <p>
- * However, the location item in the catalog has an unparsed blob of YAML, which contains
- * important things like the type and the config of the location. This is only parsed when 
- * {@link BrooklynCatalog#createSpec(CatalogItem)} is called. We therefore jump through 
- * some hoops to wire together the catalog and the registry.
- * <p>
- * To add a location to the catalog, and then to resolve a location that is in the catalog, 
- * it goes through the following steps:
- * 
- * <ol>
- *   <li>Call {@link BrooklynCatalog#addItems(String)}
- *     <ol>
- *       <li>This automatically calls {@link #updateDefinedLocation(CatalogItem)}
- *       <li>A LocationDefinition is creating, using as its id the {@link CatalogItem#getSymbolicName()}.
- *           The definition's spec is {@code brooklyn.catalog:<symbolicName>:<version>},
- *     </ol>
- *   <li>A blueprint can reference the catalog item using its symbolic name, 
- *       such as the YAML {@code location: my-new-location}.
- *       (this feels similar to the "named locations").
- *     <ol>
- *       <li>This automatically calls {@link #resolve(String)}.
- *       <li>The LocationDefinition is found by lookig up this name.
- *       <li>The {@link LocationDefiniton.getSpec()} is retrieved; the right {@link LocationResolver} is
- *           found for it.
- *       <li>This uses the {@link CatalogLocationResolver}, because the spec starts with {@code brooklyn.catalog:}.
- *       <li>This resolver extracts from the spec the <symobolicName>:<version>, and looks up the 
- *           catalog item using {@link BrooklynCatalog#getCatalogItem(String, String)}.
- *       <li>It then creates a {@link LocationSpec} by calling {@link BrooklynCatalog#createSpec(CatalogItem)}.
- *         <ol>
- *           <li>This first tries to use the type (that is in the YAML) as a simple Java class.
- *           <li>If that fails, it will resolve the type using {@link #resolve(String, Boolean, Map)}, which
- *               returns an actual location object.
- *           <li>It extracts from that location object the appropriate metadata to create a {@link LocationSpec},
- *               returns the spec and discards the location object.
- *         </ol>
- *       <li>The resolver creates the {@link Location} from the {@link LocationSpec}
- *     </ol>
- * </ol>
- * 
- * There is no concept of a location version in this registry. The version
- * in the catalog is generally ignored.
- */
-@SuppressWarnings({"rawtypes","unchecked"})
-public class BasicLocationRegistry implements LocationRegistry {
-
-    // TODO save / serialize
-    // (we persist live locations, ie those in the LocationManager, but not "catalog" locations, ie those in this Registry)
-    
-    public static final Logger log = LoggerFactory.getLogger(BasicLocationRegistry.class);
-
-    /**
-     * Splits a comma-separated list of locations (names or specs) into an explicit list.
-     * The splitting is very careful to handle commas embedded within specs, to split correctly.
-     */
-    public static List<String> expandCommaSeparateLocations(String locations) {
-        return WildcardGlobs.getGlobsAfterBraceExpansion("{"+locations+"}", false, PhraseTreatment.INTERIOR_NOT_EXPANDABLE, PhraseTreatment.INTERIOR_NOT_EXPANDABLE);
-        // don't do this, it tries to expand commas inside parentheses which is not good!
-//        QuotedStringTokenizer.builder().addDelimiterChars(",").buildList((String)id);
-    }
-
-    private final ManagementContext mgmt;
-    /** map of defined locations by their ID */
-    private final Map<String,LocationDefinition> definedLocations = new LinkedHashMap<String, LocationDefinition>();
-
-    protected final Map<String,LocationResolver> resolvers = new LinkedHashMap<String, LocationResolver>();
-
-    private final Set<String> specsWarnedOnException = Sets.newConcurrentHashSet();
-
-    public BasicLocationRegistry(ManagementContext mgmt) {
-        this.mgmt = checkNotNull(mgmt, "mgmt");
-        findServices();
-        updateDefinedLocations();
-    }
-
-    protected void findServices() {
-        ServiceLoader<LocationResolver> loader = ServiceLoader.load(LocationResolver.class, mgmt.getCatalogClassLoader());
-        for (LocationResolver r: loader) {
-            registerResolver(r);
-        }
-        if (log.isDebugEnabled()) log.debug("Location resolvers are: "+resolvers);
-        if (resolvers.isEmpty()) log.warn("No location resolvers detected: is src/main/resources correctly included?");
-    }
-
-    /** Registers the given resolver, invoking {@link LocationResolver#init(ManagementContext)} on the argument
-     * and returning true, unless the argument indicates false for {@link LocationResolver.EnableableLocationResolver#isEnabled()} */
-    public boolean registerResolver(LocationResolver r) {
-        r.init(mgmt);
-        if (r instanceof LocationResolver.EnableableLocationResolver) {
-            if (!((LocationResolver.EnableableLocationResolver)r).isEnabled()) {
-                return false;
-            }
-        }
-        resolvers.put(r.getPrefix(), r);
-        return true;
-    }
-    
-    @Override
-    public Map<String,LocationDefinition> getDefinedLocations() {
-        synchronized (definedLocations) {
-            return ImmutableMap.<String,LocationDefinition>copyOf(definedLocations);
-        }
-    }
-    
-    @Override
-    public LocationDefinition getDefinedLocationById(String id) {
-        return definedLocations.get(id);
-    }
-
-    @Override
-    public LocationDefinition getDefinedLocationByName(String name) {
-        synchronized (definedLocations) {
-            for (LocationDefinition l: definedLocations.values()) {
-                if (l.getName().equals(name)) return l;
-            }
-            return null;
-        }
-    }
-
-    @Override
-    public void updateDefinedLocation(LocationDefinition l) {
-        synchronized (definedLocations) { 
-            definedLocations.put(l.getId(), l); 
-        }
-    }
-
-    /**
-     * Converts the given item from the catalog into a LocationDefinition, and adds it
-     * to the registry (overwriting anything already registered with the id
-     * {@link CatalogItem#getCatalogItemId()}.
-     */
-    public void updateDefinedLocation(CatalogItem<Location, LocationSpec<?>> item) {
-        String id = item.getCatalogItemId();
-        String symbolicName = item.getSymbolicName();
-        String spec = CatalogLocationResolver.NAME + ":" + id;
-        Map<String, Object> config = ImmutableMap.<String, Object>of();
-        BasicLocationDefinition locDefinition = new BasicLocationDefinition(symbolicName, symbolicName, spec, config);
-        
-        updateDefinedLocation(locDefinition);
-    }
-
-    public void removeDefinedLocation(CatalogItem<Location, LocationSpec<?>> item) {
-        removeDefinedLocation(item.getSymbolicName());
-    }
-    
-    @Override
-    public void removeDefinedLocation(String id) {
-        LocationDefinition removed;
-        synchronized (definedLocations) { 
-            removed = definedLocations.remove(id);
-        }
-        if (removed == null && log.isDebugEnabled()) {
-            log.debug("{} was asked to remove location with id {} but no such location was registered", this, id);
-        }
-    }
-    
-    public void updateDefinedLocations() {
-        synchronized (definedLocations) {
-            // first read all properties starting  brooklyn.location.named.xxx
-            // (would be nice to move to a better way, e.g. yaml, then deprecate this approach, but first
-            // we need ability/format for persisting named locations, and better support for adding+saving via REST/GUI)
-            int count = 0; 
-            String NAMED_LOCATION_PREFIX = "brooklyn.location.named.";
-            ConfigMap namedLocationProps = mgmt.getConfig().submap(ConfigPredicates.startingWith(NAMED_LOCATION_PREFIX));
-            for (String k: namedLocationProps.asMapWithStringKeys().keySet()) {
-                String name = k.substring(NAMED_LOCATION_PREFIX.length());
-                // If has a dot, then is a sub-property of a named location (e.g. brooklyn.location.named.prod1.user=bob)
-                if (!name.contains(".")) {
-                    // this is a new named location
-                    String spec = (String) namedLocationProps.asMapWithStringKeys().get(k);
-                    // make up an ID
-                    String id = Identifiers.makeRandomId(8);
-                    Map<String, Object> config = ConfigUtils.filterForPrefixAndStrip(namedLocationProps.asMapWithStringKeys(), k+".");
-                    definedLocations.put(id, new BasicLocationDefinition(id, name, spec, config));
-                    count++;
-                }
-            }
-            if (log.isDebugEnabled())
-                log.debug("Found "+count+" defined locations from properties (*.named.* syntax): "+definedLocations.values());
-            if (getDefinedLocationByName("localhost")==null && !BasicOsDetails.Factory.newLocalhostInstance().isWindows()
-                    && LocationConfigUtils.isEnabled(mgmt, "brooklyn.location.localhost")) {
-                log.debug("Adding a defined location for localhost");
-                // add 'localhost' *first*
-                ImmutableMap<String, LocationDefinition> oldDefined = ImmutableMap.copyOf(definedLocations);
-                definedLocations.clear();
-                String id = Identifiers.makeRandomId(8);
-                definedLocations.put(id, localhost(id));
-                definedLocations.putAll(oldDefined);
-            }
-            
-            for (CatalogItem<Location, LocationSpec<?>> item : mgmt.getCatalog().getCatalogItems(CatalogPredicates.IS_LOCATION)) {
-                updateDefinedLocation(item);
-                count++;
-            }
-        }
-    }
-    
-    @VisibleForTesting
-    void disablePersistence() {
-        // persistence isn't enabled yet anyway (have to manually save things,
-        // defining the format and file etc)
-    }
-
-    protected static BasicLocationDefinition localhost(String id) {
-        return new BasicLocationDefinition(id, "localhost", "localhost", null);
-    }
-    
-    /** to catch circular references */
-    protected ThreadLocal<Set<String>> specsSeen = new ThreadLocal<Set<String>>();
-    
-    @Override @Deprecated
-    public boolean canMaybeResolve(String spec) {
-        return getSpecResolver(spec) != null;
-    }
-
-    @Override
-    public final Location resolve(String spec) {
-        return resolve(spec, true, null).get();
-    }
-    
-    @Override @Deprecated
-    public final Location resolveIfPossible(String spec) {
-        if (!canMaybeResolve(spec)) return null;
-        return resolve(spec, null, null).orNull();
-    }
-    
-    @Deprecated /** since 0.7.0 not used */
-    public final Maybe<Location> resolve(String spec, boolean manage) {
-        return resolve(spec, manage, null);
-    }
-    
-    public Maybe<Location> resolve(String spec, Boolean manage, Map locationFlags) {
-        try {
-            locationFlags = MutableMap.copyOf(locationFlags);
-            if (manage!=null) {
-                locationFlags.put(LocalLocationManager.CREATE_UNMANAGED, !manage);
-            }
-            
-            Set<String> seenSoFar = specsSeen.get();
-            if (seenSoFar==null) {
-                seenSoFar = new LinkedHashSet<String>();
-                specsSeen.set(seenSoFar);
-            }
-            if (seenSoFar.contains(spec))
-                return Maybe.absent(Suppliers.ofInstance(new IllegalStateException("Circular reference in definition of location '"+spec+"' ("+seenSoFar+")")));
-            seenSoFar.add(spec);
-            
-            LocationResolver resolver = getSpecResolver(spec);
-
-            if (resolver != null) {
-                try {
-                    return Maybe.of(resolver.newLocationFromString(locationFlags, spec, this));
-                } catch (RuntimeException e) {
-                    return Maybe.absent(Suppliers.ofInstance(e));
-                }
-            }
-
-            // problem: but let's ensure that classpath is sane to give better errors in common IDE bogus case;
-            // and avoid repeated logging
-            String errmsg;
-            if (spec == null || specsWarnedOnException.add(spec)) {
-                if (resolvers.get("id")==null || resolvers.get("named")==null) {
-                    log.error("Standard location resolvers not installed, location resolution will fail shortly. "
-                            + "This usually indicates a classpath problem, such as when running from an IDE which "
-                            + "has not properly copied META-INF/services from src/main/resources. "
-                            + "Known resolvers are: "+resolvers.keySet());
-                    errmsg = "Unresolvable location '"+spec+"': "
-                            + "Problem detected with location resolver configuration; "
-                            + resolvers.keySet()+" are the only available location resolvers. "
-                            + "More information can be found in the logs.";
-                } else {
-                    log.debug("Location resolution failed for '"+spec+"' (if this is being loaded it will fail shortly): known resolvers are: "+resolvers.keySet());
-                    errmsg = "Unknown location '"+spec+"': "
-                            + "either this location is not recognised or there is a problem with location resolver configuration.";
-                }
-            } else {
-                // For helpful log message construction: assumes classpath will not suddenly become wrong; might happen with OSGi though!
-                if (log.isDebugEnabled()) log.debug("Location resolution failed again for '"+spec+"' (throwing)");
-                errmsg = "Unknown location '"+spec+"': "
-                        + "either this location is not recognised or there is a problem with location resolver configuration.";
-            }
-
-            return Maybe.absent(Suppliers.ofInstance(new NoSuchElementException(errmsg)));
-
-        } finally {
-            specsSeen.remove();
-        }
-    }
-
-    @Override
-    public final Location resolve(String spec, Map locationFlags) {
-        return resolve(spec, null, locationFlags).get();
-    }
-
-    protected LocationResolver getSpecResolver(String spec) {
-        int colonIndex = spec.indexOf(':');
-        int bracketIndex = spec.indexOf("(");
-        int dividerIndex = (colonIndex < 0) ? bracketIndex : (bracketIndex < 0 ? colonIndex : Math.min(bracketIndex, colonIndex));
-        String prefix = dividerIndex >= 0 ? spec.substring(0, dividerIndex) : spec;
-        LocationResolver resolver = resolvers.get(prefix);
-       
-        if (resolver == null)
-            resolver = getSpecDefaultResolver(spec);
-        
-        return resolver;
-    }
-    
-    protected LocationResolver getSpecDefaultResolver(String spec) {
-        return getSpecFirstResolver(spec, "id", "named", "jclouds");
-    }
-    protected LocationResolver getSpecFirstResolver(String spec, String ...resolversToCheck) {
-        for (String resolverId: resolversToCheck) {
-            LocationResolver resolver = resolvers.get(resolverId);
-            if (resolver!=null && resolver.accepts(spec, this))
-                return resolver;
-        }
-        return null;
-    }
-
-    /** providers default impl for RegistryLocationResolver.accepts */
-    public static boolean isResolverPrefixForSpec(LocationResolver resolver, String spec, boolean argumentRequired) {
-        if (spec==null) return false;
-        if (spec.startsWith(resolver.getPrefix()+":")) return true;
-        if (!argumentRequired && spec.equals(resolver.getPrefix())) return true;
-        return false;
-    }
-
-    @Override
-    public List<Location> resolve(Iterable<?> spec) {
-        List<Location> result = new ArrayList<Location>();
-        for (Object id : spec) {
-            if (id instanceof String) {
-                result.add(resolve((String) id));
-            } else if (id instanceof Location) {
-                result.add((Location) id);
-            } else {
-                if (id instanceof Iterable)
-                    throw new IllegalArgumentException("Cannot resolve '"+id+"' to a location; collections of collections not allowed"); 
-                throw new IllegalArgumentException("Cannot resolve '"+id+"' to a location; unsupported type "+
-                        (id == null ? "null" : id.getClass().getName())); 
-            }
-        }
-        return result;
-    }
-    
-    public List<Location> resolveList(Object l) {
-        if (l==null) l = Collections.emptyList();
-        if (l instanceof String) l = JavaStringEscapes.unwrapJsonishListIfPossible((String)l);
-        if (l instanceof Iterable) return resolve((Iterable<?>)l);
-        throw new IllegalArgumentException("Location list must be supplied as a collection or a string, not "+
-            JavaClassNames.simpleClassName(l)+"/"+l);
-    }
-    
-    @Override
-    public Location resolve(LocationDefinition ld) {
-        return resolve(ld, null, null).get();
-    }
-
-    @Override @Deprecated
-    public Location resolveForPeeking(LocationDefinition ld) {
-        // TODO should clean up how locations are stored, figuring out whether they are shared or not;
-        // or maybe better, the API calls to this might just want to get the LocationSpec objects back
-        
-        // for now we use a 'CREATE_UNMANGED' flag to prevent management (leaks and logging)
-        return resolve(ld, ConfigBag.newInstance().configure(LocalLocationManager.CREATE_UNMANAGED, true).getAllConfig());
-    }
-
-    @Override @Deprecated
-    public Location resolve(LocationDefinition ld, Map<?,?> flags) {
-        return resolveLocationDefinition(ld, flags, null);
-    }
-    
-    /** @deprecated since 0.7.0 not used (and optionalName was ignored anyway) */
-    @Deprecated
-    public Location resolveLocationDefinition(LocationDefinition ld, Map locationFlags, String optionalName) {
-        return resolve(ld, null, locationFlags).get();
-    }
-    
-    public Maybe<Location> resolve(LocationDefinition ld, Boolean manage, Map locationFlags) {
-        ConfigBag newLocationFlags = ConfigBag.newInstance(ld.getConfig())
-            .putAll(locationFlags)
-            .putIfAbsentAndNotNull(LocationInternal.NAMED_SPEC_NAME, ld.getName())
-            .putIfAbsentAndNotNull(LocationInternal.ORIGINAL_SPEC, ld.getName());
-        Maybe<Location> result = resolve(ld.getSpec(), manage, newLocationFlags.getAllConfigRaw());
-        if (result.isPresent()) 
-            return result;
-        throw new IllegalStateException("Cannot instantiate location '"+ld+"' pointing at "+ld.getSpec()+": "+
-            Exceptions.collapseText( ((Absent<?>)result).getException() ));
-    }
-
-    @Override
-    public Map getProperties() {
-        return mgmt.getConfig().asMapWithStringKeys();
-    }
-
-    @VisibleForTesting
-    public static void setupLocationRegistryForTesting(ManagementContext mgmt) {
-        // ensure localhost is added (even on windows)
-        LocationDefinition l = mgmt.getLocationRegistry().getDefinedLocationByName("localhost");
-        if (l==null) mgmt.getLocationRegistry().updateDefinedLocation(
-                BasicLocationRegistry.localhost(Identifiers.makeRandomId(8)) );
-        
-        ((BasicLocationRegistry)mgmt.getLocationRegistry()).disablePersistence();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/BasicMachineDetails.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/BasicMachineDetails.java b/core/src/main/java/org/apache/brooklyn/location/basic/BasicMachineDetails.java
deleted file mode 100644
index e92deaf..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/BasicMachineDetails.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-
-import javax.annotation.Nonnull;
-import javax.annotation.concurrent.Immutable;
-
-import org.apache.brooklyn.api.location.HardwareDetails;
-import org.apache.brooklyn.api.location.MachineDetails;
-import org.apache.brooklyn.api.location.OsDetails;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.util.core.ResourceUtils;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.TaskTags;
-import org.apache.brooklyn.util.core.task.ssh.internal.PlainSshExecTaskFactory;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.apache.brooklyn.util.stream.Streams;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.CharMatcher;
-import com.google.common.base.Function;
-import com.google.common.base.Joiner;
-import com.google.common.base.Objects;
-import com.google.common.base.Splitter;
-import com.google.common.base.Throwables;
-import com.google.common.collect.Maps;
-import com.google.common.io.CharStreams;
-
-@Immutable
-public class BasicMachineDetails implements MachineDetails {
-
-    public static final Logger LOG = LoggerFactory.getLogger(BasicMachineDetails.class);
-
-    private final HardwareDetails hardwareDetails;
-    private final OsDetails osDetails;
-
-    public BasicMachineDetails(HardwareDetails hardwareDetails, OsDetails osDetails) {
-        this.hardwareDetails = checkNotNull(hardwareDetails, "hardwareDetails");
-        this.osDetails = checkNotNull(osDetails, "osDetails");
-    }
-
-    @Nonnull
-    @Override
-    public HardwareDetails getHardwareDetails() {
-        return hardwareDetails;
-    }
-
-    @Nonnull
-    @Override
-    public OsDetails getOsDetails() {
-        return osDetails;
-    }
-
-    @Override
-    public String toString() {
-        return Objects.toStringHelper(MachineDetails.class)
-                .add("os", osDetails)
-                .add("hardware", hardwareDetails)
-                .toString();
-    }
-
-    /**
-     * Creates a MachineDetails for the given location by SSHing to the machine and
-     * running a Bash script to gather data. Should only be called from within a
-     * task context. If this might not be the case then use {@link
-     * #taskForSshMachineLocation(SshMachineLocation)} instead.
-     */
-    static BasicMachineDetails forSshMachineLocation(SshMachineLocation location) {
-        return TaskTags.markInessential(DynamicTasks.queueIfPossible(taskForSshMachineLocation(location))
-                .orSubmitAsync()
-                .asTask())
-                .getUnchecked();
-    }
-
-    /**
-     * @return A task that gathers machine details by SSHing to the machine and running
-     *         a Bash script to gather data.
-     */
-    static Task<BasicMachineDetails> taskForSshMachineLocation(SshMachineLocation location) {
-        BufferedReader reader = new BufferedReader(Streams.reader(
-                new ResourceUtils(BasicMachineDetails.class).getResourceFromUrl(
-                        "classpath://org/apache/brooklyn/location/basic/os-details.sh")));
-        List<String> script;
-        try {
-            script = CharStreams.readLines(reader);
-        } catch (IOException e) {
-            LOG.error("Error reading os-details script", e);
-            throw Throwables.propagate(e);
-        } finally {
-            try {
-                reader.close();
-            } catch (IOException e) {
-                // Not rethrowing e because it might obscure an exception caught by the first catch
-                LOG.error("Error closing os-details script reader", e);
-            }
-        }
-        Task<BasicMachineDetails> task = new PlainSshExecTaskFactory<String>(location, script)
-                .summary("Getting machine details for: " + location)
-                .requiringZeroAndReturningStdout()
-                .returning(taskToMachineDetailsFunction(location))
-                .newTask()
-                .asTask();
-
-        return task;
-    }
-
-    private static Function<ProcessTaskWrapper<?>, BasicMachineDetails> taskToMachineDetailsFunction(final SshMachineLocation location) {
-        return new Function<ProcessTaskWrapper<?>, BasicMachineDetails>() {
-            @Override
-            public BasicMachineDetails apply(ProcessTaskWrapper<?> input) {
-                if (input.getExitCode() != 0) {
-                    LOG.warn("Non-zero exit code when fetching machine details for {}; guessing anonymous linux", location);
-                    return new BasicMachineDetails(new BasicHardwareDetails(null, null),
-                            BasicOsDetails.Factory.ANONYMOUS_LINUX);
-                }
-
-                String stdout = input.getStdout();
-                if (LOG.isDebugEnabled()) {
-                    LOG.debug("Found following details at {}: {}", location, stdout);
-                }
-
-                Map<String,String> details = Maps.newHashMap(Splitter.on(CharMatcher.anyOf("\r\n"))
-                        .omitEmptyStrings()
-                        .withKeyValueSeparator(":")
-                        .split(stdout));
-
-                String name = details.remove("name");
-                String version = details.remove("version");
-                String architecture = details.remove("architecture");
-                Integer ram = intOrNull(details, "ram");
-                Integer cpuCount = intOrNull(details, "cpus");
-                if (!details.isEmpty()) {
-                    LOG.debug("Unused keys from os-details script: " + Joiner.on(", ").join(details.keySet()));
-                }
-
-                OsDetails osDetails = new BasicOsDetails(name, architecture, version);
-                HardwareDetails hardwareDetails = new BasicHardwareDetails(cpuCount, ram);
-                BasicMachineDetails machineDetails = new BasicMachineDetails(hardwareDetails, osDetails);
-
-                if (LOG.isDebugEnabled())
-                    LOG.debug("Machine details for {}: {}", location, machineDetails);
-
-                return machineDetails;
-            }
-
-            private Integer intOrNull(Map<String, String> details, String key) {
-                try {
-                    return Integer.valueOf(details.remove(key));
-                } catch (NumberFormatException e) {
-                    return null;
-                }
-            }
-        };
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/BasicMachineMetadata.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/BasicMachineMetadata.java b/core/src/main/java/org/apache/brooklyn/location/basic/BasicMachineMetadata.java
deleted file mode 100644
index 95c8f0e..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/BasicMachineMetadata.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import com.google.common.base.Objects;
-
-import org.apache.brooklyn.api.location.MachineManagementMixins;
-
-public class BasicMachineMetadata implements MachineManagementMixins.MachineMetadata {
-
-    final String id, name, primaryIp;
-    final Boolean isRunning;
-    final Object originalMetadata;
-    
-    public BasicMachineMetadata(String id, String name, String primaryIp, Boolean isRunning, Object originalMetadata) {
-        super();
-        this.id = id;
-        this.name = name;
-        this.primaryIp = primaryIp;
-        this.isRunning = isRunning;
-        this.originalMetadata = originalMetadata;
-    }
-
-    public String getId() {
-        return id;
-    }
-
-    public String getName() {
-        return name;
-    }
-
-    public String getPrimaryIp() {
-        return primaryIp;
-    }
-
-    public Boolean isRunning() {
-        return isRunning;
-    }
-
-    public Object getOriginalMetadata() {
-        return originalMetadata;
-    }
-
-    @Override
-    public int hashCode() {
-        return Objects.hashCode(id, isRunning, name, originalMetadata, primaryIp);
-    }
-
-    @Override
-    public boolean equals(Object obj) {
-        if (this == obj) return true;
-        if (obj == null) return false;
-        if (getClass() != obj.getClass()) return false;
-        BasicMachineMetadata other = (BasicMachineMetadata) obj;
-        if (!Objects.equal(id, other.id)) return false;
-        if (!Objects.equal(name, other.name)) return false;
-        if (!Objects.equal(primaryIp, other.primaryIp)) return false;
-        if (!Objects.equal(isRunning, other.isRunning)) return false;
-        if (!Objects.equal(originalMetadata, other.originalMetadata)) return false;
-        return true;
-    }
-
-    @Override
-    public String toString() {
-        return Objects.toStringHelper(this).add("id", id).add("name", name).add("originalMetadata", originalMetadata).toString();
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/BasicOsDetails.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/BasicOsDetails.java b/core/src/main/java/org/apache/brooklyn/location/basic/BasicOsDetails.java
deleted file mode 100644
index 7ab72c7..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/BasicOsDetails.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.util.regex.Pattern;
-
-import javax.annotation.Nullable;
-import javax.annotation.concurrent.Immutable;
-
-import com.google.common.base.Objects;
-
-import org.apache.brooklyn.api.location.OsDetails;
-
-@Immutable
-public class BasicOsDetails implements OsDetails {
-
-    final String name, arch, version;
-    final boolean is64bit;
-    // (?i) forces matches to be case insensitive
-    public static final String UNIX_OS_NAME_PATTERNS = "(?i).*linux.*|centos|debian|fedora|gentoo|rhel|slackware|solaris|suse|ubuntu|coreos";
-
-    /** Sets is64Bit according to value of arch parameter. */
-    public BasicOsDetails(String name, String arch, String version) {
-       this(name, arch, version, arch != null && arch.contains("64"));
-    }
-
-    public BasicOsDetails(String name, String arch, String version, boolean is64Bit) {
-        this.name = name; this.arch = arch; this.version = version; this.is64bit = is64Bit;
-    }
-    
-    // TODO: Should be replaced with an enum like Jclouds' OsFamily and isX methods should
-    // switch against known cases
-    @Nullable
-    @Override
-    public String getName() {
-        return name;
-    }
-
-    @Nullable
-    @Override
-    public String getArch() {
-        return arch;
-    }
-
-    @Nullable
-    @Override
-    public String getVersion() {
-        return version;
-    }
-
-    @Override
-    public boolean isWindows() {
-        //TODO confirm
-        return getName()!=null && getName().toLowerCase().contains("microsoft");
-    }
-
-    @Override
-    public boolean isLinux() {
-        return getName() != null && Pattern.matches(UNIX_OS_NAME_PATTERNS, getName());
-    }
-
-    @Override
-    public boolean isMac() {
-        return getName()!=null && getName().equals(OsNames.MAC_OS_X);
-    }
-
-    @Override
-    public boolean is64bit() {
-        return is64bit;
-    }
-
-    @Override
-    public String toString() {
-        return Objects.toStringHelper(OsDetails.class)
-                .omitNullValues()
-                .add("name", name)
-                .add("version", version)
-                .add("arch", arch)
-                .toString();
-    }
-
-    public static class OsNames {
-        public static final String MAC_OS_X = "Mac OS X";
-    }
-    
-    public static class OsArchs {
-        public static final String X_86_64 = "x86_64";
-//        public static final String X_86 = "x86";
-//        // is this standard?  or do we ever need the above?
-        public static final String I386 = "i386";
-    }
-
-    public static class OsVersions {
-        public static final String MAC_10_8 = "10.8";
-        public static final String MAC_10_9 = "10.9";
-    }
-    
-    public static class Factory {
-        public static OsDetails newLocalhostInstance() {
-            return new BasicOsDetails(System.getProperty("os.name"), System.getProperty("os.arch"), System.getProperty("os.version"));
-        }
-        
-        public static final OsDetails ANONYMOUS_LINUX = new BasicOsDetails("linux", OsArchs.I386, "unknown");
-        public static final OsDetails ANONYMOUS_LINUX_64 = new BasicOsDetails("linux", OsArchs.X_86_64, "unknown");
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/ByonLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/ByonLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/basic/ByonLocationResolver.java
deleted file mode 100644
index 8a00cda..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/ByonLocationResolver.java
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static com.google.common.base.Preconditions.checkArgument;
-
-import java.net.InetAddress;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationRegistry;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.config.Sanitizer;
-import org.apache.brooklyn.core.mgmt.internal.LocalLocationManager;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.flags.TypeCoercions;
-import org.apache.brooklyn.util.net.UserAndHostAndPort;
-import org.apache.brooklyn.util.text.WildcardGlobs;
-import org.apache.brooklyn.util.text.WildcardGlobs.PhraseTreatment;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.net.HostAndPort;
-
-/**
- * Examples of valid specs:
- *   <ul>
- *     <li>byon:(hosts=myhost)
- *     <li>byon:(hosts=myhost,myhost2)
- *     <li>byon:(hosts="myhost, myhost2")
- *     <li>byon:(hosts=myhost,myhost2, name=abc)
- *     <li>byon:(hosts="myhost, myhost2", name="my location name")
- *   </ul>
- * 
- * @author aled
- */
-@SuppressWarnings({"rawtypes"})
-public class ByonLocationResolver extends AbstractLocationResolver {
-
-    public static final Logger log = LoggerFactory.getLogger(ByonLocationResolver.class);
-    
-    public static final String BYON = "byon";
-
-    public static final ConfigKey<String> OS_FAMILY = ConfigKeys.newStringConfigKey("osfamily", "OS Family of the machine, either windows or linux", "linux");
-
-    public static final Map<String, Class<? extends MachineLocation>> OS_TO_MACHINE_LOCATION_TYPE = ImmutableMap.<String, Class<? extends MachineLocation>>of(
-            "windows", WinRmMachineLocation.class,
-            "linux", SshMachineLocation.class);
-
-    @Override
-    public String getPrefix() {
-        return BYON;
-    }
-
-    @Override
-    protected Class<? extends Location> getLocationType() {
-        return FixedListMachineProvisioningLocation.class;
-    }
-
-    @Override
-    protected SpecParser getSpecParser() {
-        return new AbstractLocationResolver.SpecParser(getPrefix()).setExampleUsage("\"byon(hosts='addr1,addr2')\"");
-    }
-
-    @Override
-    protected ConfigBag extractConfig(Map<?,?> locationFlags, String spec, LocationRegistry registry) {
-        ConfigBag config = super.extractConfig(locationFlags, spec, registry);
-
-        Object hosts = config.getStringKey("hosts");
-        config.remove("hosts");
-        String user = (String) config.getStringKey("user");
-        Integer port = (Integer) TypeCoercions.coerce(config.getStringKey("port"), Integer.class);
-        Class<? extends MachineLocation> locationClass = OS_TO_MACHINE_LOCATION_TYPE.get(config.get(OS_FAMILY));
-
-        MutableMap<String, Object> defaultProps = MutableMap.of();
-        defaultProps.addIfNotNull("user", user);
-        defaultProps.addIfNotNull("port", port);
-
-        List<String> hostAddresses;
-        
-        if (hosts instanceof String) {
-            if (((String) hosts).isEmpty()) {
-                hostAddresses = ImmutableList.of();
-            } else {
-                hostAddresses = WildcardGlobs.getGlobsAfterBraceExpansion("{"+hosts+"}",
-                        true /* numeric */, /* no quote support though */ PhraseTreatment.NOT_A_SPECIAL_CHAR, PhraseTreatment.NOT_A_SPECIAL_CHAR);
-            }
-        } else if (hosts instanceof Iterable) {
-            hostAddresses = ImmutableList.copyOf((Iterable<String>)hosts);
-        } else {
-            throw new IllegalArgumentException("Invalid location '"+spec+"'; at least one host must be defined");
-        }
-        if (hostAddresses.isEmpty()) {
-            throw new IllegalArgumentException("Invalid location '"+spec+"'; at least one host must be defined");
-        }
-        
-        List<MachineLocation> machines = Lists.newArrayList();
-        for (Object host : hostAddresses) {
-            LocationSpec<? extends MachineLocation> machineSpec;
-            if (host instanceof String) {
-                machineSpec = parseMachine((String)host, locationClass, defaultProps, spec);
-            } else if (host instanceof Map) {
-                machineSpec = parseMachine((Map<String, ?>)host, locationClass, defaultProps, spec);
-            } else {
-                throw new IllegalArgumentException("Expected machine to be String or Map, but was "+host.getClass().getName()+" ("+host+")");
-            }
-            machineSpec.configureIfNotNull(LocalLocationManager.CREATE_UNMANAGED, config.get(LocalLocationManager.CREATE_UNMANAGED));
-            MachineLocation machine = managementContext.getLocationManager().createLocation(machineSpec);
-            machines.add(machine);
-        }
-        
-        config.putStringKey("machines", machines);
-
-        return config;
-    }
-    
-    protected LocationSpec<? extends MachineLocation> parseMachine(Map<String, ?> vals, Class<? extends MachineLocation> locationClass, Map<String, ?> defaults, String specForErrMsg) {
-        Map<String, Object> valSanitized = Sanitizer.sanitize(vals);
-        Map<String, Object> machineConfig = MutableMap.copyOf(vals);
-        
-        String osfamily = (String) machineConfig.remove(OS_FAMILY.getName());
-        String ssh = (String) machineConfig.remove("ssh");
-        String winrm = (String) machineConfig.remove("winrm");
-        Map<Integer, String> tcpPortMappings = (Map<Integer, String>) machineConfig.get("tcpPortMappings");
-        
-        checkArgument(ssh != null ^ winrm != null, "Must specify exactly one of 'ssh' or 'winrm' for machine: %s", valSanitized);
-        
-        UserAndHostAndPort userAndHostAndPort;
-        String host;
-        int port;
-        if (ssh != null) {
-            userAndHostAndPort = parseUserAndHostAndPort((String)ssh, 22);
-        } else {
-            userAndHostAndPort = parseUserAndHostAndPort((String)winrm, 5985);
-        }
-        
-        // If there is a tcpPortMapping defined for the connection-port, then use that for ssh/winrm machine
-        port = userAndHostAndPort.getHostAndPort().getPort();
-        if (tcpPortMappings != null && tcpPortMappings.containsKey(port)) {
-            String override = tcpPortMappings.get(port);
-            HostAndPort hostAndPortOverride = HostAndPort.fromString(override);
-            if (!hostAndPortOverride.hasPort()) {
-                throw new IllegalArgumentException("Invalid portMapping ('"+override+"') for port "+port+" in "+specForErrMsg);
-            }
-            port = hostAndPortOverride.getPort();
-            host = hostAndPortOverride.getHostText().trim();
-        } else {
-            host = userAndHostAndPort.getHostAndPort().getHostText().trim();
-        }
-        
-        machineConfig.put("address", host);
-        try {
-            InetAddress.getByName(host);
-        } catch (Exception e) {
-            throw new IllegalArgumentException("Invalid host '"+host+"' specified in '"+specForErrMsg+"': "+e);
-        }
-
-        if (userAndHostAndPort.getUser() != null) {
-            checkArgument(!vals.containsKey("user"), "Must not specify user twice for machine: %s", valSanitized);
-            machineConfig.put("user", userAndHostAndPort.getUser());
-        }
-        if (userAndHostAndPort.getHostAndPort().hasPort()) {
-            checkArgument(!vals.containsKey("port"), "Must not specify port twice for machine: %s", valSanitized);
-            machineConfig.put("port", port);
-        }
-        for (Map.Entry<String, ?> entry : defaults.entrySet()) {
-            if (!machineConfig.containsKey(entry.getKey())) {
-                machineConfig.put(entry.getKey(), entry.getValue());
-            }
-        }
-        
-        Class<? extends MachineLocation> locationClassHere = locationClass;
-        if (osfamily != null) {
-            locationClassHere = OS_TO_MACHINE_LOCATION_TYPE.get(osfamily);
-        }
-
-        return LocationSpec.create(locationClassHere).configure(machineConfig);
-    }
-
-    protected LocationSpec<? extends MachineLocation> parseMachine(String val, Class<? extends MachineLocation> locationClass, Map<String, ?> defaults, String specForErrMsg) {
-        Map<String, Object> machineConfig = Maps.newLinkedHashMap();
-        
-        UserAndHostAndPort userAndHostAndPort = parseUserAndHostAndPort(val);
-        
-        String host = userAndHostAndPort.getHostAndPort().getHostText().trim();
-        machineConfig.put("address", host);
-        try {
-            InetAddress.getByName(host.trim());
-        } catch (Exception e) {
-            throw new IllegalArgumentException("Invalid host '"+host+"' specified in '"+specForErrMsg+"': "+e);
-        }
-        
-        if (userAndHostAndPort.getUser() != null) {
-            machineConfig.put("user", userAndHostAndPort.getUser());
-        }
-        if (userAndHostAndPort.getHostAndPort().hasPort()) {
-            machineConfig.put("port", userAndHostAndPort.getHostAndPort().getPort());
-        }
-        for (Map.Entry<String, ?> entry : defaults.entrySet()) {
-            if (!machineConfig.containsKey(entry.getKey())) {
-                machineConfig.put(entry.getKey(), entry.getValue());
-            }
-        }
-
-        return LocationSpec.create(locationClass).configure(machineConfig);
-    }
-    
-    private UserAndHostAndPort parseUserAndHostAndPort(String val) {
-        String userPart = null;
-        String hostPart = val;
-        if (val.contains("@")) {
-            userPart = val.substring(0, val.indexOf("@"));
-            hostPart = val.substring(val.indexOf("@")+1);
-        }
-        return UserAndHostAndPort.fromParts(userPart, HostAndPort.fromString(hostPart));
-    }
-    
-    private UserAndHostAndPort parseUserAndHostAndPort(String val, int defaultPort) {
-        UserAndHostAndPort result = parseUserAndHostAndPort(val);
-        if (!result.getHostAndPort().hasPort()) {
-            result = UserAndHostAndPort.fromParts(result.getUser(), result.getHostAndPort().getHostText(), defaultPort);
-        }
-        return result;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/CatalogLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/CatalogLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/basic/CatalogLocationResolver.java
deleted file mode 100644
index 1b87398..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/CatalogLocationResolver.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.api.catalog.CatalogItem;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationRegistry;
-import org.apache.brooklyn.api.location.LocationResolver;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.catalog.internal.CatalogUtils;
-
-/**
- * Given a location spec in the form {@code brooklyn.catalog:<symbolicName>:<version>}, 
- * looks up the catalog to get its definition and creates such a location.
- */
-public class CatalogLocationResolver implements LocationResolver {
-
-    @SuppressWarnings("unused")
-    private static final Logger log = LoggerFactory.getLogger(CatalogLocationResolver.class);
-
-    public static final String NAME = "brooklyn.catalog";
-
-    private ManagementContext managementContext;
-
-    @Override
-    public void init(ManagementContext managementContext) {
-        this.managementContext = checkNotNull(managementContext, "managementContext");
-    }
-    
-    @Override
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
-        String id = spec.substring(NAME.length()+1);
-        CatalogItem<?, ?> item = CatalogUtils.getCatalogItemOptionalVersion(managementContext, id);
-        LocationSpec<?> origLocSpec = managementContext.getCatalog().createSpec((CatalogItem<Location, LocationSpec<?>>)item);
-        LocationSpec<?> locSpec = LocationSpec.create(origLocSpec)
-                .configure(locationFlags);
-        return managementContext.getLocationManager().createLocation(locSpec);
-    }
-
-    @Override
-    public String getPrefix() {
-        return NAME;
-    }
-    
-    /**
-     * accepts anything that looks like it will be a YAML catalog item (e.g. starting "brooklyn.locations")
-     */
-    @Override
-    public boolean accepts(String spec, LocationRegistry registry) {
-        if (BasicLocationRegistry.isResolverPrefixForSpec(this, spec, false)) return true;
-        if (registry.getDefinedLocationByName(spec)!=null) return true;
-        return false;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/DefinedLocationByIdResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/DefinedLocationByIdResolver.java b/core/src/main/java/org/apache/brooklyn/location/basic/DefinedLocationByIdResolver.java
deleted file mode 100644
index 3c4cec0..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/DefinedLocationByIdResolver.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationDefinition;
-import org.apache.brooklyn.api.location.LocationRegistry;
-import org.apache.brooklyn.api.location.LocationResolver;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * looks up based on ID in DefinedLocations map
- */
-public class DefinedLocationByIdResolver implements LocationResolver {
-
-    public static final Logger log = LoggerFactory.getLogger(DefinedLocationByIdResolver.class);
-
-    public static final String ID = "id";
-    
-    private volatile ManagementContext managementContext;
-
-    @Override
-    public void init(ManagementContext managementContext) {
-        this.managementContext = checkNotNull(managementContext, "managementContext");
-    }
-    
-    @SuppressWarnings({ "rawtypes" })
-    @Override
-    public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
-        String id = spec;
-        if (spec.toLowerCase().startsWith(ID+":")) {
-            id = spec.substring( (ID+":").length() );
-        }
-        LocationDefinition ld = registry.getDefinedLocationById(id);
-        ld.getSpec();
-        return ((BasicLocationRegistry)registry).resolveLocationDefinition(ld, locationFlags, null);
-    }
-
-    @Override
-    public String getPrefix() {
-        return ID;
-    }
-    
-    /** accepts anything starting  id:xxx  or just   xxx where xxx is a defined location ID */
-    @Override
-    public boolean accepts(String spec, LocationRegistry registry) {
-        if (BasicLocationRegistry.isResolverPrefixForSpec(this, spec, false)) return true;
-        if (registry.getDefinedLocationById(spec)!=null) return true;
-        return false;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/DeprecatedKeysMappingBuilder.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/DeprecatedKeysMappingBuilder.java b/core/src/main/java/org/apache/brooklyn/location/basic/DeprecatedKeysMappingBuilder.java
deleted file mode 100644
index a165086..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/DeprecatedKeysMappingBuilder.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.util.Map;
-
-import org.apache.brooklyn.config.ConfigKey;
-import org.slf4j.Logger;
-
-import com.google.common.base.CaseFormat;
-import com.google.common.collect.ImmutableMap;
-
-/**
-* @deprecated since 0.6; for use only in converting deprecated flags; will be deleted in future version.
-*/
-public class DeprecatedKeysMappingBuilder {
-    private final ImmutableMap.Builder<String,String> builder = new ImmutableMap.Builder<String,String>();
-    private final Logger logger;
-    
-    public DeprecatedKeysMappingBuilder(Logger logger) {
-        this.logger = logger;
-    }
-
-    public DeprecatedKeysMappingBuilder camelToHyphen(ConfigKey<?> key) {
-        return camelToHyphen(key.getName());
-    }
-    
-    public DeprecatedKeysMappingBuilder camelToHyphen(String key) {
-        String hyphen = toHyphen(key);
-        if (key.equals(hyphen)) {
-            logger.warn("Invalid attempt to convert camel-case key {} to deprecated hyphen-case: both the same", hyphen);
-        } else {
-            builder.put(hyphen, key);
-        }
-        return this;
-    }
-    
-    public DeprecatedKeysMappingBuilder putAll(Map<String,String> vals) {
-        builder.putAll(vals);
-        return this;
-    }
-
-    public Map<String,String> build() {
-        return builder.build();
-    }
-    
-    private String toHyphen(String word) {
-        return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, word);
-    }
-}


[59/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/SshMachineLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/SshMachineLocation.java b/core/src/main/java/org/apache/brooklyn/location/basic/SshMachineLocation.java
deleted file mode 100644
index 53406b1..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/SshMachineLocation.java
+++ /dev/null
@@ -1,1032 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.apache.brooklyn.util.GroovyJavaMethods.truth;
-
-import java.io.Closeable;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PipedInputStream;
-import java.io.PipedOutputStream;
-import java.io.Reader;
-import java.io.StringReader;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.security.KeyPair;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.location.MachineDetails;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.OsDetails;
-import org.apache.brooklyn.api.location.PortRange;
-import org.apache.brooklyn.api.location.PortSupplier;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.config.ConfigKey.HasConfigKey;
-import org.apache.brooklyn.core.BrooklynLogging;
-import org.apache.brooklyn.core.config.BasicConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.config.ConfigUtils;
-import org.apache.brooklyn.core.config.MapConfigKey;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Function;
-import com.google.common.base.Objects;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
-import com.google.common.base.Supplier;
-import com.google.common.base.Throwables;
-import com.google.common.cache.CacheBuilder;
-import com.google.common.cache.CacheLoader;
-import com.google.common.cache.LoadingCache;
-import com.google.common.cache.RemovalListener;
-import com.google.common.cache.RemovalNotification;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-import com.google.common.net.HostAndPort;
-import com.google.common.reflect.TypeToken;
-
-import org.apache.brooklyn.location.access.PortForwardManager;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.ResourceUtils;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.crypto.SecureKeys;
-import org.apache.brooklyn.util.core.file.ArchiveUtils;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.apache.brooklyn.util.core.flags.TypeCoercions;
-import org.apache.brooklyn.util.core.internal.ssh.ShellTool;
-import org.apache.brooklyn.util.core.internal.ssh.SshException;
-import org.apache.brooklyn.util.core.internal.ssh.SshTool;
-import org.apache.brooklyn.util.core.internal.ssh.sshj.SshjTool;
-import org.apache.brooklyn.util.core.mutex.MutexSupport;
-import org.apache.brooklyn.util.core.mutex.WithMutexes;
-import org.apache.brooklyn.util.core.task.ScheduledTask;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.core.task.system.internal.ExecWithLoggingHelpers;
-import org.apache.brooklyn.util.core.task.system.internal.ExecWithLoggingHelpers.ExecRunner;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.exceptions.RuntimeInterruptedException;
-import org.apache.brooklyn.util.guava.KeyTransformingLoadingCache.KeyTransformingSameTypeLoadingCache;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.brooklyn.util.pool.BasicPool;
-import org.apache.brooklyn.util.pool.Pool;
-import org.apache.brooklyn.util.ssh.BashCommands;
-import org.apache.brooklyn.util.stream.KnownSizeInputStream;
-import org.apache.brooklyn.util.stream.ReaderInputStream;
-import org.apache.brooklyn.util.stream.StreamGobbler;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.time.Duration;
-
-import groovy.lang.Closure;
-
-/**
- * Operations on a machine that is accessible via ssh.
- * <p>
- * We expose two ways of running scripts.
- * The execCommands method passes lines to bash and is lightweight but fragile.
- * The execScript method creates a script on the remote machine. It is portable but heavier.
- * <p>
- * Additionally there are routines to copyTo, copyFrom; and installTo (which tries a curl, and falls back to copyTo
- * in event the source is accessible by the caller only).
- */
-public class SshMachineLocation extends AbstractLocation implements MachineLocation, PortSupplier, WithMutexes, Closeable {
-
-    /** @deprecated since 0.7.0 shouldn't be public */
-    public static final Logger LOG = LoggerFactory.getLogger(SshMachineLocation.class);
-    /** @deprecated since 0.7.0 shouldn't be public */
-    public static final Logger logSsh = LoggerFactory.getLogger(BrooklynLogging.SSH_IO);
-    
-    // Use a sane timeout when doing a connectivity test
-    private static final int SSHABLE_CONNECT_TIMEOUT = (int)Duration.minutes(2).toMilliseconds();
-
-    public static final ConfigKey<Duration> SSH_CACHE_EXPIRY_DURATION = ConfigKeys.newConfigKey(Duration.class,
-            "sshCacheExpiryDuration", "Expiry time for unused cached ssh connections", Duration.FIVE_MINUTES);
-
-    public static final ConfigKey<MachineDetails> MACHINE_DETAILS = ConfigKeys.newConfigKey(
-            MachineDetails.class,
-            "machineDetails");
-
-    public static final ConfigKey<Boolean> DETECT_MACHINE_DETAILS = ConfigKeys.newBooleanConfigKey("detectMachineDetails",
-            "Attempt to detect machine details automatically. Works with SSH-accessible Linux instances.", true);
-
-    public static final ConfigKey<Iterable<String>> PRIVATE_ADDRESSES = ConfigKeys.newConfigKey(
-            new TypeToken<Iterable<String>>() {},
-            "privateAddresses",
-            "Private addresses of this machine, e.g. those within the private network", 
-            null);
-
-    public static final ConfigKey<Map<Integer, String>> TCP_PORT_MAPPINGS = ConfigKeys.newConfigKey(
-            new TypeToken<Map<Integer, String>>() {},
-            "tcpPortMappings",
-            "NAT'ed ports, giving the mapping from private TCP port to a public host:port", 
-            null);
-
-    @SetFromFlag
-    protected String user;
-
-    @SetFromFlag(nullable = false)
-    protected InetAddress address;
-
-    // TODO should not allow this to be set from flag; it is not persisted so that will be lost
-    // (mainly used for localhost currently so not a big problem)
-    @Nullable  // lazily initialized; use getMutexSupport()
-    @SetFromFlag
-    private transient WithMutexes mutexSupport;
-
-    @SetFromFlag
-    private Set<Integer> usedPorts;
-
-    private volatile MachineDetails machineDetails;
-    private final Object machineDetailsLock = new Object();
-
-    public static final ConfigKey<String> SSH_HOST = BrooklynConfigKeys.SSH_CONFIG_HOST;
-    public static final ConfigKey<Integer> SSH_PORT = BrooklynConfigKeys.SSH_CONFIG_PORT;
-
-    public static final ConfigKey<String> SSH_EXECUTABLE = ConfigKeys.newStringConfigKey("sshExecutable",
-            "Allows an `ssh` executable file to be specified, to be used in place of the default (programmatic) java ssh client");
-    public static final ConfigKey<String> SCP_EXECUTABLE = ConfigKeys.newStringConfigKey("scpExecutable",
-            "Allows an `scp` executable file to be specified, to be used in place of the default (programmatic) java ssh client");
-
-    // TODO remove
-    public static final ConfigKey<String> PASSWORD = SshTool.PROP_PASSWORD;
-    public static final ConfigKey<String> PRIVATE_KEY_FILE = SshTool.PROP_PRIVATE_KEY_FILE;
-    public static final ConfigKey<String> PRIVATE_KEY_DATA = SshTool.PROP_PRIVATE_KEY_DATA;
-    public static final ConfigKey<String> PRIVATE_KEY_PASSPHRASE = SshTool.PROP_PRIVATE_KEY_PASSPHRASE;
-
-    public static final ConfigKey<String> SCRIPT_DIR = ConfigKeys.newStringConfigKey(
-            "scriptDir", "directory where scripts should be placed and executed on the SSH target machine");
-    public static final ConfigKey<Map<String,Object>> SSH_ENV_MAP = new MapConfigKey<Object>(
-            Object.class, "env", "environment variables to pass to the remote SSH shell session");
-
-    public static final ConfigKey<Boolean> ALLOCATE_PTY = SshTool.PROP_ALLOCATE_PTY;
-
-    public static final ConfigKey<OutputStream> STDOUT = new BasicConfigKey<OutputStream>(OutputStream.class, "out");
-    public static final ConfigKey<OutputStream> STDERR = new BasicConfigKey<OutputStream>(OutputStream.class, "err");
-    public static final ConfigKey<Boolean> NO_STDOUT_LOGGING = ConfigKeys.newBooleanConfigKey(
-            "noStdoutLogging", "whether to disable logging of stdout from SSH commands (e.g. for verbose commands)", false);
-    public static final ConfigKey<Boolean> NO_STDERR_LOGGING = ConfigKeys.newBooleanConfigKey(
-            "noStderrLogging", "whether to disable logging of stderr from SSH commands (e.g. for verbose commands)", false);
-    public static final ConfigKey<String> LOG_PREFIX = ConfigKeys.newStringConfigKey("logPrefix");
-
-    public static final ConfigKey<String> LOCAL_TEMP_DIR = SshTool.PROP_LOCAL_TEMP_DIR;
-
-    public static final ConfigKey<Boolean> CLOSE_CONNECTION = ConfigKeys.newBooleanConfigKey("close", "Close the SSH connection after use", false);
-    public static final ConfigKey<String> UNIQUE_ID = ConfigKeys.newStringConfigKey("unique", "Unique ID for the SSH connection");
-
-    /**
-     * Specifies config keys where a change in the value does not require a new SshTool instance,
-     * i.e. they can be specified per command on the tool
-     */
-    // TODO: Fully specify.
-    public static final Set<ConfigKey<?>> REUSABLE_SSH_PROPS = ImmutableSet.of(
-            STDOUT, STDERR, SCRIPT_DIR, CLOSE_CONNECTION,
-            SshTool.PROP_SCRIPT_HEADER, SshTool.PROP_PERMISSIONS, SshTool.PROP_LAST_MODIFICATION_DATE,
-            SshTool.PROP_LAST_ACCESS_DATE, SshTool.PROP_OWNER_UID, SshTool.PROP_SSH_RETRY_DELAY);
-
-    public static final Set<HasConfigKey<?>> ALL_SSH_CONFIG_KEYS =
-            ImmutableSet.<HasConfigKey<?>>builder()
-                    .addAll(ConfigUtils.getStaticKeysOnClass(SshMachineLocation.class))
-                    .addAll(ConfigUtils.getStaticKeysOnClass(SshTool.class))
-                    .build();
-
-    public static final Set<String> ALL_SSH_CONFIG_KEY_NAMES =
-            ImmutableSet.copyOf(Iterables.transform(ALL_SSH_CONFIG_KEYS, new Function<HasConfigKey<?>,String>() {
-                @Override
-                public String apply(HasConfigKey<?> input) {
-                    return input.getConfigKey().getName();
-                }
-            }));
-
-    /**
-     * The set of config keys on this location which become default values for properties when invoking an SSH
-     * operation.
-     */
-    @Beta
-    public static final Set<ConfigKey<?>> SSH_CONFIG_GIVEN_TO_PROPS = ImmutableSet.<ConfigKey<?>>of(
-            SCRIPT_DIR);
-
-    private Task<?> cleanupTask;
-    /** callers should use {@link #getSshPoolCache()} */
-    @Nullable 
-    private transient LoadingCache<Map<String, ?>, Pool<SshTool>> sshPoolCacheOrNull;
-
-    public SshMachineLocation() {
-        this(MutableMap.of());
-    }
-
-    public SshMachineLocation(Map properties) {
-        super(properties);
-        usedPorts = (usedPorts != null) ? Sets.newLinkedHashSet(usedPorts) : Sets.<Integer>newLinkedHashSet();
-    }
-
-    @Override
-    public void init() {
-        super.init();
-
-        // Register any pre-existing port-mappings with the PortForwardManager
-        Map<Integer, String> tcpPortMappings = getConfig(TCP_PORT_MAPPINGS);
-        if (tcpPortMappings != null) {
-            PortForwardManager pfm = (PortForwardManager) getManagementContext().getLocationRegistry().resolve("portForwardManager(scope=global)");
-            for (Map.Entry<Integer, String> entry : tcpPortMappings.entrySet()) {
-                int targetPort = entry.getKey();
-                HostAndPort publicEndpoint = HostAndPort.fromString(entry.getValue());
-                if (!publicEndpoint.hasPort()) {
-                    throw new IllegalArgumentException("Invalid portMapping ('"+entry.getValue()+"') for port "+targetPort+" in machine "+this);
-                }
-                pfm.associate(publicEndpoint.getHostText(), publicEndpoint, this, targetPort);
-            }
-        }
-    }
-    
-    private final transient Object poolCacheMutex = new Object();
-    @Nonnull
-    private LoadingCache<Map<String, ?>, Pool<SshTool>> getSshPoolCache() {
-        synchronized (poolCacheMutex) {
-            if (sshPoolCacheOrNull==null) {
-                sshPoolCacheOrNull = buildSshToolPoolCacheLoader();
-                addSshPoolCacheCleanupTask();
-            }
-        }
-        return sshPoolCacheOrNull;
-    }
-
-    private LoadingCache<Map<String, ?>, Pool<SshTool>> buildSshToolPoolCacheLoader() {
-        // TODO: Appropriate numbers for maximum size and expire after access
-        // At the moment every SshMachineLocation instance creates its own pool.
-        // It might make more sense to create one pool and inject it into all SshMachineLocations.
-        Duration expiryDuration = getConfig(SSH_CACHE_EXPIRY_DURATION);
-        
-        LoadingCache<Map<String, ?>, Pool<SshTool>> delegate = CacheBuilder.newBuilder()
-                .maximumSize(10)
-                .expireAfterAccess(expiryDuration.toMilliseconds(), TimeUnit.MILLISECONDS)
-                .recordStats()
-                .removalListener(new RemovalListener<Map<String, ?>, Pool<SshTool>>() {
-                    // TODO: Does it matter that this is synchronous? - Can closing pools cause long delays?
-                    @Override
-                    public void onRemoval(RemovalNotification<Map<String, ?>, Pool<SshTool>> notification) {
-                        Pool<SshTool> removed = notification.getValue();
-                        if (removed == null) {
-                            if (LOG.isDebugEnabled()) {
-                                LOG.debug("Pool evicted from SshTool cache is null so we can't call pool.close(). " +
-                                        "It's probably already been garbage collected. Eviction cause: {} ",
-                                        notification.getCause().name());
-                            }
-                        } else {
-                            if (LOG.isDebugEnabled()) {
-                                LOG.debug("{} evicted from SshTool cache. Eviction cause: {}",
-                                        removed, notification.getCause().name());
-                            }
-                            try {
-                                removed.close();
-                            } catch (IOException e) {
-                                if (LOG.isDebugEnabled()) {
-                                    LOG.debug("Exception closing "+removed, e);
-                                }
-                            }
-                        }
-                    }
-                })
-                .build(new CacheLoader<Map<String, ?>, Pool<SshTool>>() {
-                    public Pool<SshTool> load(Map<String, ?> properties) {
-                        if (LOG.isDebugEnabled()) {
-                            LOG.debug("{} building ssh pool for {} with properties: {}",
-                                    new Object[] {this, getSshHostAndPort(), properties});
-                        }
-                        return buildPool(properties);
-                    }
-                });
-
-        final Set<String> reusableSshProperties = ImmutableSet.copyOf(
-                Iterables.transform(REUSABLE_SSH_PROPS, new Function<ConfigKey<?>, String>() {
-                    @Override public String apply(ConfigKey<?> input) {
-                        return input.getName();
-                    }
-                }));
-        // Groovy-eclipse compiler refused to compile `KeyTransformingSameTypeLoadingCache.from(...)`
-        return new KeyTransformingSameTypeLoadingCache<Map<String, ?>, Pool<SshTool>>(
-                delegate,
-                new Function<Map<String, ?>, Map<String, ?>>() {
-                    @Override
-                    public Map<String, ?> apply(@Nullable Map<String, ?> input) {
-                        Map<String, Object> copy = new HashMap<String, Object>(input);
-                        copy.keySet().removeAll(reusableSshProperties);
-                        return copy;
-                    }
-                });
-    }
-
-    private BasicPool<SshTool> buildPool(final Map<String, ?> properties) {
-        return BasicPool.<SshTool>builder()
-                .name(getDisplayName()+"@"+address+":"+getPort()+
-                        (config().getRaw(SSH_HOST).isPresent() ? "("+getConfig(SSH_HOST)+":"+getConfig(SSH_PORT)+")" : "")+
-                        ":hash"+System.identityHashCode(this))
-                .supplier(new Supplier<SshTool>() {
-                        @Override public SshTool get() {
-                            return connectSsh(properties);
-                        }})
-                .viabilityChecker(new Predicate<SshTool>() {
-                        @Override public boolean apply(SshTool input) {
-                            return input != null && input.isConnected();
-                        }})
-                .closer(new Function<SshTool,Void>() {
-                        @Override public Void apply(SshTool input) {
-                            if (LOG.isDebugEnabled()) {
-                                LOG.debug("{} closing pool for {}", this, input);
-                            }
-                            try {
-                                input.disconnect();
-                            } catch (Exception e) {
-                                if (logSsh.isDebugEnabled()) logSsh.debug("On machine "+SshMachineLocation.this+", ssh-disconnect failed", e);
-                            }
-                            return null;
-                        }})
-                .build();
-    }
-
-    @Override
-    public SshMachineLocation configure(Map<?,?> properties) {
-        super.configure(properties);
-
-        // TODO Note that check for addresss!=null is done automatically in super-constructor, in FlagUtils.checkRequiredFields
-        // Yikes, dangerous code for accessing fields of sub-class in super-class' constructor! But getting away with it so far!
-
-        boolean deferConstructionChecks = (properties.containsKey("deferConstructionChecks") && TypeCoercions.coerce(properties.get("deferConstructionChecks"), Boolean.class));
-        if (!deferConstructionChecks) {
-            if (getDisplayName() == null) {
-                setDisplayName((truth(user) ? user+"@" : "") + address.getHostName());
-            }
-        }
-        return this;
-    }
-    
-    private transient final Object mutexSupportCreationLock = new Object();
-    protected WithMutexes getMutexSupport() {
-        synchronized (mutexSupportCreationLock) {
-            // create on demand so that it is not null after serialization
-            if (mutexSupport == null) {
-                mutexSupport = new MutexSupport();
-            }
-            return mutexSupport;
-        }
-    }
-    
-    protected void addSshPoolCacheCleanupTask() {
-        if (cleanupTask!=null && !cleanupTask.isDone()) {
-            return;
-        }
-        if (getManagementContext()==null || getManagementContext().getExecutionManager()==null) {
-            LOG.debug("No management context for "+this+"; ssh-pool cache will only be closed when machine is closed");
-            return;
-        }
-        
-        Callable<Task<?>> cleanupTaskFactory = new Callable<Task<?>>() {
-            @Override public Task<Void> call() {
-                return Tasks.<Void>builder().dynamic(false).tag(BrooklynTaskTags.TRANSIENT_TASK_TAG)
-                    .name("ssh-location cache cleaner").body(new Callable<Void>() {
-                    @Override public Void call() {
-                        try {
-                            if (sshPoolCacheOrNull != null) sshPoolCacheOrNull.cleanUp();
-                            if (!SshMachineLocation.this.isManaged()) {
-                                if (sshPoolCacheOrNull != null) sshPoolCacheOrNull.invalidateAll();
-                                cleanupTask.cancel(false);
-                                sshPoolCacheOrNull = null;
-                            }
-                            return null;
-                        } catch (Exception e) {
-                            // Don't rethrow: the behaviour of executionManager is different from a scheduledExecutorService,
-                            // if we throw an exception, then our task will never get executed again
-                            LOG.warn("Problem cleaning up ssh-pool-cache", e);
-                            return null;
-                        } catch (Throwable t) {
-                            LOG.warn("Problem cleaning up ssh-pool-cache (rethrowing)", t);
-                            throw Exceptions.propagate(t);
-                        }
-                    }}).build();
-            }
-        };
-        
-        Duration expiryDuration = getConfig(SSH_CACHE_EXPIRY_DURATION);
-        cleanupTask = getManagementContext().getExecutionManager().submit(new ScheduledTask(
-            MutableMap.of("displayName", "scheduled[ssh-location cache cleaner]"), cleanupTaskFactory).period(expiryDuration));
-    }
-    
-    // TODO close has been used for a long time to perform clean-up wanted on unmanagement, but that's not clear; 
-    // we should probably expose a mechanism such as that in Entity (or re-use Entity for locations!)
-    @Override
-    public void close() throws IOException {
-        if (sshPoolCacheOrNull != null) {
-            if (LOG.isDebugEnabled()) {
-                LOG.debug("{} invalidating all entries in ssh pool cache. Final stats: {}", this, sshPoolCacheOrNull.stats());
-            }
-            sshPoolCacheOrNull.invalidateAll();
-        }
-        if (cleanupTask != null) {
-            cleanupTask.cancel(false);
-            cleanupTask = null;
-            sshPoolCacheOrNull = null;
-        }
-    }
-
-    // should not be necessary, and causes objects to be kept around a lot longer than desired
-//    @Override
-//    protected void finalize() throws Throwable {
-//        try {
-//            close();
-//        } finally {
-//            super.finalize();
-//        }
-//    }
-
-    @Override
-    public InetAddress getAddress() {
-        return address;
-    }
-
-    @Override
-    public String getHostname() {
-        String hostname = address.getHostName();
-        return (hostname == null || hostname.equals(address.getHostAddress())) ? null : hostname;
-    }
-    
-    @Override
-    public Set<String> getPublicAddresses() {
-        return ImmutableSet.of(address.getHostAddress());
-    }
-    
-    @Override
-    public Set<String> getPrivateAddresses() {
-        Iterable<String> result = getConfig(PRIVATE_ADDRESSES);
-        return (result == null) ? ImmutableSet.<String>of() : ImmutableSet.copyOf(result);
-    }
-
-    public HostAndPort getSshHostAndPort() {
-        String host = getConfig(SSH_HOST);
-        if (host == null || Strings.isEmpty(host))
-            host = address.getHostName();
-        Integer port = getConfig(SSH_PORT);
-        if (port == null || port == 0)
-            port = 22;
-        return HostAndPort.fromParts(host, port);
-    }
-
-    public String getUser() {
-        if (!truth(user)) {
-            if (config().getLocalRaw(SshTool.PROP_USER).isPresent()) {
-                LOG.warn("User configuration for "+this+" set after deployment; deprecated behaviour may not be supported in future versions");
-            }
-            return getConfig(SshTool.PROP_USER);
-        }
-        return user;
-    }
-
-    /** port for SSHing */
-    public int getPort() {
-        return getConfig(SshTool.PROP_PORT);
-    }
-
-    protected <T> T execSsh(final Map<String, ?> props, final Function<ShellTool, T> task) {
-        final LoadingCache<Map<String, ?>, Pool<SshTool>> sshPoolCache = getSshPoolCache();
-        Pool<SshTool> pool = sshPoolCache.getUnchecked(props);
-        if (LOG.isTraceEnabled()) {
-            LOG.trace("{} execSsh got pool: {}", this, pool);
-        }
-
-        if (truth(props.get(CLOSE_CONNECTION.getName()))) {
-            Function<SshTool, T> close = new Function<SshTool, T>() {
-                @Override
-                public T apply(SshTool input) {
-                    T result = task.apply(input);
-                    if (LOG.isDebugEnabled()) {
-                        LOG.debug("{} invalidating all sshPoolCache entries: {}", SshMachineLocation.this, sshPoolCache.stats().toString());
-                    }
-                    sshPoolCache.invalidateAll();
-                    sshPoolCache.cleanUp();
-                    return result;
-                }
-            };
-            return pool.exec(close);
-        } else {
-            return pool.exec(task);
-        }
-    }
-
-    protected SshTool connectSsh() {
-        return connectSsh(ImmutableMap.of());
-    }
-
-    protected boolean previouslyConnected = false;
-    protected SshTool connectSsh(Map props) {
-        try {
-            if (!truth(user)) {
-                String newUser = getUser();
-                if (LOG.isTraceEnabled()) LOG.trace("For "+this+", setting user in connectSsh: oldUser="+user+"; newUser="+newUser);
-                user = newUser;
-            }
-
-            ConfigBag args = new ConfigBag()
-                .configure(SshTool.PROP_USER, user)
-                // default value of host, overridden if SSH_HOST is supplied
-                .configure(SshTool.PROP_HOST, address.getHostName());
-
-            for (Map.Entry<String,Object> entry: config().getBag().getAllConfig().entrySet()) {
-                String key = entry.getKey();
-                if (key.startsWith(SshTool.BROOKLYN_CONFIG_KEY_PREFIX)) {
-                    key = Strings.removeFromStart(key, SshTool.BROOKLYN_CONFIG_KEY_PREFIX);
-                } else if (ALL_SSH_CONFIG_KEY_NAMES.contains(entry.getKey())) {
-                    // key should be included, and does not need to be changed
-
-                    // TODO make this config-setting mechanism more universal
-                    // currently e.g. it will not admit a tool-specific property.
-                    // thinking either we know about the tool here,
-                    // or we don't allow unadorned keys to be set
-                    // (require use of BROOKLYN_CONFIG_KEY_PREFIX)
-                } else {
-                    // this key is not applicable here; ignore it
-                    continue;
-                }
-                args.putStringKey(key, entry.getValue());
-            }
-
-            // Explicit props trump all.
-            args.putAll(props);
-
-            if (LOG.isTraceEnabled()) LOG.trace("creating ssh session for "+args);
-            if (!user.equals(args.get(SshTool.PROP_USER))) {
-                LOG.warn("User mismatch configuring ssh for "+this+": preferring user "+args.get(SshTool.PROP_USER)+" over "+user);
-                user = args.get(SshTool.PROP_USER);
-            }
-
-            // look up tool class
-            String sshToolClass = args.get(SshTool.PROP_TOOL_CLASS);
-            if (sshToolClass==null) sshToolClass = SshjTool.class.getName();
-            SshTool ssh = (SshTool) Class.forName(sshToolClass).getConstructor(Map.class).newInstance(args.getAllConfig());
-
-            if (LOG.isTraceEnabled()) LOG.trace("using ssh-tool {} (of type {}); props ", ssh, sshToolClass);
-
-            Tasks.setBlockingDetails("Opening ssh connection");
-            try { ssh.connect(); } finally { Tasks.setBlockingDetails(null); }
-            previouslyConnected = true;
-            return ssh;
-        } catch (Exception e) {
-            if (previouslyConnected) throw Throwables.propagate(e);
-            // subsequence connection (above) most likely network failure, our remarks below won't help
-            // on first connection include additional information if we can't connect, to help with debugging
-            String rootCause = Throwables.getRootCause(e).getMessage();
-            throw new IllegalStateException("Cannot establish ssh connection to "+user+" @ "+this+
-                    (rootCause!=null && !rootCause.isEmpty() ? " ("+rootCause+")" : "")+". \n"+
-                    "Ensure that passwordless and passphraseless ssh access is enabled using standard keys from ~/.ssh or " +
-                    "as configured in brooklyn.properties. " +
-                    "Check that the target host is accessible, " +
-                    "that credentials are correct (location and permissions if using a key), " +
-                    "that the SFTP subsystem is available on the remote side, " +
-                    "and that there is sufficient random noise in /dev/random on both ends. " +
-                    "To debug less common causes, see the original error in the trace or log, and/or enable 'net.schmizz' (sshj) logging."
-                    , e);
-        }
-    }
-
-    // TODO submitCommands and submitScript which submit objects we can subsequently poll (cf JcloudsSshMachineLocation.submitRunScript)
-
-    /**
-     * Executes a set of commands, directly on the target machine (no wrapping in script).
-     * Joined using {@literal ;} by default.
-     * <p>
-     * Stdout and stderr will be logged automatically to brooklyn.SSH logger, unless the
-     * flags 'noStdoutLogging' and 'noStderrLogging' are set. To set a logging prefix, use
-     * the flag 'logPrefix'.
-     * <p>
-     * Currently runs the commands in an interactive/login shell
-     * by passing each as a line to bash. To terminate early, use:
-     * <pre>
-     * foo || exit 1
-     * </pre>
-     * It may be desirable instead, in some situations, to wrap as:
-     * <pre>
-     * { line1 ; } && { line2 ; } ...
-     * </pre>
-     * and run as a single command (possibly not as an interacitve/login
-     * shell) causing the script to exit on the first command which fails.
-     * <p>
-     * Currently this has to be done by the caller.
-     * (If desired we can add a flag {@code exitIfAnyNonZero} to support this mode,
-     * and/or {@code commandPrepend} and {@code commandAppend} similar to
-     * (currently supported in SshjTool) {@code separator}.)
-     */
-    public int execCommands(String summaryForLogging, List<String> commands) {
-        return execCommands(MutableMap.<String,Object>of(), summaryForLogging, commands, MutableMap.<String,Object>of());
-    }
-    public int execCommands(Map<String,?> props, String summaryForLogging, List<String> commands) {
-        return execCommands(props, summaryForLogging, commands, MutableMap.<String,Object>of());
-    }
-    public int execCommands(String summaryForLogging, List<String> commands, Map<String,?> env) {
-        return execCommands(MutableMap.<String,Object>of(), summaryForLogging, commands, env);
-    }
-    public int execCommands(Map<String,?> props, String summaryForLogging, List<String> commands, Map<String,?> env) {
-        return newExecWithLoggingHelpers().execCommands(augmentPropertiesWithSshConfigGivenToProps(props), summaryForLogging, commands, env);
-    }
-
-    /**
-     * Executes a set of commands, wrapped as a script sent to the remote machine.
-     * <p>
-     * Stdout and stderr will be logged automatically to brooklyn.SSH logger, unless the
-     * flags 'noStdoutLogging' and 'noStderrLogging' are set. To set a logging prefix, use
-     * the flag 'logPrefix'.
-     */
-    public int execScript(String summaryForLogging, List<String> commands) {
-        return execScript(MutableMap.<String,Object>of(), summaryForLogging, commands, MutableMap.<String,Object>of());
-    }
-    public int execScript(Map<String,?> props, String summaryForLogging, List<String> commands) {
-        return execScript(props, summaryForLogging, commands, MutableMap.<String,Object>of());
-    }
-    public int execScript(String summaryForLogging, List<String> commands, Map<String,?> env) {
-        return execScript(MutableMap.<String,Object>of(), summaryForLogging, commands, env);
-    }
-    public int execScript(Map<String,?> props, String summaryForLogging, List<String> commands, Map<String,?> env) {
-        return newExecWithLoggingHelpers().execScript(augmentPropertiesWithSshConfigGivenToProps(props), summaryForLogging, commands, env);
-    }
-
-    private Map<String, Object> augmentPropertiesWithSshConfigGivenToProps(Map<String, ?> props) {
-        Map<String,Object> augmentedProps = Maps.newHashMap(props);
-        for (ConfigKey<?> config : SSH_CONFIG_GIVEN_TO_PROPS) {
-            if (!augmentedProps.containsKey(config.getName()) && hasConfig(config, true))
-                augmentedProps.put(config.getName(), getConfig(config));
-        }
-        return augmentedProps;
-    }
-
-    protected ExecWithLoggingHelpers newExecWithLoggingHelpers() {
-        return new ExecWithLoggingHelpers("SSH") {
-            @Override
-            protected <T> T execWithTool(MutableMap<String, Object> props, Function<ShellTool, T> function) {
-                return execSsh(props, function);
-            }
-            @Override
-            protected void preExecChecks() {
-                Preconditions.checkNotNull(address, "host address must be specified for ssh");
-            }
-            @Override
-            protected String constructDefaultLoggingPrefix(ConfigBag execFlags) {
-                String hostname = getAddress().getHostName();
-                Integer port = execFlags.peek(SshTool.PROP_PORT);
-                if (port == null) port = getConfig(ConfigUtils.prefixedKey(SshTool.BROOKLYN_CONFIG_KEY_PREFIX, SshTool.PROP_PORT));
-                return (user != null ? user+"@" : "") + hostname + (port != null ? ":"+port : "");
-            }
-            @Override
-            protected String getTargetName() {
-                return ""+SshMachineLocation.this;
-            }
-        }.logger(logSsh);
-    }
-
-    /**
-     * @deprecated since 0.7.0; use {@link #execCommands(Map, String, List, Map), and rely on that calling the execWithLogging
-     */
-    @SuppressWarnings({"rawtypes", "unchecked"})
-    @Deprecated
-    protected int execWithLogging(Map<String,?> props, String summaryForLogging, List<String> commands, Map env, final Closure<Integer> execCommand) {
-        return newExecWithLoggingHelpers().execWithLogging(props, summaryForLogging, commands, env, new ExecRunner() {
-                @Override public int exec(ShellTool ssh, Map<String, ?> flags, List<String> cmds, Map<String, ?> env) {
-                    return execCommand.call(ssh, flags, cmds, env);
-                }});
-    }
-
-    public int copyTo(File src, File destination) {
-        return copyTo(MutableMap.<String,Object>of(), src, destination);
-    }
-    public int copyTo(Map<String,?> props, File src, File destination) {
-        return copyTo(props, src, destination.getPath());
-    }
-
-    public int copyTo(File src, String destination) {
-        return copyTo(MutableMap.<String,Object>of(), src, destination);
-    }
-    public int copyTo(Map<String,?> props, File src, String destination) {
-        Preconditions.checkNotNull(address, "Host address must be specified for scp");
-        Preconditions.checkArgument(src.exists(), "File %s must exist for scp", src.getPath());
-        try {
-            return copyTo(props, new FileInputStream(src), src.length(), destination);
-        } catch (FileNotFoundException e) {
-            throw Throwables.propagate(e);
-        }
-    }
-    public int copyTo(Reader src, String destination) {
-        return copyTo(MutableMap.<String,Object>of(), src, destination);
-    }
-    public int copyTo(Map<String,?> props, Reader src, String destination) {
-        return copyTo(props, new ReaderInputStream(src), destination);
-    }
-    public int copyTo(InputStream src, String destination) {
-        return copyTo(MutableMap.<String,Object>of(), src, destination);
-    }
-    public int copyTo(InputStream src, long filesize, String destination) {
-        return copyTo(MutableMap.<String,Object>of(), src, filesize, destination);
-    }
-    // FIXME the return code is not a reliable indicator of success or failure
-    public int copyTo(final Map<String,?> props, final InputStream src, final long filesize, final String destination) {
-        if (filesize == -1) {
-            return copyTo(props, src, destination);
-        } else {
-            return execSsh(props, new Function<ShellTool,Integer>() {
-                public Integer apply(ShellTool ssh) {
-                    return ((SshTool) ssh).copyToServer(props, new KnownSizeInputStream(src, filesize), destination);
-                }});
-        }
-    }
-    // FIXME the return code is not a reliable indicator of success or failure
-    // Closes input stream before returning
-    public int copyTo(final Map<String,?> props, final InputStream src, final String destination) {
-        return execSsh(props, new Function<ShellTool,Integer>() {
-            public Integer apply(ShellTool ssh) {
-                return ((SshTool)ssh).copyToServer(props, src, destination);
-            }});
-    }
-
-    // FIXME the return code is not a reliable indicator of success or failure
-    public int copyFrom(String remote, String local) {
-        return copyFrom(MutableMap.<String,Object>of(), remote, local);
-    }
-    public int copyFrom(final Map<String,?> props, final String remote, final String local) {
-        return execSsh(props, new Function<ShellTool,Integer>() {
-            public Integer apply(ShellTool ssh) {
-                return ((SshTool)ssh).copyFromServer(props, remote, new File(local));
-            }});
-    }
-
-    public int installTo(String url, String destPath) {
-        return installTo(MutableMap.<String, Object>of(), url, destPath);
-    }
-
-    public int installTo(Map<String,?> props, String url, String destPath) {
-        return installTo(ResourceUtils.create(this), props, url, destPath);
-    }
-
-    public int installTo(ResourceUtils loader, String url, String destPath) {
-        return installTo(loader, MutableMap.<String, Object>of(), url, destPath);
-    }
-
-    /**
-     * Installs the given URL at the indicated destination path.
-     * <p>
-     * Attempts to curl the source URL on the remote machine,
-     * then if that fails, loads locally (from classpath or file) and transfers.
-     * <p>
-     * Use {@link ArchiveUtils} to handle directories and their contents properly.
-     *
-     * TODO allow s3://bucket/file URIs for AWS S3 resources
-     * TODO use PAX-URL style URIs for maven artifacts
-     * TODO use subtasks here for greater visibility?; deprecate in favour of SshTasks.installFromUrl?
-     *
-     * @param utils A {@link ResourceUtils} that can resolve the source URLs
-     * @param url The source URL to be installed
-     * @param destPath The file to be created on the destination
-     *
-     * @see ArchiveUtils#deploy(String, SshMachineLocation, String)
-     * @see ArchiveUtils#deploy(String, SshMachineLocation, String, String)
-     * @see ResourceUtils#getResourceFromUrl(String)
-     */
-    public int installTo(ResourceUtils utils, Map<String,?> props, String url, String destPath) {
-        LOG.debug("installing {} to {} on {}, attempting remote curl", new Object[] { url, destPath, this });
-
-        try {
-            PipedInputStream insO = new PipedInputStream(); OutputStream outO = new PipedOutputStream(insO);
-            PipedInputStream insE = new PipedInputStream(); OutputStream outE = new PipedOutputStream(insE);
-            StreamGobbler sgsO = new StreamGobbler(insO, null, LOG); sgsO.setLogPrefix("[curl @ "+address+":stdout] ").start();
-            StreamGobbler sgsE = new StreamGobbler(insE, null, LOG); sgsE.setLogPrefix("[curl @ "+address+":stdout] ").start();
-            Map<String, ?> sshProps = MutableMap.<String, Object>builder().putAll(props).put("out", outO).put("err", outE).build();
-            int result = execScript(sshProps, "copying remote resource "+url+" to server",  ImmutableList.of(
-                    BashCommands.INSTALL_CURL, // TODO should hold the 'installing' mutex
-                    "mkdir -p `dirname '"+destPath+"'`",
-                    "curl "+url+" -L --silent --insecure --show-error --fail --connect-timeout 60 --max-time 600 --retry 5 -o '"+destPath+"'"));
-            sgsO.close();
-            sgsE.close();
-            if (result != 0) {
-                LOG.debug("installing {} to {} on {}, curl failed, attempting local fetch and copy", new Object[] { url, destPath, this });
-                try {
-                    Tasks.setBlockingDetails("retrieving resource "+url+" for copying across");
-                    InputStream stream = utils.getResourceFromUrl(url);
-                    Tasks.setBlockingDetails("copying resource "+url+" to server");
-                    result = copyTo(props, stream, destPath);
-                } finally {
-                    Tasks.setBlockingDetails(null);
-                }
-            }
-            if (result == 0) {
-                LOG.debug("installing {} complete; {} on {}", new Object[] { url, destPath, this });
-            } else {
-                LOG.warn("installing {} failed; {} on {}: {}", new Object[] { url, destPath, this, result });
-            }
-            return result;
-        } catch (IOException e) {
-            throw Throwables.propagate(e);
-        }
-    }
-
-    @Override
-    public String toString() {
-        return "SshMachineLocation["+getDisplayName()+":"+address+":"+getPort()+"@"+getId()+"]";
-    }
-
-    @Override
-    public String toVerboseString() {
-        return Objects.toStringHelper(this).omitNullValues()
-                .add("id", getId()).add("name", getDisplayName())
-                .add("user", getUser()).add("address", getAddress()).add("port", getPort())
-                .add("parentLocation", getParent())
-                .toString();
-    }
-
-    /**
-     * @see #obtainPort(PortRange)
-     * @see PortRanges#ANY_HIGH_PORT
-     */
-    @Override
-    public boolean obtainSpecificPort(int portNumber) {
-        synchronized (usedPorts) {
-            // TODO Does not yet check if the port really is free on this machine
-            if (usedPorts.contains(portNumber)) {
-                return false;
-            } else {
-                usedPorts.add(portNumber);
-                return true;
-            }
-        }
-    }
-
-    @Override
-    public int obtainPort(PortRange range) {
-        synchronized (usedPorts) {
-            for (int p: range)
-                if (obtainSpecificPort(p)) return p;
-            if (LOG.isDebugEnabled()) LOG.debug("unable to find port in {} on {}; returning -1", range, this);
-            return -1;
-        }
-    }
-
-    @Override
-    public void releasePort(int portNumber) {
-        synchronized (usedPorts) {
-            usedPorts.remove((Object) portNumber);
-        }
-    }
-
-    public boolean isSshable() {
-        String cmd = "date";
-        try {
-            try {
-                Socket s = new Socket();
-                s.connect(new InetSocketAddress(getAddress(), getPort()), SSHABLE_CONNECT_TIMEOUT);
-                s.close();
-            } catch (IOException e) {
-                if (LOG.isDebugEnabled()) LOG.debug(""+this+" not [yet] reachable (socket "+getAddress()+":"+getPort()+"): "+e);
-                return false;
-            }
-            // this should do execCommands because sftp subsystem might not be available (or sometimes seems to take a while for it to become so?)
-            int result = execCommands(MutableMap.<String,Object>of(), "isSshable", ImmutableList.of(cmd));
-            if (result == 0) {
-                return true;
-            } else {
-                if (LOG.isDebugEnabled()) LOG.debug("Not reachable: {}, executing `{}`, exit code {}", new Object[] {this, cmd, result});
-                return false;
-            }
-        } catch (SshException e) {
-            if (LOG.isDebugEnabled()) LOG.debug("Exception checking if "+this+" is reachable; assuming not", e);
-            return false;
-        } catch (IllegalStateException e) {
-            if (LOG.isDebugEnabled()) LOG.debug("Exception checking if "+this+" is reachable; assuming not", e);
-            return false;
-        } catch (RuntimeException e) {
-            if (Exceptions.getFirstThrowableOfType(e, IOException.class) != null) {
-                if (LOG.isDebugEnabled()) LOG.debug("Exception checking if "+this+" is reachable; assuming not", e);
-                return false;
-            } else {
-                throw e;
-            }
-        }
-    }
-
-    @Override
-    public OsDetails getOsDetails() {
-        return getMachineDetails().getOsDetails();
-    }
-
-    @Override
-    public MachineDetails getMachineDetails() {
-        synchronized (machineDetailsLock) {
-            if (machineDetails == null) {
-                machineDetails = getConfig(MACHINE_DETAILS);
-            }
-            if (machineDetails == null) {
-                machineDetails = inferMachineDetails();
-            }
-        }
-        return machineDetails;
-    }
-
-    protected MachineDetails inferMachineDetails() {
-        boolean detectionEnabled = getConfig(DETECT_MACHINE_DETAILS);
-        if (!detectionEnabled)
-            return new BasicMachineDetails(new BasicHardwareDetails(-1, -1), new BasicOsDetails("UNKNOWN", "UNKNOWN", "UNKNOWN"));
-
-        Tasks.setBlockingDetails("Waiting for machine details");
-        try {
-            return BasicMachineDetails.forSshMachineLocation(this);
-        } finally {
-            Tasks.resetBlockingDetails();
-        }
-    }
-
-    @Override
-    public void acquireMutex(String mutexId, String description) throws RuntimeInterruptedException {
-        try {
-            getMutexSupport().acquireMutex(mutexId, description);
-        } catch (InterruptedException ie) {
-            throw new RuntimeInterruptedException("Interrupted waiting for mutex: " + mutexId, ie);
-        }
-    }
-
-    @Override
-    public boolean tryAcquireMutex(String mutexId, String description) {
-        return getMutexSupport().tryAcquireMutex(mutexId, description);
-    }
-
-    @Override
-    public void releaseMutex(String mutexId) {
-        getMutexSupport().releaseMutex(mutexId);
-    }
-
-    @Override
-    public boolean hasMutex(String mutexId) {
-        return getMutexSupport().hasMutex(mutexId);
-    }
-
-    //We want the SshMachineLocation to be serializable and therefore the pool needs to be dealt with correctly.
-    //In this case we are not serializing the pool (we made the field transient) and create a new pool when deserialized.
-    //This fix is currently needed for experiments, but isn't used in normal Brooklyn usage.
-    private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
-        in.defaultReadObject();
-        getSshPoolCache();
-    }
-
-    /** returns the un-passphrased key-pair info if a key is being used, or else null */
-    public KeyPair findKeyPair() {
-        String fn = getConfig(SshTool.PROP_PRIVATE_KEY_FILE);
-        ResourceUtils r = ResourceUtils.create(this);
-        if (fn!=null) return SecureKeys.readPem(r.getResourceFromUrl(fn), getConfig(SshTool.PROP_PRIVATE_KEY_PASSPHRASE));
-        String data = getConfig(SshTool.PROP_PRIVATE_KEY_DATA);
-        if (data!=null) return SecureKeys.readPem(new ReaderInputStream(new StringReader(data)), getConfig(SshTool.PROP_PRIVATE_KEY_PASSPHRASE));
-        if (findPassword()!=null)
-            // if above not specified, and password is, use password
-            return null;
-        // fall back to id_rsa and id_dsa
-        if (new File( Urls.mergePaths(System.getProperty("user.home"), ".ssh/id_rsa") ).exists() )
-            return SecureKeys.readPem(r.getResourceFromUrl("~/.ssh/id_rsa"), getConfig(SshTool.PROP_PRIVATE_KEY_PASSPHRASE));
-        if (new File( Urls.mergePaths(System.getProperty("user.home"), ".ssh/id_dsa") ).exists() )
-            return SecureKeys.readPem(r.getResourceFromUrl("~/.ssh/id_dsa"), getConfig(SshTool.PROP_PRIVATE_KEY_PASSPHRASE));
-        LOG.warn("Unable to extract any key or passphrase data in request to findKeyPair for "+this);
-        return null;
-    }
-
-    /** returns the password being used to log in, if a password is being used, or else null */
-    public String findPassword() {
-        return getConfig(SshTool.PROP_PASSWORD);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/SupportsPortForwarding.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/SupportsPortForwarding.java b/core/src/main/java/org/apache/brooklyn/location/basic/SupportsPortForwarding.java
deleted file mode 100644
index d58e9a5..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/SupportsPortForwarding.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import org.apache.brooklyn.util.net.Cidr;
-
-import com.google.common.net.HostAndPort;
-
-public interface SupportsPortForwarding {
-
-    /** returns an endpoint suitable for contacting the indicated private port on this object,
-     * from the given Cidr, creating it if necessary and possible; 
-     * may return null if forwarding not available 
-     */
-    public HostAndPort getSocketEndpointFor(Cidr accessor, int privatePort);
-    
-    /** marker on a location to indicate that port forwarding should be done automatically
-     * for attempts to access from Brooklyn
-     */
-    public interface RequiresPortForwarding extends SupportsPortForwarding {
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/WinRmMachineLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/WinRmMachineLocation.java b/core/src/main/java/org/apache/brooklyn/location/basic/WinRmMachineLocation.java
deleted file mode 100644
index 9bac3c5..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/WinRmMachineLocation.java
+++ /dev/null
@@ -1,361 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-import java.net.InetAddress;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.location.MachineDetails;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.OsDetails;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.commons.codec.binary.Base64;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Charsets;
-import com.google.common.base.Joiner;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Lists;
-import com.google.common.net.HostAndPort;
-import com.google.common.reflect.TypeToken;
-
-import org.apache.brooklyn.location.access.PortForwardManager;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.stream.Streams;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-
-import io.cloudsoft.winrm4j.winrm.WinRmTool;
-import io.cloudsoft.winrm4j.winrm.WinRmToolResponse;
-
-public class WinRmMachineLocation extends AbstractLocation implements MachineLocation {
-
-    private static final Logger LOG = LoggerFactory.getLogger(WinRmMachineLocation.class);
-
-    // FIXME Respect `port` config when using {@link WinRmTool}
-    public static final ConfigKey<Integer> WINRM_PORT = ConfigKeys.newIntegerConfigKey(
-            "port",
-            "WinRM port to use when connecting to the remote machine",
-            5985);
-    
-    // TODO merge with {link SshTool#PROP_USER} and {@link SshMachineLocation#user}
-    public static final ConfigKey<String> USER = ConfigKeys.newStringConfigKey("user",
-            "Username to use when connecting to the remote machine");
-
-    // TODO merge with {link SshTool#PROP_PASSWORD}
-    public static final ConfigKey<String> PASSWORD = ConfigKeys.newStringConfigKey("password",
-            "Password to use when connecting to the remote machine");
-
-    public static final ConfigKey<Integer> COPY_FILE_CHUNK_SIZE_BYTES = ConfigKeys.newIntegerConfigKey("windows.copy.file.size.bytes",
-            "Size of file chunks (in bytes) to be used when copying a file to the remote server", 1024);
-
-     public static final ConfigKey<InetAddress> ADDRESS = ConfigKeys.newConfigKey(
-            InetAddress.class,
-            "address",
-            "Address of the remote machine");
-
-    public static final ConfigKey<Integer> EXECUTION_ATTEMPTS = ConfigKeys.newIntegerConfigKey(
-            "windows.exec.attempts",
-            "Number of attempts to execute a remote command",
-            1);
-    
-    // TODO See SshTool#PROP_SSH_TRIES, where it was called "sshTries"; remove duplication? Merge into one well-named thing?
-    public static final ConfigKey<Integer> EXEC_TRIES = ConfigKeys.newIntegerConfigKey(
-            "execTries", 
-            "Max number of times to attempt WinRM operations", 
-            10);
-
-    public static final ConfigKey<Iterable<String>> PRIVATE_ADDRESSES = ConfigKeys.newConfigKey(
-            new TypeToken<Iterable<String>>() {},
-            "privateAddresses",
-            "Private addresses of this machine, e.g. those within the private network", 
-            null);
-
-    public static final ConfigKey<Map<Integer, String>> TCP_PORT_MAPPINGS = ConfigKeys.newConfigKey(
-            new TypeToken<Map<Integer, String>>() {},
-            "tcpPortMappings",
-            "NAT'ed ports, giving the mapping from private TCP port to a public host:port", 
-            null);
-
-    @Override
-    public InetAddress getAddress() {
-        return getConfig(ADDRESS);
-    }
-
-    @Override
-    public OsDetails getOsDetails() {
-        return null;
-    }
-
-    @Override
-    public MachineDetails getMachineDetails() {
-        return null;
-    }
-
-    @Nullable
-    @Override
-    public String getHostname() {
-        InetAddress address = getAddress();
-        return (address != null) ? address.getHostAddress() : null;
-    }
-
-    @Nullable
-    protected String getHostAndPort() {
-        String host = getHostname();
-        return (host == null) ? null : host + ":" + config().get(WINRM_PORT);
-    }
-
-    @Override
-    public Set<String> getPublicAddresses() {
-        InetAddress address = getAddress();
-        return (address == null) ? ImmutableSet.<String>of() : ImmutableSet.of(address.getHostAddress());
-    }
-    
-    @Override
-    public Set<String> getPrivateAddresses() {
-        Iterable<String> result = getConfig(PRIVATE_ADDRESSES);
-        return (result == null) ? ImmutableSet.<String>of() : ImmutableSet.copyOf(result);
-    }
-
-    public WinRmToolResponse executeScript(String script) {
-        return executeScript(ImmutableList.of(script));
-    }
-
-    public WinRmToolResponse executeScript(List<String> script) {
-        int execTries = getRequiredConfig(EXEC_TRIES);
-        Collection<Throwable> exceptions = Lists.newArrayList();
-        for (int i = 0; i < execTries; i++) {
-            try {
-                return executeScriptNoRetry(script);
-            } catch (Exception e) {
-                Exceptions.propagateIfFatal(e);
-                if (i == (execTries+1)) {
-                    LOG.info("Propagating WinRM exception (attempt "+(i+1)+" of "+execTries+")", e);
-                } else if (i == 0) {
-                    LOG.warn("Ignoring WinRM exception and retrying (attempt "+(i+1)+" of "+execTries+")", e);
-                } else {
-                    LOG.debug("Ignoring WinRM exception and retrying (attempt "+(i+1)+" of "+execTries+")", e);
-                }
-                exceptions.add(e);
-            }
-        }
-        throw Exceptions.propagate("failed to execute shell script", exceptions);
-    }
-
-    protected WinRmToolResponse executeScriptNoRetry(List<String> script) {
-        WinRmTool winRmTool = WinRmTool.connect(getHostAndPort(), getUser(), getPassword());
-        WinRmToolResponse response = winRmTool.executeScript(script);
-        return response;
-    }
-
-    public WinRmToolResponse executePsScript(String psScript) {
-        return executePsScript(ImmutableList.of(psScript));
-    }
-
-    public WinRmToolResponse executePsScript(List<String> psScript) {
-        int execTries = getRequiredConfig(EXEC_TRIES);
-        Collection<Throwable> exceptions = Lists.newArrayList();
-        for (int i = 0; i < execTries; i++) {
-            try {
-                return executePsScriptNoRetry(psScript);
-            } catch (Exception e) {
-                Exceptions.propagateIfFatal(e);
-                if (i == (execTries+1)) {
-                    LOG.info("Propagating WinRM exception (attempt "+(i+1)+" of "+execTries+")", e);
-                } else if (i == 0) {
-                    LOG.warn("Ignoring WinRM exception and retrying after 5 seconds (attempt "+(i+1)+" of "+execTries+")", e);
-                    Time.sleep(Duration.FIVE_SECONDS);
-                } else {
-                    LOG.debug("Ignoring WinRM exception and retrying after 5 seconds (attempt "+(i+1)+" of "+execTries+")", e);
-                    Time.sleep(Duration.FIVE_SECONDS);
-                }
-                exceptions.add(e);
-            }
-        }
-        throw Exceptions.propagate("failed to execute powershell script", exceptions);
-    }
-
-    public WinRmToolResponse executePsScriptNoRetry(List<String> psScript) {
-        WinRmTool winRmTool = WinRmTool.connect(getHostAndPort(), getUser(), getPassword());
-        WinRmToolResponse response = winRmTool.executePs(psScript);
-        return response;
-    }
-
-    public int copyTo(File source, String destination) {
-        FileInputStream sourceStream = null;
-        try {
-            sourceStream = new FileInputStream(source);
-            return copyTo(sourceStream, destination);
-        } catch (FileNotFoundException e) {
-            throw Exceptions.propagate(e);
-        } finally {
-            if (sourceStream != null) {
-                Streams.closeQuietly(sourceStream);
-            }
-        }
-    }
-
-    public int copyTo(InputStream source, String destination) {
-        executePsScript(ImmutableList.of("rm -ErrorAction SilentlyContinue " + destination));
-        try {
-            int chunkSize = getConfig(COPY_FILE_CHUNK_SIZE_BYTES);
-            byte[] inputData = new byte[chunkSize];
-            int bytesRead;
-            int expectedFileSize = 0;
-            while ((bytesRead = source.read(inputData)) > 0) {
-                byte[] chunk;
-                if (bytesRead == chunkSize) {
-                    chunk = inputData;
-                } else {
-                    chunk = Arrays.copyOf(inputData, bytesRead);
-                }
-                executePsScript(ImmutableList.of("If ((!(Test-Path " + destination + ")) -or ((Get-Item '" + destination + "').length -eq " +
-                        expectedFileSize + ")) {Add-Content -Encoding Byte -path " + destination +
-                        " -value ([System.Convert]::FromBase64String(\"" + new String(Base64.encodeBase64(chunk)) + "\"))}"));
-                expectedFileSize += bytesRead;
-            }
-
-            return 0;
-        } catch (java.io.IOException e) {
-            throw Exceptions.propagate(e);
-        }
-    }
-
-    @Override
-    public void init() {
-        super.init();
-
-        // Register any pre-existing port-mappings with the PortForwardManager
-        Map<Integer, String> tcpPortMappings = getConfig(TCP_PORT_MAPPINGS);
-        if (tcpPortMappings != null) {
-            PortForwardManager pfm = (PortForwardManager) getManagementContext().getLocationRegistry().resolve("portForwardManager(scope=global)");
-            for (Map.Entry<Integer, String> entry : tcpPortMappings.entrySet()) {
-                int targetPort = entry.getKey();
-                HostAndPort publicEndpoint = HostAndPort.fromString(entry.getValue());
-                if (!publicEndpoint.hasPort()) {
-                    throw new IllegalArgumentException("Invalid portMapping ('"+entry.getValue()+"') for port "+targetPort+" in machine "+this);
-                }
-                pfm.associate(publicEndpoint.getHostText(), publicEndpoint, this, targetPort);
-            }
-        }
-    }
-    public String getUser() {
-        return config().get(USER);
-    }
-
-    private String getPassword() {
-        return config().get(PASSWORD);
-    }
-
-    private <T> T getRequiredConfig(ConfigKey<T> key) {
-        return checkNotNull(getConfig(key), "key %s must be set", key);
-    }
-    
-    public static String getDefaultUserMetadataString() {
-        // Using an encoded command obviates the need to escape
-        String unencodePowershell = Joiner.on("\r\n").join(ImmutableList.of(
-                // Allow TS connections
-                "$RDP = Get-WmiObject -Class Win32_TerminalServiceSetting -ComputerName $env:computername -Namespace root\\CIMV2\\TerminalServices -Authentication PacketPrivacy",
-                "$RDP.SetAllowTSConnections(1,1)",
-                "Set-ExecutionPolicy Unrestricted -Force",
-                // Set unlimited values for remote execution limits
-                "Set-Item WSMan:\\localhost\\Shell\\MaxConcurrentUsers 100",
-                "Set-Item WSMan:\\localhost\\Shell\\MaxMemoryPerShellMB 0",
-                "Set-Item WSMan:\\localhost\\Shell\\MaxProcessesPerShell 0",
-                "Set-Item WSMan:\\localhost\\Shell\\MaxShellsPerUser 0",
-                "New-ItemProperty \"HKLM:\\System\\CurrentControlSet\\Control\\LSA\" -Name \"SuppressExtendedProtection\" -Value 1 -PropertyType \"DWord\"",
-                // The following allows scripts to re-authenticate with local credential - this is required
-                // as certain operations cannot be performed with remote credentials
-                "$allowed = @('WSMAN/*')",
-                "$key = 'hklm:\\SOFTWARE\\Policies\\Microsoft\\Windows\\CredentialsDelegation'",
-                "if (!(Test-Path $key)) {",
-                "    md $key",
-                "}",
-                "New-ItemProperty -Path $key -Name AllowFreshCredentials -Value 1 -PropertyType Dword -Force",
-                "New-ItemProperty -Path $key -Name AllowFreshCredentialsWhenNTLMOnly -Value 1 -PropertyType Dword -Force",
-                "$credKey = Join-Path $key 'AllowFreshCredentials'",
-                "if (!(Test-Path $credKey)) {",
-                "    md $credkey",
-                "}",
-                "$ntlmKey = Join-Path $key 'AllowFreshCredentialsWhenNTLMOnly'",
-                "if (!(Test-Path $ntlmKey)) {",
-                "    md $ntlmKey",
-                "}",
-                "$i = 1",
-                "$allowed |% {",
-                "    # Script does not take into account existing entries in this key",
-                "    New-ItemProperty -Path $credKey -Name $i -Value $_ -PropertyType String -Force",
-                "    New-ItemProperty -Path $ntlmKey -Name $i -Value $_ -PropertyType String -Force",
-                "    $i++",
-                "}"
-        ));
-
-        String encoded = new String(Base64.encodeBase64(unencodePowershell.getBytes(Charsets.UTF_16LE)));
-        return "winrm quickconfig -q & " +
-                "winrm set winrm/config/service/auth @{Basic=\"true\"} & " +
-                "winrm set winrm/config/service/auth @{CredSSP=\"true\"} & " +
-                "winrm set winrm/config/client/auth @{CredSSP=\"true\"} & " +
-                "winrm set winrm/config/client @{AllowUnencrypted=\"true\"} & " +
-                "winrm set winrm/config/service @{AllowUnencrypted=\"true\"} & " +
-                "winrm set winrm/config/winrs @{MaxConcurrentUsers=\"100\"} & " +
-                "winrm set winrm/config/winrs @{MaxMemoryPerShellMB=\"0\"} & " +
-                "winrm set winrm/config/winrs @{MaxProcessesPerShell=\"0\"} & " +
-                "winrm set winrm/config/winrs @{MaxShellsPerUser=\"0\"} & " +
-                "netsh advfirewall firewall add rule name=RDP dir=in protocol=tcp localport=3389 action=allow profile=any & " +
-                "netsh advfirewall firewall add rule name=WinRM dir=in protocol=tcp localport=5985 action=allow profile=any & " +
-                "powershell -EncodedCommand " + encoded;
-        /* TODO: Find out why scripts with new line characters aren't working on AWS. The following appears as if it *should*
-           work but doesn't - the script simply isn't run. By connecting to the machine via RDP, you can get the script
-           from 'http://169.254.169.254/latest/user-data', and running it at the command prompt works, but for some
-           reason the script isn't run when the VM is provisioned
-        */
-//        return Joiner.on("\r\n").join(ImmutableList.of(
-//                "winrm quickconfig -q",
-//                "winrm set winrm/config/service/auth @{Basic=\"true\"}",
-//                "winrm set winrm/config/client @{AllowUnencrypted=\"true\"}",
-//                "winrm set winrm/config/service @{AllowUnencrypted=\"true\"}",
-//                "netsh advfirewall firewall add rule name=RDP dir=in protocol=tcp localport=3389 action=allow profile=any",
-//                "netsh advfirewall firewall add rule name=WinRM dir=in protocol=tcp localport=5985 action=allow profile=any",
-//                // Using an encoded command necessitates the need to escape. The unencoded command is as follows:
-//                // $RDP = Get-WmiObject -Class Win32_TerminalServiceSetting -ComputerName $env:computername -Namespace root\CIMV2\TerminalServices -Authentication PacketPrivacy
-//                // $Result = $RDP.SetAllowTSConnections(1,1)
-//                "powershell -EncodedCommand JABSAEQAUAAgAD0AIABHAGUAdAAtAFcAbQBpAE8AYgBqAGUAYwB0ACAALQBDAGwAYQBzAHMAI" +
-//                        "ABXAGkAbgAzADIAXwBUAGUAcgBtAGkAbgBhAGwAUwBlAHIAdgBpAGMAZQBTAGUAdAB0AGkAbgBnACAALQBDAG8AbQBwA" +
-//                        "HUAdABlAHIATgBhAG0AZQAgACQAZQBuAHYAOgBjAG8AbQBwAHUAdABlAHIAbgBhAG0AZQAgAC0ATgBhAG0AZQBzAHAAY" +
-//                        "QBjAGUAIAByAG8AbwB0AFwAQwBJAE0AVgAyAFwAVABlAHIAbQBpAG4AYQBsAFMAZQByAHYAaQBjAGUAcwAgAC0AQQB1A" +
-//                        "HQAaABlAG4AdABpAGMAYQB0AGkAbwBuACAAUABhAGMAawBlAHQAUAByAGkAdgBhAGMAeQANAAoAJABSAGUAcwB1AGwAd" +
-//                        "AAgAD0AIAAkAFIARABQAC4AUwBlAHQAQQBsAGwAbwB3AFQAUwBDAG8AbgBuAGUAYwB0AGkAbwBuAHMAKAAxACwAMQApAA=="
-//        ));
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/byon/ByonLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/byon/ByonLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/byon/ByonLocationResolver.java
new file mode 100644
index 0000000..e45b583
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/byon/ByonLocationResolver.java
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.byon;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+import java.net.InetAddress;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationRegistry;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.config.Sanitizer;
+import org.apache.brooklyn.core.mgmt.internal.LocalLocationManager;
+import org.apache.brooklyn.location.core.AbstractLocationResolver;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.location.winrm.WinRmMachineLocation;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.flags.TypeCoercions;
+import org.apache.brooklyn.util.net.UserAndHostAndPort;
+import org.apache.brooklyn.util.text.WildcardGlobs;
+import org.apache.brooklyn.util.text.WildcardGlobs.PhraseTreatment;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.net.HostAndPort;
+
+/**
+ * Examples of valid specs:
+ *   <ul>
+ *     <li>byon:(hosts=myhost)
+ *     <li>byon:(hosts=myhost,myhost2)
+ *     <li>byon:(hosts="myhost, myhost2")
+ *     <li>byon:(hosts=myhost,myhost2, name=abc)
+ *     <li>byon:(hosts="myhost, myhost2", name="my location name")
+ *   </ul>
+ * 
+ * @author aled
+ */
+@SuppressWarnings({"rawtypes"})
+public class ByonLocationResolver extends AbstractLocationResolver {
+
+    public static final Logger log = LoggerFactory.getLogger(ByonLocationResolver.class);
+    
+    public static final String BYON = "byon";
+
+    public static final ConfigKey<String> OS_FAMILY = ConfigKeys.newStringConfigKey("osfamily", "OS Family of the machine, either windows or linux", "linux");
+
+    public static final Map<String, Class<? extends MachineLocation>> OS_TO_MACHINE_LOCATION_TYPE = ImmutableMap.<String, Class<? extends MachineLocation>>of(
+            "windows", WinRmMachineLocation.class,
+            "linux", SshMachineLocation.class);
+
+    @Override
+    public String getPrefix() {
+        return BYON;
+    }
+
+    @Override
+    protected Class<? extends Location> getLocationType() {
+        return FixedListMachineProvisioningLocation.class;
+    }
+
+    @Override
+    protected SpecParser getSpecParser() {
+        return new AbstractLocationResolver.SpecParser(getPrefix()).setExampleUsage("\"byon(hosts='addr1,addr2')\"");
+    }
+
+    @Override
+    protected ConfigBag extractConfig(Map<?,?> locationFlags, String spec, LocationRegistry registry) {
+        ConfigBag config = super.extractConfig(locationFlags, spec, registry);
+
+        Object hosts = config.getStringKey("hosts");
+        config.remove("hosts");
+        String user = (String) config.getStringKey("user");
+        Integer port = (Integer) TypeCoercions.coerce(config.getStringKey("port"), Integer.class);
+        Class<? extends MachineLocation> locationClass = OS_TO_MACHINE_LOCATION_TYPE.get(config.get(OS_FAMILY));
+
+        MutableMap<String, Object> defaultProps = MutableMap.of();
+        defaultProps.addIfNotNull("user", user);
+        defaultProps.addIfNotNull("port", port);
+
+        List<String> hostAddresses;
+        
+        if (hosts instanceof String) {
+            if (((String) hosts).isEmpty()) {
+                hostAddresses = ImmutableList.of();
+            } else {
+                hostAddresses = WildcardGlobs.getGlobsAfterBraceExpansion("{"+hosts+"}",
+                        true /* numeric */, /* no quote support though */ PhraseTreatment.NOT_A_SPECIAL_CHAR, PhraseTreatment.NOT_A_SPECIAL_CHAR);
+            }
+        } else if (hosts instanceof Iterable) {
+            hostAddresses = ImmutableList.copyOf((Iterable<String>)hosts);
+        } else {
+            throw new IllegalArgumentException("Invalid location '"+spec+"'; at least one host must be defined");
+        }
+        if (hostAddresses.isEmpty()) {
+            throw new IllegalArgumentException("Invalid location '"+spec+"'; at least one host must be defined");
+        }
+        
+        List<MachineLocation> machines = Lists.newArrayList();
+        for (Object host : hostAddresses) {
+            LocationSpec<? extends MachineLocation> machineSpec;
+            if (host instanceof String) {
+                machineSpec = parseMachine((String)host, locationClass, defaultProps, spec);
+            } else if (host instanceof Map) {
+                machineSpec = parseMachine((Map<String, ?>)host, locationClass, defaultProps, spec);
+            } else {
+                throw new IllegalArgumentException("Expected machine to be String or Map, but was "+host.getClass().getName()+" ("+host+")");
+            }
+            machineSpec.configureIfNotNull(LocalLocationManager.CREATE_UNMANAGED, config.get(LocalLocationManager.CREATE_UNMANAGED));
+            MachineLocation machine = managementContext.getLocationManager().createLocation(machineSpec);
+            machines.add(machine);
+        }
+        
+        config.putStringKey("machines", machines);
+
+        return config;
+    }
+    
+    protected LocationSpec<? extends MachineLocation> parseMachine(Map<String, ?> vals, Class<? extends MachineLocation> locationClass, Map<String, ?> defaults, String specForErrMsg) {
+        Map<String, Object> valSanitized = Sanitizer.sanitize(vals);
+        Map<String, Object> machineConfig = MutableMap.copyOf(vals);
+        
+        String osfamily = (String) machineConfig.remove(OS_FAMILY.getName());
+        String ssh = (String) machineConfig.remove("ssh");
+        String winrm = (String) machineConfig.remove("winrm");
+        Map<Integer, String> tcpPortMappings = (Map<Integer, String>) machineConfig.get("tcpPortMappings");
+        
+        checkArgument(ssh != null ^ winrm != null, "Must specify exactly one of 'ssh' or 'winrm' for machine: %s", valSanitized);
+        
+        UserAndHostAndPort userAndHostAndPort;
+        String host;
+        int port;
+        if (ssh != null) {
+            userAndHostAndPort = parseUserAndHostAndPort((String)ssh, 22);
+        } else {
+            userAndHostAndPort = parseUserAndHostAndPort((String)winrm, 5985);
+        }
+        
+        // If there is a tcpPortMapping defined for the connection-port, then use that for ssh/winrm machine
+        port = userAndHostAndPort.getHostAndPort().getPort();
+        if (tcpPortMappings != null && tcpPortMappings.containsKey(port)) {
+            String override = tcpPortMappings.get(port);
+            HostAndPort hostAndPortOverride = HostAndPort.fromString(override);
+            if (!hostAndPortOverride.hasPort()) {
+                throw new IllegalArgumentException("Invalid portMapping ('"+override+"') for port "+port+" in "+specForErrMsg);
+            }
+            port = hostAndPortOverride.getPort();
+            host = hostAndPortOverride.getHostText().trim();
+        } else {
+            host = userAndHostAndPort.getHostAndPort().getHostText().trim();
+        }
+        
+        machineConfig.put("address", host);
+        try {
+            InetAddress.getByName(host);
+        } catch (Exception e) {
+            throw new IllegalArgumentException("Invalid host '"+host+"' specified in '"+specForErrMsg+"': "+e);
+        }
+
+        if (userAndHostAndPort.getUser() != null) {
+            checkArgument(!vals.containsKey("user"), "Must not specify user twice for machine: %s", valSanitized);
+            machineConfig.put("user", userAndHostAndPort.getUser());
+        }
+        if (userAndHostAndPort.getHostAndPort().hasPort()) {
+            checkArgument(!vals.containsKey("port"), "Must not specify port twice for machine: %s", valSanitized);
+            machineConfig.put("port", port);
+        }
+        for (Map.Entry<String, ?> entry : defaults.entrySet()) {
+            if (!machineConfig.containsKey(entry.getKey())) {
+                machineConfig.put(entry.getKey(), entry.getValue());
+            }
+        }
+        
+        Class<? extends MachineLocation> locationClassHere = locationClass;
+        if (osfamily != null) {
+            locationClassHere = OS_TO_MACHINE_LOCATION_TYPE.get(osfamily);
+        }
+
+        return LocationSpec.create(locationClassHere).configure(machineConfig);
+    }
+
+    protected LocationSpec<? extends MachineLocation> parseMachine(String val, Class<? extends MachineLocation> locationClass, Map<String, ?> defaults, String specForErrMsg) {
+        Map<String, Object> machineConfig = Maps.newLinkedHashMap();
+        
+        UserAndHostAndPort userAndHostAndPort = parseUserAndHostAndPort(val);
+        
+        String host = userAndHostAndPort.getHostAndPort().getHostText().trim();
+        machineConfig.put("address", host);
+        try {
+            InetAddress.getByName(host.trim());
+        } catch (Exception e) {
+            throw new IllegalArgumentException("Invalid host '"+host+"' specified in '"+specForErrMsg+"': "+e);
+        }
+        
+        if (userAndHostAndPort.getUser() != null) {
+            machineConfig.put("user", userAndHostAndPort.getUser());
+        }
+        if (userAndHostAndPort.getHostAndPort().hasPort()) {
+            machineConfig.put("port", userAndHostAndPort.getHostAndPort().getPort());
+        }
+        for (Map.Entry<String, ?> entry : defaults.entrySet()) {
+            if (!machineConfig.containsKey(entry.getKey())) {
+                machineConfig.put(entry.getKey(), entry.getValue());
+            }
+        }
+
+        return LocationSpec.create(locationClass).configure(machineConfig);
+    }
+    
+    private UserAndHostAndPort parseUserAndHostAndPort(String val) {
+        String userPart = null;
+        String hostPart = val;
+        if (val.contains("@")) {
+            userPart = val.substring(0, val.indexOf("@"));
+            hostPart = val.substring(val.indexOf("@")+1);
+        }
+        return UserAndHostAndPort.fromParts(userPart, HostAndPort.fromString(hostPart));
+    }
+    
+    private UserAndHostAndPort parseUserAndHostAndPort(String val, int defaultPort) {
+        UserAndHostAndPort result = parseUserAndHostAndPort(val);
+        if (!result.getHostAndPort().hasPort()) {
+            result = UserAndHostAndPort.fromParts(result.getUser(), result.getHostAndPort().getHostText(), defaultPort);
+        }
+        return result;
+    }
+}


[13/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/MachineLifecycleEffectorTasksTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/software/MachineLifecycleEffectorTasksTest.java b/software/base/src/test/java/brooklyn/entity/software/MachineLifecycleEffectorTasksTest.java
deleted file mode 100644
index d746c60..0000000
--- a/software/base/src/test/java/brooklyn/entity/software/MachineLifecycleEffectorTasksTest.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
-import java.util.List;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.entity.stock.BasicEntity;
-import org.apache.brooklyn.entity.stock.BasicEntityImpl;
-import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.sensor.core.DependentConfiguration;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.core.task.TaskInternal;
-import org.apache.brooklyn.util.time.Duration;
-import org.testng.annotations.DataProvider;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
-import brooklyn.entity.basic.EmptySoftwareProcess;
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.basic.SoftwareProcess.StopSoftwareParameters.StopMode;
-
-import org.apache.brooklyn.location.jclouds.BailOutJcloudsLocation;
-
-public class MachineLifecycleEffectorTasksTest {
-    public static boolean canStop(StopMode stopMode, boolean isEntityStopped) {
-        BasicEntityImpl entity = new BasicEntityImpl();
-        Lifecycle state = isEntityStopped ? Lifecycle.STOPPED : Lifecycle.RUNNING;
-        entity.setAttribute(SoftwareProcess.SERVICE_STATE_ACTUAL, state);
-        return MachineLifecycleEffectorTasks.canStop(stopMode, entity);
-    }
-    
-    @DataProvider(name = "canStopStates")
-    public Object[][] canStopStates() {
-        return new Object[][] {
-            { StopMode.ALWAYS, true, true },
-            { StopMode.ALWAYS, false, true },
-            { StopMode.IF_NOT_STOPPED, true, false },
-            { StopMode.IF_NOT_STOPPED, false, true },
-            { StopMode.NEVER, true, false },
-            { StopMode.NEVER, false, false },
-        };
-    }
-
-    @Test(dataProvider = "canStopStates")
-    public void testBasicSonftwareProcessCanStop(StopMode mode, boolean isEntityStopped, boolean expected) {
-        boolean canStop = canStop(mode, isEntityStopped);
-        assertEquals(canStop, expected);
-    }
-
-    @Test
-    public void testProvisionLatchObeyed() throws Exception {
-
-        AttributeSensor<Boolean> ready = Sensors.newBooleanSensor("readiness");
-
-        TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
-        BasicEntity triggerEntity = app.createAndManageChild(EntitySpec.create(BasicEntity.class));
-
-        EmptySoftwareProcess entity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class)
-                .configure(BrooklynConfigKeys.PROVISION_LATCH, DependentConfiguration.attributeWhenReady(triggerEntity, ready)));
-
-        final Task<Void> task = Entities.invokeEffector(app, app, Startable.START, ImmutableMap.of(
-                "locations", ImmutableList.of(BailOutJcloudsLocation.newBailOutJcloudsLocation(app.getManagementContext()))));
-
-        assertEffectorBlockingDetailsEventually(entity, "Waiting for config " + BrooklynConfigKeys.PROVISION_LATCH.getName());
-
-        Asserts.succeedsContinually(new Runnable() {
-            @Override
-            public void run() {
-                assertFalse(task.isDone());
-            }
-        });
-        try {
-            ((EntityLocal) triggerEntity).setAttribute(ready, true);
-            task.get(Duration.THIRTY_SECONDS);
-        } catch (Throwable t) {
-            // BailOut location throws but we don't care.
-        } finally {
-            Entities.destroyAll(app.getManagementContext());
-        }
-    }
-
-    private void assertEffectorBlockingDetailsEventually(final Entity entity, final String blockingDetailsSnippet) {
-        Asserts.succeedsEventually(new Runnable() {
-            @Override public void run() {
-                Task<?> entityTask = Iterables.getOnlyElement(entity.getApplication().getManagementContext().getExecutionManager().getTasksWithAllTags(
-                        ImmutableList.of(BrooklynTaskTags.EFFECTOR_TAG, BrooklynTaskTags.tagForContextEntity(entity))));
-                String blockingDetails = getBlockingDetails(entityTask);
-                assertTrue(blockingDetails.contains(blockingDetailsSnippet));
-            }});
-    }
-
-    private String getBlockingDetails(Task<?> task) {
-        List<TaskInternal<?>> taskChain = Lists.newArrayList();
-        TaskInternal<?> taskI = (TaskInternal<?>) task;
-        while (taskI != null) {
-            taskChain.add(taskI);
-            if (taskI.getBlockingDetails() != null) {
-                return taskI.getBlockingDetails();
-            }
-            taskI = (TaskInternal<?>) taskI.getBlockingTask();
-        }
-        throw new IllegalStateException("No blocking details for "+task+" (walked task chain "+taskChain+")");
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/SoftwareEffectorTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/software/SoftwareEffectorTest.java b/software/base/src/test/java/brooklyn/entity/software/SoftwareEffectorTest.java
deleted file mode 100644
index 4c11b4d..0000000
--- a/software/base/src/test/java/brooklyn/entity/software/SoftwareEffectorTest.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software;
-
-import java.util.Arrays;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.software.SshEffectorTasks.SshEffectorBody;
-
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-import com.google.common.base.Throwables;
-
-public class SoftwareEffectorTest {
-
-    private static final Logger log = LoggerFactory.getLogger(SoftwareEffectorTest.class);
-                
-    TestApplication app;
-    ManagementContext mgmt;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setup() throws Exception {
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        mgmt = app.getManagementContext();
-        
-        LocalhostMachineProvisioningLocation lhc = mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class));
-        SshMachineLocation lh = lhc.obtain();
-        app.start(Arrays.asList(lh));
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (mgmt != null) Entities.destroyAll(mgmt);
-        mgmt = null;
-    }
-
-    public static final Effector<String> GET_REMOTE_DATE_1 = Effectors.effector(String.class, "getRemoteDate")
-            .description("retrieves the date from the remote machine")
-            .impl(new SshEffectorBody<String>() {
-                public String call(ConfigBag parameters) {
-                    queue( ssh("date").requiringZeroAndReturningStdout() );
-                    return last(String.class);
-                }
-            })
-            .build();
-
-    public static final Effector<String> GET_REMOTE_DATE_2 = Effectors.effector(GET_REMOTE_DATE_1)
-            // Just get year to confirm implementation is different
-            .description("retrieves the year from the remote machine")
-            .impl(SshEffectorTasks.ssh("date +%Y").requiringZeroAndReturningStdout())
-            .build();
-
-    // TODO revisit next two tests before end 2019 ;)
-
-    @Test(groups="Integration")
-    public void testSshDateEffector1() {
-        Task<String> call = Entities.invokeEffector(app, app, GET_REMOTE_DATE_1);
-        log.info("ssh date 1 gives: "+call.getUnchecked());
-        Assert.assertTrue(call.getUnchecked().indexOf("201") > 0);
-    }
-
-    @Test(groups="Integration")
-    public void testSshDateEffector2() {
-        Task<String> call = Entities.invokeEffector(app, app, GET_REMOTE_DATE_2);
-        log.info("ssh date 2 gives: "+call.getUnchecked());
-        Assert.assertTrue(call.getUnchecked().indexOf("201") == 0);
-    }
-
-    public static final String COMMAND_THAT_DOES_NOT_EXIST = "blah_blah_blah_command_DOES_NOT_EXIST";
-    
-    @Test(groups="Integration")
-    public void testBadExitCodeCaught() {
-        Task<Void> call = Entities.invokeEffector(app, app, Effectors.effector(Void.class, "badExitCode")
-                .impl(new SshEffectorBody<Void>() {
-                    public Void call(ConfigBag parameters) {
-                        queue( ssh(COMMAND_THAT_DOES_NOT_EXIST).requiringZeroAndReturningStdout() );
-                        return null;
-                    }
-                }).build() );
-        try {
-            Object result = call.getUnchecked();
-            Assert.fail("ERROR: should have failed earlier in this test, instead got successful task result "+result+" from "+call);
-        } catch (Exception e) {
-            Throwable root = Throwables.getRootCause(e);
-            if (!(root instanceof IllegalStateException)) Assert.fail("Should have failed with IAE, but got: "+root);
-            if (root.getMessage()==null || root.getMessage().indexOf("exit code")<=0) 
-                Assert.fail("Should have failed with 'exit code' message, but got: "+root);
-            // test passed
-            return;
-        }
-    }
-        
-    @Test(groups="Integration")
-    public void testBadExitCodeCaughtAndStdErrAvailable() {
-        final ProcessTaskWrapper<?>[] sshTasks = new ProcessTaskWrapper[1];
-        
-        Task<Void> call = Entities.invokeEffector(app, app, Effectors.effector(Void.class, "badExitCode")
-                .impl(new SshEffectorBody<Void>() {
-                    public Void call(ConfigBag parameters) {
-                        sshTasks[0] = queue( ssh(COMMAND_THAT_DOES_NOT_EXIST).requiringExitCodeZero() );
-                        return null;
-                    }
-                }).build() );
-        call.blockUntilEnded();
-        Assert.assertTrue(call.isError());
-        log.info("stderr gives: "+new String(sshTasks[0].getStderr()));
-        Assert.assertTrue(new String(sshTasks[0].getStderr()).indexOf(COMMAND_THAT_DOES_NOT_EXIST) >= 0);
-    }
-        
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/SshEffectorTasksTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/software/SshEffectorTasksTest.java b/software/base/src/test/java/brooklyn/entity/software/SshEffectorTasksTest.java
deleted file mode 100644
index c076e56..0000000
--- a/software/base/src/test/java/brooklyn/entity/software/SshEffectorTasksTest.java
+++ /dev/null
@@ -1,263 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Arrays;
-
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.TaskAdaptable;
-import org.apache.brooklyn.api.mgmt.TaskFactory;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.util.core.task.ssh.SshFetchTaskWrapper;
-import org.apache.brooklyn.util.core.task.ssh.SshPutTaskWrapper;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.apache.brooklyn.util.exceptions.PropagatedRuntimeException;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.commons.io.FileUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-import com.google.common.io.Files;
-
-public class SshEffectorTasksTest {
-
-    private static final Logger log = LoggerFactory.getLogger(SshEffectorTasksTest.class);
-    
-    TestApplication app;
-    ManagementContext mgmt;
-    SshMachineLocation host;
-    File tempDir;
-    
-    boolean failureExpected;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setup() throws Exception {
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        mgmt = app.getManagementContext();
-        
-        LocalhostMachineProvisioningLocation lhc = mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class));
-        host = lhc.obtain();
-        app.start(Arrays.asList(host));
-        clearExpectedFailure();
-        tempDir = Files.createTempDir();
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (mgmt != null) Entities.destroyAll(mgmt);
-        mgmt = null;
-        FileUtils.deleteDirectory(tempDir);
-        checkExpectedFailure();
-    }
-
-    protected void checkExpectedFailure() {
-        if (failureExpected) {
-            clearExpectedFailure();
-            Assert.fail("Test should have thrown an exception but it did not.");
-        }
-    }
-    
-    protected void clearExpectedFailure() {
-        failureExpected = false;
-    }
-
-    protected void setExpectingFailure() {
-        failureExpected = true;
-    }
-    
-    public <T extends TaskAdaptable<?>> T submit(final TaskFactory<T> taskFactory) {
-        return Entities.submit(app, taskFactory);
-    }
-    
-    // ------------------- basic ssh
-    
-    @Test(groups="Integration")
-    public void testSshEchoHello() {
-        ProcessTaskWrapper<Integer> t = submit(SshEffectorTasks.ssh("sleep 1 ; echo hello world"));
-        Assert.assertFalse(t.isDone());
-        Assert.assertEquals(t.get(), (Integer)0);
-        Assert.assertEquals(t.getTask().getUnchecked(), (Integer)0);
-        Assert.assertEquals(t.getStdout().trim(), "hello world");
-    }
-
-    @Test(groups="Integration")
-    public void testSshPut() throws IOException {
-        String fn = Urls.mergePaths(tempDir.getPath(), "f1");
-        SshPutTaskWrapper t = submit(SshEffectorTasks.put(fn).contents("hello world"));
-        t.block();
-        Assert.assertEquals(FileUtils.readFileToString(new File(fn)), "hello world");
-        // and make sure this doesn't throw
-        Assert.assertTrue(t.isDone());
-        Assert.assertTrue(t.isSuccessful());
-        Assert.assertEquals(t.get(), null);
-        Assert.assertEquals(t.getExitCode(), (Integer)0);
-    }
-
-    @Test(groups="Integration")
-    public void testSshFetch() throws IOException {
-        String fn = Urls.mergePaths(tempDir.getPath(), "f2");
-        FileUtils.write(new File(fn), "hello fetched world");
-        
-        SshFetchTaskWrapper t = submit(SshEffectorTasks.fetch(fn));
-        t.block();
-        
-        Assert.assertTrue(t.isDone());
-        Assert.assertEquals(t.get(), "hello fetched world");
-    }
-
-    // ----------------- pid stuff
-    
-    @Test(groups="Integration")
-    public void testNonRunningPid() {
-        ProcessTaskWrapper<Integer> t = submit(SshEffectorTasks.codePidRunning(99999));
-        Assert.assertNotEquals(t.getTask().getUnchecked(), (Integer)0);
-        Assert.assertNotEquals(t.getExitCode(), (Integer)0);
-        ProcessTaskWrapper<Boolean> t2 = submit(SshEffectorTasks.isPidRunning(99999));
-        Assert.assertFalse(t2.getTask().getUnchecked());
-    }
-
-    @Test(groups="Integration")
-    public void testNonRunningPidRequired() {
-        ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidRunning(99999));
-        setExpectingFailure();
-        try {
-            t.getTask().getUnchecked();
-        } catch (Exception e) {
-            log.info("The error if required PID is not found is: "+e);
-            clearExpectedFailure();
-            Assert.assertTrue(e.toString().contains("Process with PID"), "Expected nice clue in error but got: "+e);
-        }
-        checkExpectedFailure();
-    }
-
-    public static Integer getMyPid() {
-        try {
-            java.lang.management.RuntimeMXBean runtime = 
-                    java.lang.management.ManagementFactory.getRuntimeMXBean();
-            java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
-            jvm.setAccessible(true);
-//            sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);
-            Object mgmt = jvm.get(runtime);
-            java.lang.reflect.Method pid_method =  
-                    mgmt.getClass().getDeclaredMethod("getProcessId");
-            pid_method.setAccessible(true);
-
-            return (Integer) pid_method.invoke(mgmt);
-        } catch (Exception e) {
-            throw new PropagatedRuntimeException("Test depends on (fragile) getMyPid method which does not work here", e);
-        }
-    }
-
-    @Test(groups="Integration")
-    public void testRunningPid() {
-        ProcessTaskWrapper<Integer> t = submit(SshEffectorTasks.codePidRunning(getMyPid()));
-        Assert.assertEquals(t.getTask().getUnchecked(), (Integer)0);
-        ProcessTaskWrapper<Boolean> t2 = submit(SshEffectorTasks.isPidRunning(getMyPid()));
-        Assert.assertTrue(t2.getTask().getUnchecked());
-    }
-
-    @Test(groups="Integration")
-    public void testRunningPidFromFile() throws IOException {
-        File f = File.createTempFile("testBrooklynPid", ".pid");
-        Files.write( (""+getMyPid()).getBytes(), f );
-        ProcessTaskWrapper<Integer> t = submit(SshEffectorTasks.codePidFromFileRunning(f.getPath()));
-        Assert.assertEquals(t.getTask().getUnchecked(), (Integer)0);
-        ProcessTaskWrapper<Boolean> t2 = submit(SshEffectorTasks.isPidFromFileRunning(f.getPath()));
-        Assert.assertTrue(t2.getTask().getUnchecked());
-    }
-
-    @Test(groups="Integration")
-    public void testRequirePidFromFileOnFailure() throws IOException {
-        File f = File.createTempFile("testBrooklynPid", ".pid");
-        Files.write( "99999".getBytes(), f );
-        ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidFromFileRunning(f.getPath()));
-        
-        setExpectingFailure();
-        try {
-            t.getTask().getUnchecked();
-        } catch (Exception e) {
-            log.info("The error if required PID is not found is: "+e);
-            clearExpectedFailure();
-            Assert.assertTrue(e.toString().contains("Process with PID"), "Expected nice clue in error but got: "+e);
-            Assert.assertEquals(t.getExitCode(), (Integer)1);
-        }
-        checkExpectedFailure();
-    }
-
-    @Test(groups="Integration")
-    public void testRequirePidFromFileOnFailureNoSuchFile() throws IOException {
-        ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidFromFileRunning("/path/does/not/exist/SADVQW"));
-        
-        setExpectingFailure();
-        try {
-            t.getTask().getUnchecked();
-        } catch (Exception e) {
-            log.info("The error if required PID is not found is: "+e);
-            clearExpectedFailure();
-            Assert.assertTrue(e.toString().contains("Process with PID"), "Expected nice clue in error but got: "+e);
-            Assert.assertEquals(t.getExitCode(), (Integer)1);
-        }
-        checkExpectedFailure();
-    }
-
-    @Test(groups="Integration")
-    public void testRequirePidFromFileOnFailureTooManyFiles() throws IOException {
-        ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidFromFileRunning("/*"));
-        
-        setExpectingFailure();
-        try {
-            t.getTask().getUnchecked();
-        } catch (Exception e) {
-            log.info("The error if required PID is not found is: "+e);
-            clearExpectedFailure();
-            Assert.assertTrue(e.toString().contains("Process with PID"), "Expected nice clue in error but got: "+e);
-            Assert.assertEquals(t.getExitCode(), (Integer)2);
-        }
-        checkExpectedFailure();
-    }
-
-    @Test(groups="Integration")
-    public void testRequirePidFromFileOnSuccess() throws IOException {
-        File f = File.createTempFile("testBrooklynPid", ".pid");
-        Files.write( (""+getMyPid()).getBytes(), f );
-        ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidFromFileRunning(f.getPath()));
-        
-        t.getTask().getUnchecked();
-    }
-
-    @Test(groups="Integration")
-    public void testRequirePidFromFileOnSuccessAcceptsWildcards() throws IOException {
-        File f = File.createTempFile("testBrooklynPid", ".pid");
-        Files.write( (""+getMyPid()).getBytes(), f );
-        ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidFromFileRunning(f.getPath()+"*"));
-        
-        t.getTask().getUnchecked();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/StaticSensorTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/software/StaticSensorTest.java b/software/base/src/test/java/brooklyn/entity/software/StaticSensorTest.java
deleted file mode 100644
index 33c4987..0000000
--- a/software/base/src/test/java/brooklyn/entity/software/StaticSensorTest.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.entity.stock.BasicEntity;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableMap;
-
-public class StaticSensorTest extends BrooklynAppUnitTestSupport {
-
-    @Test
-    public void testAddsStaticSensorOfTypeString() {
-        BasicEntity entity = app.createAndManageChild(EntitySpec.create(BasicEntity.class)
-                .addInitializer(new StaticSensor<String>(ConfigBag.newInstance(ImmutableMap.of(
-                        StaticSensor.SENSOR_NAME, "myname",
-                        StaticSensor.SENSOR_TYPE, String.class.getName(),
-                        StaticSensor.STATIC_VALUE, "myval")))));
-        
-        EntityTestUtils.assertAttributeEquals(entity, Sensors.newSensor(String.class, "myname"), "myval");
-    }
-    
-    @Test
-    public void testAddsStaticSensorOfTypeInteger() {
-        BasicEntity entity = app.createAndManageChild(EntitySpec.create(BasicEntity.class)
-                .addInitializer(new StaticSensor<Integer>(ConfigBag.newInstance(ImmutableMap.of(
-                        StaticSensor.SENSOR_NAME, "myname",
-                        StaticSensor.SENSOR_TYPE, Integer.class.getName(),
-                        StaticSensor.STATIC_VALUE, "1")))));
-        
-        EntityTestUtils.assertAttributeEquals(entity, Sensors.newSensor(Integer.class, "myname"), 1);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/http/HttpRequestSensorTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/software/http/HttpRequestSensorTest.java b/software/base/src/test/java/brooklyn/entity/software/http/HttpRequestSensorTest.java
deleted file mode 100644
index d5367f2..0000000
--- a/software/base/src/test/java/brooklyn/entity/software/http/HttpRequestSensorTest.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software.http;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.core.test.TestHttpRequestHandler;
-import org.apache.brooklyn.core.test.TestHttpServer;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.time.Duration;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-
-public class HttpRequestSensorTest {
-    final static AttributeSensor<String> SENSOR_STRING = Sensors.newStringSensor("aString");
-    final static String TARGET_TYPE = "java.lang.String";
-
-    private TestApplication app;
-    private EntityLocal entity;
-
-    private TestHttpServer server;
-    private String serverUrl;
-
-    @BeforeClass(alwaysRun=true)
-    public void setUp() throws Exception {
-        server = new TestHttpServer()
-            .handler("/myKey/myValue", new TestHttpRequestHandler().header("Content-Type", "application/json").response("{\"myKey\":\"myValue\"}"))
-            .start();
-        serverUrl = server.getUrl();
-
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        entity = app.createAndManageChild(EntitySpec.create(TestEntity.class)
-                .location(app.newLocalhostProvisioningLocation().obtain()));
-        app.start(ImmutableList.<Location>of());
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-        server.stop();
-    }
-
-    @Test
-    public void testHttpSensor() throws Exception {
-        HttpRequestSensor<Integer> sensor = new HttpRequestSensor<Integer>(ConfigBag.newInstance()
-                .configure(HttpRequestSensor.SENSOR_PERIOD, Duration.millis(100))
-                .configure(HttpRequestSensor.SENSOR_NAME, SENSOR_STRING.getName())
-                .configure(HttpRequestSensor.SENSOR_TYPE, TARGET_TYPE)
-                .configure(HttpRequestSensor.JSON_PATH, "$.myKey")
-                .configure(HttpRequestSensor.SENSOR_URI, serverUrl + "/myKey/myValue"));
-        sensor.apply(entity);
-        entity.setAttribute(Attributes.SERVICE_UP, true);
-
-        EntityTestUtils.assertAttributeEqualsEventually(entity, SENSOR_STRING, "myValue");
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/mysql/AbstractToyMySqlEntityTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/software/mysql/AbstractToyMySqlEntityTest.java b/software/base/src/test/java/brooklyn/entity/software/mysql/AbstractToyMySqlEntityTest.java
deleted file mode 100644
index 7a465de..0000000
--- a/software/base/src/test/java/brooklyn/entity/software/mysql/AbstractToyMySqlEntityTest.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software.mysql;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.BeforeMethod;
-
-import brooklyn.entity.software.SshEffectorTasks;
-
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-import com.google.common.base.Predicates;
-import com.google.common.collect.Iterables;
-
-
-public abstract class AbstractToyMySqlEntityTest extends BrooklynAppLiveTestSupport {
-
-    private static final Logger log = LoggerFactory.getLogger(AbstractToyMySqlEntityTest.class);
-    
-    protected MachineProvisioningLocation<? extends SshMachineLocation> targetLocation;
-
-    @Override
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        super.setUp();
-        
-        targetLocation = createLocation();
-    }
-
-    protected MachineProvisioningLocation<? extends SshMachineLocation> createLocation() {
-        return mgmt.getLocationManager().createLocation(LocationSpec.create(
-                LocalhostMachineProvisioningLocation.class));
-    }
-    
-    protected abstract Entity createMysql();
-
-    // deliberately not marked as a test here so that subclasses mark it correctly (Live v Integration)
-    public void testMySqlOnProvisioningLocation() throws Exception {
-        Entity mysql = createMysql();
-        app.start(MutableList.of(targetLocation));
-        checkStartsRunning(mysql);
-        checkIsRunningAndStops(mysql, (SshMachineLocation) Iterables.getOnlyElement( mysql.getLocations() ));
-    }
-
-    protected Integer getPid(Entity mysql) {
-        return mysql.getAttribute(Attributes.PID);
-    }
-
-    protected void checkStartsRunning(Entity mysql) {
-        // should be starting within a few seconds (and almost certainly won't complete in that time)
-        EntityTestUtils.assertAttributeEventually(
-                mysql, 
-                Attributes.SERVICE_STATE_ACTUAL,
-                Predicates.or(Predicates.equalTo(Lifecycle.STARTING), Predicates.equalTo(Lifecycle.RUNNING)));
-        // should be up and running within 5m 
-        EntityTestUtils.assertAttributeEqualsEventually(MutableMap.of("timeout", Duration.FIVE_MINUTES),
-                mysql, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
-    }
-
-    protected void checkIsRunningAndStops(Entity mysql, SshMachineLocation lh) {
-        Integer pid = getPid(mysql);
-        Assert.assertNotNull(pid, "PID should be set as an attribute (or getPid() overridden to supply)");
-        Entities.submit(app, SshEffectorTasks.requirePidRunning(pid).machine(lh).newTask() ).get();
-        
-        app.stop();
-
-        // let the kill -1 take effect 
-        Time.sleep(Duration.ONE_SECOND);
-        
-        // and assert it has died
-        log.info("mysql in pid "+pid+" should be dead now");
-        // (app has stopped, so submit on mgmt context)
-        ProcessTaskWrapper<Integer> t = SshEffectorTasks.codePidRunning(pid).machine(lh).newTask();
-        mgmt.getExecutionManager().submit(t);
-        Assert.assertNotEquals(t.block().getExitCode(), (Integer)0);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityBuilder.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityBuilder.java b/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityBuilder.java
deleted file mode 100644
index 91f402d..0000000
--- a/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityBuilder.java
+++ /dev/null
@@ -1,191 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software.mysql;
-
-import java.io.File;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntityInitializer;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.OsDetails;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.stock.BasicStartable;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.software.MachineLifecycleEffectorTasks;
-import brooklyn.entity.software.SshEffectorTasks;
-
-import org.apache.brooklyn.location.basic.BasicOsDetails.OsVersions;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.core.task.ssh.SshTasks;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.apache.brooklyn.util.ssh.BashCommands;
-import org.apache.brooklyn.util.text.ComparableVersion;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-
-import com.google.common.base.Predicates;
-import com.google.common.base.Splitter;
-import com.google.common.base.Supplier;
-import com.google.common.base.Suppliers;
-import com.google.common.collect.Iterables;
-
-public class DynamicToyMySqlEntityBuilder {
-
-    private static final Logger log = LoggerFactory.getLogger(DynamicToyMySqlEntityBuilder.class);
-
-    public static EntitySpec<? extends Entity> spec() {
-        return EntitySpec.create(BasicStartable.class).addInitializer(MySqlEntityInitializer.class);
-    }
-
-    public static final String downloadUrl(Entity e, boolean isLocalhost) {
-        if (isLocalhost) {
-            for (int i=50; i>20; i--) {
-                String f = System.getProperty("user.home")+"/.brooklyn/repository/MySqlNode/5.5."+i+"/mysql-5.5."+i+"-osx10.6-x86_64.tar.gz";
-                if (new File(f).exists())
-                    return "file://"+f;
-            }
-        }
-        // download
-        String version = "5.5.37";
-        String osTag = getOsTag(e);
-        String mirrorUrl = "http://www.mirrorservice.org/sites/ftp.mysql.com/";
-        return "http://dev.mysql.com/get/Downloads/MySQL-5.5/mysql-"+version+"-"+osTag+".tar.gz/from/"+mirrorUrl;
-    }
-
-    public static final String installDir(Entity e, boolean isLocalhost) {
-        String url = downloadUrl(e, isLocalhost);
-        String archive = Iterables.find(Splitter.on('/').omitEmptyStrings().split(url), Predicates.containsPattern(".tar.gz"));
-        return archive.replace(".tar.gz", "");
-    }
-
-    public static final String dir(Entity e) {
-        return "/tmp/brooklyn-mysql-"+e.getId();
-    }
-
-    // copied from MySqlSshDriver
-    public static String getOsTag(Entity e) {
-        // e.g. "osx10.6-x86_64"; see http://www.mysql.com/downloads/mysql/#downloads
-        OsDetails os = ((SshMachineLocation)Iterables.getOnlyElement(e.getLocations())).getOsDetails();
-        if (os == null) return "linux-glibc2.5-x86_64";
-        if (os.isMac()) {
-            String osp1 = os.getVersion()==null ? "osx10.8" //lowest common denominator
-                : new ComparableVersion(os.getVersion()).isGreaterThanOrEqualTo(OsVersions.MAC_10_9) ? "osx10.9"
-                : "osx10.8";  //lowest common denominator
-            if (!os.is64bit()) {
-                throw new IllegalStateException("Only 64 bit MySQL build is available for OS X");
-            }
-            return osp1+"-x86_64";
-        }
-        //assume generic linux
-        String osp1 = "linux-glibc2.5";
-        String osp2 = os.is64bit() ? "x86_64" : "i686";
-        return osp1+"-"+osp2;
-    }
-
-    public static class MySqlEntityInitializer implements EntityInitializer {
-        public void apply(final EntityLocal entity) {
-          new MachineLifecycleEffectorTasks() {
-            @Override
-            protected String startProcessesAtMachine(Supplier<MachineLocation> machineS) {
-                DynamicTasks.queue(
-                        SshEffectorTasks.ssh(
-                            "mkdir "+dir(entity),
-                            "cd "+dir(entity),
-                            BashCommands.downloadToStdout(downloadUrl(entity, isLocalhost(machineS)))+" | tar xvz"
-                        ).summary("download mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true)));
-                if (isLinux(machineS)) {
-                    DynamicTasks.queue(SshEffectorTasks.ssh(BashCommands.installPackage("libaio1")));
-                }
-                DynamicTasks.queue(
-                        SshEffectorTasks.put(".my.cnf")
-                            .contents(String.format("[mysqld]\nbasedir=%s/%s\n", dir(entity), installDir(entity, isLocalhost(machineS)))),
-                        SshEffectorTasks.ssh(
-                            "cd "+dir(entity)+"/*",
-                            "./scripts/mysql_install_db",
-                            "./support-files/mysql.server start > out.log 2> err.log < /dev/null"
-                        ).summary("setup and run mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true)));
-                return "submitted start";
-            }
-            protected void postStartCustom() {
-                // if it's still up after 5s assume we are good
-                Time.sleep(Duration.FIVE_SECONDS);
-                if (!DynamicTasks.queue(SshEffectorTasks.isPidFromFileRunning(dir(entity)+"/*/data/*.pid")).get()) {
-                    // but if it's not up add a bunch of other info
-                    log.warn("MySQL did not start: "+dir(entity));
-                    ProcessTaskWrapper<Integer> info = DynamicTasks.queue(SshEffectorTasks.ssh(
-                            "cd "+dir(entity)+"/*",
-                            "cat out.log",
-                            "cat err.log > /dev/stderr")).block();
-                    log.info("STDOUT:\n"+info.getStdout());
-                    log.info("STDERR:\n"+info.getStderr());
-                    BrooklynTaskTags.addTagsDynamically(Tasks.current(), 
-                        BrooklynTaskTags.tagForStream("console (nohup stdout)", Suppliers.ofInstance(info.getStdout()), null),
-                        BrooklynTaskTags.tagForStream("console (nohup stderr)", Suppliers.ofInstance(info.getStderr()), null));
-                    throw new IllegalStateException("MySQL appears not to be running");
-                }
-
-                // and set the PID
-                entity().setAttribute(Attributes.PID, 
-                        Integer.parseInt(DynamicTasks.queue(SshEffectorTasks.ssh("cat "+dir(entity)+"/*/data/*.pid")).block().getStdout().trim()));
-                
-                // TODO Without this, tests fail because nothing else sets serviceUp!
-                // Really should set this with a Feed that checks pid periodically.
-                // Should this instead be using SERVICE_NOT_UP_INDICATORS?
-                entity().setAttribute(Attributes.SERVICE_UP, true);
-            }
-
-            @Override
-            protected String stopProcessesAtMachine() {
-                // TODO Where is best place to set? 
-                // Really should set this with a Feed that checks pid periodically.
-                entity().setAttribute(Attributes.SERVICE_UP, false);
-                
-                Integer pid = entity().getAttribute(Attributes.PID);
-                if (pid==null) {
-                    log.info("mysql not running");
-                    return "No pid -- is it running?";
-                }
-
-                DynamicTasks.queue(SshEffectorTasks.ssh(
-                        "cd "+dir(entity)+"/*",
-                        "./support-files/mysql.server stop"
-                    ).summary("stop mysql"));
-                return "submitted stop";
-            }
-          }.attachLifecycleEffectors(entity);
-      }
-    }
-
-    private static boolean isLocalhost(Supplier<MachineLocation> machineS) {
-        return machineS.get() instanceof LocalhostMachine;
-    }
-
-    private static boolean isLinux(Supplier<MachineLocation> machineS) {
-        return machineS.get().getMachineDetails().getOsDetails().isLinux();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityTest.java b/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityTest.java
deleted file mode 100644
index 75684f5..0000000
--- a/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityTest.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software.mysql;
-
-import java.util.Arrays;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.util.collections.MutableMap;
-
-
-public class DynamicToyMySqlEntityTest extends AbstractToyMySqlEntityTest {
-
-    private static final Logger log = LoggerFactory.getLogger(DynamicToyMySqlEntityTest.class);
-    
-    protected Entity createMysql() {
-        Entity mysql = app.createAndManageChild(DynamicToyMySqlEntityBuilder.spec());
-        log.debug("created "+mysql);
-        return mysql;
-    }
-
-    // put right group on test (also help Eclipse IDE pick it up)
-    @Override
-    @Test(groups = "Integration")
-    public void testMySqlOnProvisioningLocation() throws Exception {
-        super.testMySqlOnProvisioningLocation();
-    }
-    
-    @Test(groups="Integration")
-    public void testMySqlOnMachineLocation() throws Exception {
-        Entity mysql = createMysql();
-        SshMachineLocation lh = targetLocation.obtain(MutableMap.of());
-        
-        app.start(Arrays.asList(lh));
-        checkStartsRunning(mysql);
-        checkIsRunningAndStops(mysql, lh);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/ssh/SshCommandIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/software/ssh/SshCommandIntegrationTest.java b/software/base/src/test/java/brooklyn/entity/software/ssh/SshCommandIntegrationTest.java
deleted file mode 100644
index 085b737..0000000
--- a/software/base/src/test/java/brooklyn/entity/software/ssh/SshCommandIntegrationTest.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.software.ssh;
-
-import static org.testng.Assert.assertTrue;
-
-import java.io.File;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.time.Duration;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-import com.google.common.collect.ImmutableList;
-
-public class SshCommandIntegrationTest {
-
-    final static AttributeSensor<String> SENSOR_STRING = Sensors.newStringSensor("aString", "");
-    final static AttributeSensor<Integer> SENSOR_INT = Sensors.newIntegerSensor("aLong", "");
-    final static Effector<String> EFFECTOR_SAY_HI = Effectors.effector(String.class, "sayHi").buildAbstract();
-
-    private TestApplication app;
-    private SshMachineLocation machine;
-    private EntityLocal entity;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        machine = app.newLocalhostProvisioningLocation().obtain();
-        entity = app.createAndManageChild(EntitySpec.create(TestEntity.class).location(machine));
-        app.start(ImmutableList.<Location>of());
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-    }
-    
-    @Test(groups="Integration")
-    public void testSshSensor() throws Exception {
-        File tempFile = File.createTempFile("testSshCommand", "txt");
-        tempFile.deleteOnExit();
-        new SshCommandSensor<String>(ConfigBag.newInstance()
-                .configure(SshCommandSensor.SENSOR_PERIOD, Duration.millis(100))
-                .configure(SshCommandSensor.SENSOR_NAME, SENSOR_STRING.getName())
-                .configure(SshCommandSensor.SENSOR_COMMAND, "echo foo > "+tempFile.getAbsolutePath()+"\n"
-                    + "wc "+tempFile.getAbsolutePath()))
-            .apply(entity);
-        entity.setAttribute(Attributes.SERVICE_UP, true);
-
-        String val = EntityTestUtils.assertAttributeEventuallyNonNull(entity, SENSOR_STRING);
-        assertTrue(val.contains("1"), "val="+val);
-        String[] counts = val.trim().split("\\s+");
-        Assert.assertEquals(counts.length, 4, "val="+val);
-        Assert.assertEquals(counts[0], "1", "val="+val);
-    }
-
-    @Test(groups="Integration")
-    public void testSshEffector() throws Exception {
-        File tempFile = File.createTempFile("testSshCommand", "txt");
-        tempFile.deleteOnExit();
-        new SshCommandEffector(ConfigBag.newInstance()
-                .configure(SshCommandEffector.EFFECTOR_NAME, "sayHi")
-                .configure(SshCommandEffector.EFFECTOR_COMMAND, "echo hi"))
-            .apply(entity);
-        
-        String val = entity.invoke(EFFECTOR_SAY_HI, MutableMap.<String,String>of()).get();
-        Assert.assertEquals(val.trim(), "hi", "val="+val);
-    }
-
-    @Test(groups="Integration")
-    public void testSshEffectorWithParameters() throws Exception {
-        File tempFile = File.createTempFile("testSshCommand", "txt");
-        tempFile.deleteOnExit();
-        new SshCommandEffector(ConfigBag.newInstance()
-                .configure(SshCommandEffector.EFFECTOR_NAME, "sayHi")
-                .configure(SshCommandEffector.EFFECTOR_COMMAND, "echo $foo")
-                .configure(SshCommandEffector.EFFECTOR_PARAMETER_DEFS, 
-                    MutableMap.<String,Object>of("foo", MutableMap.of("defaultValue", "hi"))))
-            .apply(entity);
-        
-        String val;
-        // explicit value
-        val = entity.invoke(EFFECTOR_SAY_HI, MutableMap.<String,String>of("foo", "bar")).get();
-        Assert.assertEquals(val.trim(), "bar", "val="+val);
-        
-        // default value
-        val = entity.invoke(EFFECTOR_SAY_HI, MutableMap.<String,String>of()).get();
-        Assert.assertEquals(val.trim(), "hi", "val="+val);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/event/basic/PortAttributeSensorAndConfigKeyTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/event/basic/PortAttributeSensorAndConfigKeyTest.java b/software/base/src/test/java/brooklyn/event/basic/PortAttributeSensorAndConfigKeyTest.java
deleted file mode 100644
index 8bcbb67..0000000
--- a/software/base/src/test/java/brooklyn/event/basic/PortAttributeSensorAndConfigKeyTest.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.event.basic;
-
-import static org.testng.Assert.assertEquals;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.entity.core.Entities;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.EmptySoftwareProcess;
-import brooklyn.entity.basic.EmptySoftwareProcessImpl;
-
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
-
-import com.google.common.collect.ImmutableList;
-
-public class PortAttributeSensorAndConfigKeyTest extends BrooklynAppUnitTestSupport {
-
-    /*
-     * FIXME Fails because port is never released. Nothing calls PortSupplier.releasePort(int).
-     * The stacktrace below shows where it is obtained:
-     * 
-        Daemon Thread [brooklyn-execmanager-XwLLLdS4-5] (Suspended (breakpoint at line 244 in LocalhostMachineProvisioningLocation$LocalhostMachine))   
-            LocalhostMachineProvisioningLocation$LocalhostMachine.obtainPort(PortRange) line: 244   
-            PortAttributeSensorAndConfigKey.convertConfigToSensor(PortRange, Entity) line: 78   
-            PortAttributeSensorAndConfigKey.convertConfigToSensor(Object, Entity) line: 1   
-            PortAttributeSensorAndConfigKey(AttributeSensorAndConfigKey<ConfigType,SensorType>).getAsSensorValue(Entity) line: 93   
-            ConfigToAttributes.apply(EntityLocal, AttributeSensorAndConfigKey<?,T>) line: 28    
-            ConfigToAttributes.apply(EntityLocal) line: 17  
-            SoftwareProcessDriverLifecycleEffectorTasks(MachineLifecycleEffectorTasks).preStartCustom(MachineLocation) line: 343    
-            SoftwareProcessDriverLifecycleEffectorTasks.preStartCustom(MachineLocation) line: 69    
-            MachineLifecycleEffectorTasks$6.run() line: 283 
-     */
-    @Test(enabled=false, groups="Integration") // test is slow (for some reason - why?)
-    public void testStoppingEntityReleasesPortFromMachineForReuse() throws Exception {
-        LocalhostMachineProvisioningLocation loc = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost");
-        SshMachineLocation machine = loc.obtain();
-        runStoppingEntityReleasesPortFromLocalhostForReuse(machine);
-    }
-
-    @Test(groups="Integration") // test is slow (for some reason - why?)
-    public void testStoppingEntityReleasesPortFromLocalhostProvisioningLocationForReuse() throws Exception {
-        LocalhostMachineProvisioningLocation loc = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost");
-        runStoppingEntityReleasesPortFromLocalhostForReuse(loc);
-    }
-    
-    protected void runStoppingEntityReleasesPortFromLocalhostForReuse(Location loc) throws Exception {
-        MyEntity e1 = app.createAndManageChild(EntitySpec.create(MyEntity.class));
-        e1.start(ImmutableList.of(loc));
-        assertEquals(e1.getAttribute(MyEntity.MY_PORT), (Integer)47653);
-        
-        e1.stop();
-        Entities.unmanage(e1);
-        MyEntity e2 = app.createAndManageChild(EntitySpec.create(MyEntity.class));
-        e2.start(ImmutableList.of(loc));
-        assertEquals(e2.getAttribute(MyEntity.MY_PORT), (Integer)47653);
-    }
-
-    @ImplementedBy(MyEntityImpl.class)
-    public interface MyEntity extends EmptySoftwareProcess {
-        PortAttributeSensorAndConfigKey MY_PORT = new PortAttributeSensorAndConfigKey("myport", "", "47653");
-    }
-    
-    public static class MyEntityImpl extends EmptySoftwareProcessImpl implements MyEntity {
-    }        
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/event/feed/jmx/JmxFeedTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/event/feed/jmx/JmxFeedTest.java b/software/base/src/test/java/brooklyn/event/feed/jmx/JmxFeedTest.java
deleted file mode 100644
index f0c51a2..0000000
--- a/software/base/src/test/java/brooklyn/event/feed/jmx/JmxFeedTest.java
+++ /dev/null
@@ -1,418 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.event.feed.jmx;
-
-import static org.apache.brooklyn.test.TestUtils.executeUntilSucceeds;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import javax.management.MBeanOperationInfo;
-import javax.management.MBeanParameterInfo;
-import javax.management.Notification;
-import javax.management.NotificationListener;
-import javax.management.ObjectName;
-import javax.management.StandardEmitterMBean;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenType;
-import javax.management.openmbean.SimpleType;
-import javax.management.openmbean.TabularDataSupport;
-import javax.management.openmbean.TabularType;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.api.sensor.SensorEvent;
-import org.apache.brooklyn.api.sensor.SensorEventListener;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.core.test.entity.TestApplicationImpl;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.core.test.entity.TestEntityImpl;
-import org.apache.brooklyn.entity.core.AbstractEntity;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
-import org.apache.brooklyn.sensor.core.BasicNotificationSensor;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.test.TestUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.testng.collections.Lists;
-
-import brooklyn.entity.java.JmxSupport;
-import brooklyn.entity.java.UsesJmx;
-import brooklyn.entity.java.UsesJmx.JmxAgentModes;
-
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.PortRanges;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
-
-import brooklyn.test.GeneralisedDynamicMBean;
-import brooklyn.test.JmxService;
-
-import com.google.common.base.Function;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-/**
- * Test the operation of the {@link JmxFeed} class.
- * <p>
- * Also confirm some of the JMX setup done by {@link JmxSupport} and {@link JmxHelper},
- * based on ports in {@link UsesJmx}.
- * <p>
- * TODO tests of other JMX_AGENT_MODE are done in ActiveMqIntegrationTest; 
- * would be nice to promote some to live here
- */
-public class JmxFeedTest {
-    
-    // FIXME Move out the JmxHelper tests into the JmxHelperTest class
-    
-    // FIXME Also test that setting poll period takes effect
-    
-    private static final Logger log = LoggerFactory.getLogger(JmxFeedTest.class);
-
-    private static final int TIMEOUT_MS = 5000;
-    private static final int SHORT_WAIT_MS = 250;
-    
-    private JmxService jmxService;
-    private TestApplication app;
-    private TestEntity entity;
-    private JmxFeed feed;
-    private JmxHelper jmxHelper;
-    
-    private AttributeSensor<Integer> intAttribute = Sensors.newIntegerSensor("brooklyn.test.intAttribute", "Brooklyn testing int attribute");
-    private AttributeSensor<String> stringAttribute = Sensors.newStringSensor("brooklyn.test.stringAttribute", "Brooklyn testing string attribute");
-    private BasicAttributeSensor<Map> mapAttribute = new BasicAttributeSensor<Map>(Map.class, "brooklyn.test.mapAttribute", "Brooklyn testing map attribute");
-    private String objectName = "Brooklyn:type=MyTestMBean,name=myname";
-    private ObjectName jmxObjectName;
-    private String attributeName = "myattrib";
-    private String opName = "myop";
-    
-    public static class TestEntityWithJmx extends TestEntityImpl {
-        @Override public void init() {
-            setAttribute(Attributes.HOSTNAME, "localhost");
-            setAttribute(UsesJmx.JMX_PORT, 
-                    LocalhostMachineProvisioningLocation.obtainPort(PortRanges.fromString("40123+")));
-            // only supports no-agent, at the moment
-            setConfig(UsesJmx.JMX_AGENT_MODE, JmxAgentModes.NONE);
-            setAttribute(UsesJmx.RMI_REGISTRY_PORT, -1);  // -1 means to use the JMX_PORT only
-            ConfigToAttributes.apply(this, UsesJmx.JMX_CONTEXT);
-        }
-    }
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        jmxObjectName = new ObjectName(objectName);
-        
-        // Create an entity and configure it with the above JMX service
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        entity = app.createAndManageChild(EntitySpec.create(TestEntity.class).impl(TestEntityWithJmx.class));
-        app.start(ImmutableList.of(new SimulatedLocation()));
-
-        jmxHelper = new JmxHelper(entity);
-        
-        jmxService = new JmxService(entity);
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (feed != null) feed.stop();
-        if (jmxHelper != null) jmxHelper.disconnect();
-        if (jmxService != null) jmxService.shutdown();
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-        feed = null;
-    }
-
-    @Test
-    public void testJmxAttributePollerReturnsMBeanAttribute() throws Exception {
-        GeneralisedDynamicMBean mbean = jmxService.registerMBean(ImmutableMap.of(attributeName, 42), objectName);
-
-        feed = JmxFeed.builder()
-                .entity(entity)
-                .pollAttribute(new JmxAttributePollConfig<Integer>(intAttribute)
-                        .objectName(objectName)
-                        .period(50)
-                        .attributeName(attributeName))
-                .build();
-        
-        // Starts with value defined when registering...
-        assertSensorEventually(intAttribute, 42, TIMEOUT_MS);
-
-        // Change the value and check it updates
-        mbean.updateAttributeValue(attributeName, 64);
-        assertSensorEventually(intAttribute, 64, TIMEOUT_MS);
-    }
-
-    @Test
-    public void testJmxAttributeOfTypeTabularDataProviderConvertedToMap() throws Exception {
-        // Create the CompositeType and TabularData
-        CompositeType compositeType = new CompositeType(
-                "typeName",
-                "description",
-                new String[] {"myint", "mystring", "mybool"},    // item names
-                new String[] {"myint", "mystring", "mybool"},    // item descriptions, can't be null or empty string
-                new OpenType<?>[] {SimpleType.INTEGER, SimpleType.STRING, SimpleType.BOOLEAN}
-        );
-        TabularType tt = new TabularType(
-                "typeName",
-                "description",
-                compositeType,
-                new String[] {"myint"}
-        );
-        TabularDataSupport tds = new TabularDataSupport(tt);
-        tds.put(new CompositeDataSupport(
-                compositeType,
-                new String[] {"mybool", "myint", "mystring"},
-                new Object[] {true, 1234, "on"}
-        ));
-
-        // Create MBean
-        GeneralisedDynamicMBean mbean = jmxService.registerMBean(ImmutableMap.of(attributeName, tds), objectName);
-
-        feed = JmxFeed.builder()
-                .entity(entity)
-                .pollAttribute(new JmxAttributePollConfig<Map>(mapAttribute)
-                        .objectName(objectName)
-                        .attributeName(attributeName)
-                        .onSuccess((Function)JmxValueFunctions.tabularDataToMap()))
-                .build();
-
-        // Starts with value defined when registering...
-        assertSensorEventually(
-                mapAttribute, 
-                ImmutableMap.of("myint", 1234, "mystring", "on", "mybool", Boolean.TRUE), 
-                TIMEOUT_MS);
-    }
-
-    @Test
-    public void testJmxOperationPolledForSensor() throws Exception {
-        // This is awful syntax...
-        final int opReturnVal = 123;
-        final AtomicInteger invocationCount = new AtomicInteger();
-        MBeanOperationInfo opInfo = new MBeanOperationInfo(opName, "my descr", new MBeanParameterInfo[0], Integer.class.getName(), MBeanOperationInfo.ACTION);
-        GeneralisedDynamicMBean mbean = jmxService.registerMBean(
-                Collections.emptyMap(), 
-                ImmutableMap.of(opInfo, new Function<Object[], Integer>() {
-                        public Integer apply(Object[] args) {
-                            invocationCount.incrementAndGet(); return opReturnVal;
-                        }}),
-                objectName);
-
-        feed = JmxFeed.builder()
-                .entity(entity)
-                .pollOperation(new JmxOperationPollConfig<Integer>(intAttribute)
-                        .objectName(objectName)
-                        .operationName(opName))
-                .build();
-        
-        TestUtils.executeUntilSucceeds(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
-            public void run() {
-                assertTrue(invocationCount.get() > 0, "invocationCount="+invocationCount);
-                assertEquals(entity.getAttribute(intAttribute), (Integer)opReturnVal);
-            }});
-    }
-
-    @Test
-    public void testJmxOperationWithArgPolledForSensor() throws Exception {
-        // This is awful syntax...
-        MBeanParameterInfo paramInfo = new MBeanParameterInfo("param1", String.class.getName(), "my param1");
-        MBeanParameterInfo[] paramInfos = new MBeanParameterInfo[] {paramInfo};
-        MBeanOperationInfo opInfo = new MBeanOperationInfo(opName, "my descr", paramInfos, String.class.getName(), MBeanOperationInfo.ACTION);
-        GeneralisedDynamicMBean mbean = jmxService.registerMBean(
-                Collections.emptyMap(), 
-                ImmutableMap.of(opInfo, new Function<Object[], String>() {
-                        public String apply(Object[] args) {
-                            return args[0]+"suffix";
-                        }}),
-                objectName);
-        
-        feed = JmxFeed.builder()
-                .entity(entity)
-                .pollOperation(new JmxOperationPollConfig<String>(stringAttribute)
-                        .objectName(objectName)
-                        .operationName(opName)
-                        .operationParams(ImmutableList.of("myprefix")))
-                .build();
-        
-        assertSensorEventually(stringAttribute, "myprefix"+"suffix", TIMEOUT_MS);
-    }
-
-    @Test
-    public void testJmxNotificationSubscriptionForSensor() throws Exception {
-        final String one = "notification.one", two = "notification.two";
-        final StandardEmitterMBean mbean = jmxService.registerMBean(ImmutableList.of(one, two), objectName);
-        final AtomicInteger sequence = new AtomicInteger(0);
-
-        feed = JmxFeed.builder()
-                .entity(entity)
-                .subscribeToNotification(new JmxNotificationSubscriptionConfig<Integer>(intAttribute)
-                        .objectName(objectName)
-                        .notificationFilter(JmxNotificationFilters.matchesType(one)))
-                .build();        
-
-        // Notification updates the sensor
-        // Note that subscription is done async, so can't just send notification immediately during test.
-        Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
-            public void run() {
-                sendNotification(mbean, one, sequence.getAndIncrement(), 123);
-                assertEquals(entity.getAttribute(intAttribute), (Integer)123);
-            }});
-        
-        // But other notification types are ignored
-        sendNotification(mbean, two, sequence.getAndIncrement(), -1);
-            
-        Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
-            public void run() {
-                assertEquals(entity.getAttribute(intAttribute), (Integer)123);
-            }});
-    }
-    
-    @Test
-    public void testJmxNotificationSubscriptionForSensorParsingNotification() throws Exception {
-        final String one = "notification.one", two = "notification.two";
-        final StandardEmitterMBean mbean = jmxService.registerMBean(ImmutableList.of(one, two), objectName);
-        final AtomicInteger sequence = new AtomicInteger(0);
-        
-        feed = JmxFeed.builder()
-                .entity(entity)
-                .subscribeToNotification(new JmxNotificationSubscriptionConfig<Integer>(intAttribute)
-                        .objectName(objectName)
-                        .notificationFilter(JmxNotificationFilters.matchesType(one))
-                        .onNotification(new Function<Notification, Integer>() {
-                            public Integer apply(Notification notif) {
-                                return (Integer) notif.getUserData();
-                            }
-                        }))
-                .build();
-        
-        
-        // Notification updates the sensor
-        // Note that subscription is done async, so can't just send notification immediately during test.
-        Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
-            public void run() {
-                sendNotification(mbean, one, sequence.getAndIncrement(), 123);
-                assertEquals(entity.getAttribute(intAttribute), (Integer)123);
-            }});
-    }
-
-    @Test
-    public void testJmxNotificationMultipleSubscriptionUsingListener() throws Exception {
-        final String one = "notification.one";
-        final String two = "notification.two";
-        final StandardEmitterMBean mbean = jmxService.registerMBean(ImmutableList.of(one, two), objectName);
-        final AtomicInteger sequence = new AtomicInteger(0);
-
-        feed = JmxFeed.builder()
-                .entity(entity)
-                .subscribeToNotification(new JmxNotificationSubscriptionConfig<Integer>(intAttribute)
-                        .objectName(objectName)
-                        .notificationFilter(JmxNotificationFilters.matchesTypes(one, two)))
-                .build();
-        
-        // Notification updates the sensor
-        // Note that subscription is done async, so can't just send notification immediately during test.
-        Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
-            public void run() {
-                sendNotification(mbean, one, sequence.getAndIncrement(), 123);
-                assertEquals(entity.getAttribute(intAttribute), (Integer)123);
-            }});
-
-        // And wildcard means other notifications also received
-        sendNotification(mbean, two, sequence.getAndIncrement(), 456);
-        assertSensorEventually(intAttribute, 456, TIMEOUT_MS);
-    }
-
-    // Test reproduces functionality used in Monterey, for Venue entity being told of requestActor
-    @Test
-    public void testSubscribeToJmxNotificationAndEmitCorrespondingNotificationSensor() throws Exception {
-        TestApplication app2 = new TestApplicationImpl();
-        final EntityWithEmitter entity = new EntityWithEmitter(app2);
-        Entities.startManagement(app2);
-        try {
-            app2.start(ImmutableList.of(new SimulatedLocation()));
-            
-            final List<SensorEvent<String>> received = Lists.newArrayList();
-            app2.subscribe(null, EntityWithEmitter.MY_NOTIF, new SensorEventListener<String>() {
-                public void onEvent(SensorEvent<String> event) {
-                    received.add(event);
-                }});
-    
-            final StandardEmitterMBean mbean = jmxService.registerMBean(ImmutableList.of("one"), objectName);
-            final AtomicInteger sequence = new AtomicInteger(0);
-            
-            jmxHelper.connect(TIMEOUT_MS);
-            jmxHelper.addNotificationListener(jmxObjectName, new NotificationListener() {
-                    public void handleNotification(Notification notif, Object callback) {
-                        if (notif.getType().equals("one")) {
-                            entity.emit(EntityWithEmitter.MY_NOTIF, (String) notif.getUserData());
-                        }
-                    }});
-            
-
-            Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
-                public void run() {
-                    sendNotification(mbean, "one", sequence.getAndIncrement(), "abc");
-                    assertTrue(received.size() > 0, "received size should be bigger than 0");
-                    assertEquals(received.get(0).getValue(), "abc");
-                }});
-        } finally {
-            Entities.destroyAll(app2.getManagementContext());
-        }
-    }
-    
-    public static class EntityWithEmitter extends AbstractEntity {
-        public static final BasicNotificationSensor<String> MY_NOTIF = new BasicNotificationSensor<String>(String.class, "test.myNotif", "My notif");
-        
-        public EntityWithEmitter(Entity owner) {
-            super(owner);
-        }
-        public EntityWithEmitter(Map flags) {
-            super(flags);
-        }
-        public EntityWithEmitter(Map flags, Entity owner) {
-            super(flags, owner);
-        }
-    }
-    
-    private Notification sendNotification(StandardEmitterMBean mbean, String type, long seq, Object userData) {
-        Notification notif = new Notification(type, mbean, seq);
-        notif.setUserData(userData);
-        mbean.sendNotification(notif);
-        return notif;
-    }
-    
-    private <T> void assertSensorEventually(final AttributeSensor<T> sensor, final T expectedVal, long timeout) {
-        executeUntilSucceeds(ImmutableMap.of("timeout", timeout), new Callable<Void>() {
-            public Void call() {
-                assertEquals(entity.getAttribute(sensor), expectedVal);
-                return null;
-            }});
-    }
-}


[46/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/MultiLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/MultiLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/core/MultiLocationTest.java
new file mode 100644
index 0000000..ab527f2
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/MultiLocationTest.java
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static org.testng.Assert.assertTrue;
+
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.collections.MutableSet;
+import org.apache.brooklyn.util.net.Networking;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.cloud.AvailabilityZoneExtension;
+import org.apache.brooklyn.location.core.MultiLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+public class MultiLocationTest {
+
+    private static final Logger log = LoggerFactory.getLogger(MultiLocationTest.class);
+    
+    private LocalManagementContext managementContext;
+    private SshMachineLocation mac1a;
+    private SshMachineLocation mac1b;
+    private SshMachineLocation mac2a;
+    private SshMachineLocation mac2b;
+    private FixedListMachineProvisioningLocation<SshMachineLocation> loc1;
+    private FixedListMachineProvisioningLocation<SshMachineLocation> loc2;
+    private MultiLocation<SshMachineLocation> multiLoc;
+    
+    @SuppressWarnings("unchecked")
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        managementContext = LocalManagementContextForTests.newInstance();
+        mac1a = managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .displayName("mac1a")
+                .configure("address", Networking.getInetAddressWithFixedName("1.1.1.1")));
+        mac1b = managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .displayName("mac1b")
+                .configure("address", Networking.getInetAddressWithFixedName("1.1.1.2")));
+        mac2a = managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .displayName("mac2a")
+                .configure("address", Networking.getInetAddressWithFixedName("1.1.1.3")));
+        mac2b = managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .displayName("mac2b")
+                .configure("address", Networking.getInetAddressWithFixedName("1.1.1.4")));
+        loc1 = managementContext.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
+                .displayName("loc1")
+                .configure("machines", MutableSet.of(mac1a, mac1b)));
+        loc2 = managementContext.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
+                .displayName("loc2")
+                .configure("machines", MutableSet.of(mac2a, mac2b)));
+        multiLoc = managementContext.getLocationManager().createLocation(LocationSpec.create(MultiLocation.class)
+                        .displayName("multiLoc")
+                        .configure("subLocations", ImmutableList.of(loc1, loc2)));
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (managementContext != null) Entities.destroyAll(managementContext);
+    }
+    
+    @Test
+    public void testHasAvailabilityZonesAsSubLocations() throws Exception {
+        multiLoc.hasExtension(AvailabilityZoneExtension.class);
+        AvailabilityZoneExtension extension = multiLoc.getExtension(AvailabilityZoneExtension.class);
+        Asserts.assertEqualsIgnoringOrder(extension.getAllSubLocations(), ImmutableList.of(loc1, loc2));
+        Asserts.assertEqualsIgnoringOrder(extension.getSubLocations(2), ImmutableList.of(loc1, loc2));
+        assertTrue(ImmutableList.of(loc1, loc2).containsAll(extension.getSubLocations(1)));
+    }
+    
+    @Test
+    public void testObtainAndReleaseDelegateToSubLocation() throws Exception {
+        SshMachineLocation obtained = multiLoc.obtain(ImmutableMap.of());
+        assertTrue(ImmutableList.of(mac1a, mac1b, mac2a, mac2b).contains(obtained));
+        multiLoc.release(obtained);
+    }
+    
+    @Test
+    public void testObtainsMovesThroughSubLocations() throws Exception {
+        Assert.assertEquals(multiLoc.obtain().getAddress().getHostAddress(), "1.1.1.1");
+        Assert.assertEquals(multiLoc.obtain().getAddress().getHostAddress(), "1.1.1.2");
+        Assert.assertEquals(multiLoc.obtain().getAddress().getHostAddress(), "1.1.1.3");
+        Assert.assertEquals(multiLoc.obtain().getAddress().getHostAddress(), "1.1.1.4");
+        try {
+            multiLoc.obtain();
+            Assert.fail();
+        } catch (NoMachinesAvailableException e) {
+            log.info("Error when no machines available across locations is: "+e);
+            Assert.assertTrue(e.toString().contains("loc1"), "Message should have referred to sub-location message: "+e);
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/PaasLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/PaasLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/core/PaasLocationTest.java
new file mode 100644
index 0000000..a58c0a1
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/PaasLocationTest.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import org.apache.brooklyn.core.test.location.TestPaasLocation;
+import org.apache.brooklyn.location.paas.PaasLocation;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+public class PaasLocationTest {
+
+    private PaasLocation location;
+    
+    @Test
+    public void testProviderName(){
+        location = new TestPaasLocation();
+        Assert.assertEquals(location.getPaasProviderName(), "TestPaas");
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/PortRangesTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/PortRangesTest.java b/core/src/test/java/org/apache/brooklyn/location/core/PortRangesTest.java
new file mode 100644
index 0000000..e4d7036
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/PortRangesTest.java
@@ -0,0 +1,130 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static org.testng.Assert.assertEquals;
+
+import java.util.Iterator;
+
+import org.testng.Assert;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.api.location.PortRange;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.util.core.flags.TypeCoercions;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+public class PortRangesTest {
+
+    @Test
+    public void testSingleRange() {
+        PortRange r = PortRanges.fromInteger(1234);
+        assertContents(r, 1234);
+    }
+
+    @Test
+    public void testFromCollection() {
+        PortRange r = PortRanges.fromCollection(ImmutableList.of(1234, 2345));
+        assertContents(r, 1234, 2345);
+    }
+
+    @Test
+    public void testFromString() {
+        PortRange r = PortRanges.fromString("80,8080,8000,8080-8099");
+        assertContents(r, 80, 8080, 8000, 
+                8080, 8081, 8082, 8083, 8084, 8085, 8086, 8087, 8088, 8089,
+                8090, 8091, 8092, 8093, 8094, 8095, 8096, 8097, 8098, 8099);
+    }
+
+    @Test
+    public void testFromStringWithSpaces() {
+        PortRange r = PortRanges.fromString(" 80 , 8080  , 8000 , 8080  - 8099 ");
+        assertContents(r, 80, 8080, 8000, 
+                8080, 8081, 8082, 8083, 8084, 8085, 8086, 8087, 8088, 8089,
+                8090, 8091, 8092, 8093, 8094, 8095, 8096, 8097, 8098, 8099);
+    }
+
+    @Test
+    public void testFromStringWithSpacesToString() {
+        PortRange r = PortRanges.fromString(" 80 , 8080  , 8000 , 8080  - 8099 ");
+        Assert.assertEquals(r.toString(), "80,8080,8000,8080-8099");
+    }
+    
+    @Test
+    public void testFromStringThrowsIllegalArgumentException() {
+        assertFromStringThrowsIllegalArgumentException("80-100000");
+        assertFromStringThrowsIllegalArgumentException("0-80");
+    }
+
+    @Test
+    public void testCoercion() {
+        PortRanges.init();
+        PortRange r = TypeCoercions.coerce("80", PortRange.class);
+        assertContents(r, 80);
+    }
+
+    @Test
+    public void testCoercionInt() {
+        PortRanges.init();
+        PortRange r = TypeCoercions.coerce(80, PortRange.class);
+        assertContents(r, 80);
+    }
+    
+    @Test
+    public void testLinearRangeOfSizeOne() throws Exception {
+        PortRanges.LinearPortRange range = new PortRanges.LinearPortRange(80, 80);
+        assertEquals(Lists.newArrayList(range), ImmutableList.of(80));
+    }
+
+    @Test
+    public void testLinearRangeCountingUpwards() throws Exception {
+        PortRanges.LinearPortRange range = new PortRanges.LinearPortRange(80, 81);
+        assertEquals(Lists.newArrayList(range), ImmutableList.of(80, 81));
+    }
+    
+    @Test
+    public void testLinearRangeCountingDownwards() throws Exception {
+        PortRanges.LinearPortRange range = new PortRanges.LinearPortRange(80, 79);
+        assertEquals(Lists.newArrayList(range), ImmutableList.of(80, 79));
+    }
+    
+    protected void assertFromStringThrowsIllegalArgumentException(String range) {
+        try {
+            PortRanges.fromString(range);
+            Assert.fail();
+        } catch (IllegalArgumentException e) {
+            // success
+        }
+    }
+
+    private static <T> void assertContents(Iterable<T> actual, T ...expected) {
+        Iterator<T> i = actual.iterator();
+        int c = 0;
+        while (i.hasNext()) {
+            if (expected.length<=c) {
+                Assert.fail("Iterable contained more than the "+c+" expected elements");
+            }
+            Assert.assertEquals(i.next(), expected[c++]);
+        }
+        if (expected.length>c) {
+            Assert.fail("Iterable contained only "+c+" elements, "+expected.length+" expected");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/RecordingMachineLocationCustomizer.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/RecordingMachineLocationCustomizer.java b/core/src/test/java/org/apache/brooklyn/location/core/RecordingMachineLocationCustomizer.java
new file mode 100644
index 0000000..efaa94f
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/RecordingMachineLocationCustomizer.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.util.List;
+
+import com.google.common.base.Objects;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.MachineLocationCustomizer;
+
+public class RecordingMachineLocationCustomizer implements MachineLocationCustomizer {
+    public static class Call {
+        public final String methodName;
+        public final List<?> args;
+        
+        public Call(String methodName, List<?> args) {
+            this.methodName = checkNotNull(methodName);
+            this.args = checkNotNull(args);
+        }
+        
+        @Override
+        public String toString() {
+            return methodName+args;
+        }
+        
+        @Override
+        public int hashCode() {
+            return Objects.hashCode(methodName, args);
+        }
+        
+        @Override
+        public boolean equals(Object other) {
+            return (other instanceof RecordingMachineLocationCustomizer.Call) && 
+                    methodName.equals(((RecordingMachineLocationCustomizer.Call)other).methodName) && 
+                    args.equals(((RecordingMachineLocationCustomizer.Call)other).args);
+        }
+    }
+    
+    public final List<RecordingMachineLocationCustomizer.Call> calls = Lists.newCopyOnWriteArrayList();
+    
+    @Override
+    public void customize(MachineLocation machine) {
+        calls.add(new Call("customize", ImmutableList.of(machine)));
+    }
+
+    @Override
+    public void preRelease(MachineLocation machine) {
+        calls.add(new Call("preRelease", ImmutableList.of(machine)));
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/SimulatedLocation.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/SimulatedLocation.java b/core/src/test/java/org/apache/brooklyn/location/core/SimulatedLocation.java
new file mode 100644
index 0000000..e9f572c
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/SimulatedLocation.java
@@ -0,0 +1,141 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import java.net.InetAddress;
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.brooklyn.api.location.HardwareDetails;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineDetails;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.location.OsDetails;
+import org.apache.brooklyn.api.location.PortRange;
+import org.apache.brooklyn.api.location.PortSupplier;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.location.core.BasicHardwareDetails;
+import org.apache.brooklyn.location.core.BasicMachineDetails;
+import org.apache.brooklyn.location.core.BasicOsDetails;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.net.Networking;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Sets;
+
+
+/** Location for use in dev/test, defining custom start/stop support, and/or tweaking the ports which are permitted to be available
+ * (using setPermittedPorts(Iterable))
+ */
+public class SimulatedLocation extends AbstractLocation implements MachineProvisioningLocation<MachineLocation>, MachineLocation, PortSupplier {
+
+    private static final long serialVersionUID = 1L;
+    
+    private static final InetAddress address;
+    static {
+        address = Networking.getLocalHost();
+    }
+
+    Iterable<Integer> permittedPorts = PortRanges.fromString("1+");
+    Set<Integer> usedPorts = Sets.newLinkedHashSet();
+
+    public SimulatedLocation() {
+        this(MutableMap.<String,Object>of());
+    }
+    public SimulatedLocation(Map<String,? extends Object> flags) {
+        super(flags);
+    }
+    
+    @Override
+    public SimulatedLocation newSubLocation(Map<?,?> newFlags) {
+        // TODO shouldn't have to copy config bag as it should be inherited (but currently it is not used inherited everywhere; just most places)
+        return getManagementContext().getLocationManager().createLocation(LocationSpec.create(getClass())
+                .parent(this)
+                .configure(config().getLocalBag().getAllConfig())  // FIXME Should this just be inherited?
+                .configure(newFlags));
+    }
+
+    public MachineLocation obtain(Map<?,?> flags) {
+        return this;
+    }
+
+    public void release(MachineLocation machine) {
+    }
+
+    public Map<String,Object> getProvisioningFlags(Collection<String> tags) {
+        return MutableMap.<String,Object>of();
+    }
+    
+    public InetAddress getAddress() {
+        return address;
+    }
+
+    @Override
+    public String getHostname() {
+        String hostname = address.getHostName();
+        return (hostname == null || hostname.equals(address.getHostAddress())) ? null : hostname;
+    }
+    
+    @Override
+    public Set<String> getPublicAddresses() {
+        return ImmutableSet.of(address.getHostAddress());
+    }
+    
+    @Override
+    public Set<String> getPrivateAddresses() {
+        return ImmutableSet.of();
+    }
+
+    public synchronized boolean obtainSpecificPort(int portNumber) {
+        if (!Iterables.contains(permittedPorts, portNumber)) return false;
+        if (usedPorts.contains(portNumber)) return false;
+        usedPorts.add(portNumber);
+        return true;
+    }
+
+    public synchronized int obtainPort(PortRange range) {
+        for (int p: range)
+            if (obtainSpecificPort(p)) return p;
+        return -1;
+    }
+
+    public synchronized void releasePort(int portNumber) {
+        usedPorts.remove(portNumber);
+    }
+    
+    public synchronized void setPermittedPorts(Iterable<Integer> ports) {
+        permittedPorts  = ports;
+    }
+
+    @Override
+    public OsDetails getOsDetails() {
+        return getMachineDetails().getOsDetails();
+    }
+
+    @Override
+    public MachineDetails getMachineDetails() {
+        HardwareDetails hardwareDetails = new BasicHardwareDetails(null, null);
+        OsDetails osDetails = BasicOsDetails.Factory.ANONYMOUS_LINUX;
+        return new BasicMachineDetails(hardwareDetails, osDetails);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/TestPortSupplierLocation.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/TestPortSupplierLocation.java b/core/src/test/java/org/apache/brooklyn/location/core/TestPortSupplierLocation.java
new file mode 100644
index 0000000..df37585
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/TestPortSupplierLocation.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static org.testng.Assert.assertEquals;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
+import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+
+public class TestPortSupplierLocation extends BrooklynAppUnitTestSupport {
+
+    SimulatedLocation loc;
+    PortAttributeSensorAndConfigKey ps;
+    TestEntity entity;
+    
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        loc = app.newSimulatedLocation();
+        entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
+        app.start(ImmutableList.of(loc));
+        
+        ps = new PortAttributeSensorAndConfigKey("some.port", "for testing", "1234+");
+    }
+
+    @Test
+    public void testObtainsPort() throws Exception {
+        ConfigToAttributes.apply(entity, ps);
+        
+        int p = entity.getAttribute(ps);
+        assertEquals(p, 1234);
+        
+        //sensor access should keep the same value
+        p = entity.getAttribute(ps);
+        assertEquals(p, 1234);
+    }
+    
+    @Test
+    public void testRepeatedConvertAccessIncrements() throws Exception {
+        int p = ps.getAsSensorValue(entity);
+        assertEquals(p, 1234);
+
+        //but direct access should see it as being reserved (not required behaviour, but it is the current behaviour)
+        int p2 = ps.getAsSensorValue(entity);
+        assertEquals(p2, 1235);
+    }
+
+    @Test
+    public void testNullBeforeSetting() throws Exception {
+        // currently getting the attribute before explicitly setting return null; i.e. no "auto-set" -- 
+        // but this behaviour may be changed
+        Integer p = entity.getAttribute(ps);
+        assertEquals(p, null);
+    }
+
+    @Test
+    public void testSimulatedRestrictedPermitted() throws Exception {
+        loc.setPermittedPorts(PortRanges.fromString("1240+"));
+        
+        ConfigToAttributes.apply(entity, ps);
+        int p = entity.getAttribute(ps);
+        assertEquals((int)p, 1240);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/localhost/LocalhostLocationResolverTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/localhost/LocalhostLocationResolverTest.java b/core/src/test/java/org/apache/brooklyn/location/core/localhost/LocalhostLocationResolverTest.java
new file mode 100644
index 0000000..bb781a4
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/localhost/LocalhostLocationResolverTest.java
@@ -0,0 +1,269 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core.localhost;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.core.BasicLocationRegistry;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.util.text.StringEscapes.JavaStringEscapes;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+
+public class LocalhostLocationResolverTest {
+
+    private BrooklynProperties brooklynProperties;
+    private LocalManagementContext managementContext;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        managementContext = LocalManagementContextForTests.newInstance();
+        brooklynProperties = managementContext.getBrooklynProperties();
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (managementContext != null) Entities.destroyAll(managementContext);
+    }
+    
+    @Test
+    public void testTakesLocalhostScopedProperties() {
+        brooklynProperties.put("brooklyn.location.localhost.privateKeyFile", "myprivatekeyfile");
+        brooklynProperties.put("brooklyn.location.localhost.publicKeyFile", "mypublickeyfile");
+        brooklynProperties.put("brooklyn.location.localhost.privateKeyData", "myprivateKeyData");
+        brooklynProperties.put("brooklyn.location.localhost.publicKeyData", "myPublicKeyData");
+        brooklynProperties.put("brooklyn.location.localhost.privateKeyPassphrase", "myprivateKeyPassphrase");
+
+        Map<String, Object> conf = resolve("localhost").config().getBag().getAllConfig();
+        
+        assertEquals(conf.get("privateKeyFile"), "myprivatekeyfile");
+        assertEquals(conf.get("publicKeyFile"), "mypublickeyfile");
+        assertEquals(conf.get("privateKeyData"), "myprivateKeyData");
+        assertEquals(conf.get("publicKeyData"), "myPublicKeyData");
+        assertEquals(conf.get("privateKeyPassphrase"), "myprivateKeyPassphrase");
+    }
+
+    @Test
+    public void testTakesLocalhostDeprecatedScopedProperties() {
+        brooklynProperties.put("brooklyn.localhost.privateKeyFile", "myprivatekeyfile");
+        brooklynProperties.put("brooklyn.localhost.publicKeyFile", "mypublickeyfile");
+        brooklynProperties.put("brooklyn.localhost.privateKeyData", "myprivateKeyData");
+        brooklynProperties.put("brooklyn.localhost.publicKeyData", "myPublicKeyData");
+        brooklynProperties.put("brooklyn.localhost.privateKeyPassphrase", "myprivateKeyPassphrase");
+
+        Map<String, Object> conf = resolve("localhost").config().getBag().getAllConfig();
+        
+        assertEquals(conf.get("privateKeyFile"), "myprivatekeyfile");
+        assertEquals(conf.get("publicKeyFile"), "mypublickeyfile");
+        assertEquals(conf.get("privateKeyData"), "myprivateKeyData");
+        assertEquals(conf.get("publicKeyData"), "myPublicKeyData");
+        assertEquals(conf.get("privateKeyPassphrase"), "myprivateKeyPassphrase");
+    }
+
+    @Test
+    public void testTakesDeprecatedProperties() {
+        brooklynProperties.put("brooklyn.localhost.private-key-file", "myprivatekeyfile");
+        brooklynProperties.put("brooklyn.localhost.public-key-file", "mypublickeyfile");
+        brooklynProperties.put("brooklyn.localhost.private-key-data", "myprivateKeyData");
+        brooklynProperties.put("brooklyn.localhost.public-key-data", "myPublicKeyData");
+        brooklynProperties.put("brooklyn.localhost.private-key-passphrase", "myprivateKeyPassphrase");
+        Map<String, Object> conf = resolve("localhost").config().getBag().getAllConfig();
+        
+        assertEquals(conf.get("privateKeyFile"), "myprivatekeyfile");
+        assertEquals(conf.get("publicKeyFile"), "mypublickeyfile");
+        assertEquals(conf.get("privateKeyData"), "myprivateKeyData");
+        assertEquals(conf.get("publicKeyData"), "myPublicKeyData");
+        assertEquals(conf.get("privateKeyPassphrase"), "myprivateKeyPassphrase");
+    }
+    
+    @Test
+    public void testPropertyScopePrescedence() {
+        brooklynProperties.put("brooklyn.location.named.mynamed", "localhost");
+        
+        // prefer those in "named" over everything else
+        brooklynProperties.put("brooklyn.location.named.mynamed.privateKeyFile", "privateKeyFile-inNamed");
+        brooklynProperties.put("brooklyn.location.localhost.privateKeyFile", "privateKeyFile-inProviderSpecific");
+        brooklynProperties.put("brooklyn.localhost.privateKeyFile", "privateKeyFile-inGeneric");
+
+        // prefer those in provider-specific over generic
+        brooklynProperties.put("brooklyn.location.localhost.publicKeyFile", "publicKeyFile-inProviderSpecific");
+        brooklynProperties.put("brooklyn.location.publicKeyFile", "publicKeyFile-inGeneric");
+
+        // prefer location-generic if nothing else
+        brooklynProperties.put("brooklyn.location.privateKeyData", "privateKeyData-inGeneric");
+
+        Map<String, Object> conf = resolve("named:mynamed").config().getBag().getAllConfig();
+        
+        assertEquals(conf.get("privateKeyFile"), "privateKeyFile-inNamed");
+        assertEquals(conf.get("publicKeyFile"), "publicKeyFile-inProviderSpecific");
+        assertEquals(conf.get("privateKeyData"), "privateKeyData-inGeneric");
+    }
+
+    @Test
+    public void testLocalhostLoads() {
+        Assert.assertTrue(resolve("localhost") instanceof LocalhostMachineProvisioningLocation);
+    }
+
+    @Test
+    public void testThrowsOnInvalid() throws Exception {
+        assertThrowsNoSuchElement("wrongprefix");
+        assertThrowsIllegalArgument("localhost(name=abc"); // no closing bracket
+        assertThrowsIllegalArgument("localhost(name)"); // no value for name
+        assertThrowsIllegalArgument("localhost(name=)"); // no value for name
+    }
+    
+
+    @Test
+    public void testAcceptsList() {
+        List<Location> l = getLocationResolver().resolve(ImmutableList.of("localhost"));
+        assertEquals(l.size(), 1, "l="+l);
+        assertTrue(l.get(0) instanceof LocalhostMachineProvisioningLocation, "l="+l);
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testRegistryCommaResolution() throws NoMachinesAvailableException {
+        List<Location> l;
+        l = getLocationResolver().resolve(JavaStringEscapes.unwrapJsonishListIfPossible("localhost,localhost,localhost"));
+        assertEquals(l.size(), 3, "l="+l);
+        assertTrue(l.get(0) instanceof LocalhostMachineProvisioningLocation, "l="+l);
+        assertTrue(l.get(1) instanceof LocalhostMachineProvisioningLocation, "l="+l);
+        assertTrue(l.get(2) instanceof LocalhostMachineProvisioningLocation, "l="+l);
+
+        // And check works if comma in brackets
+        l = getLocationResolver().resolve(JavaStringEscapes.unwrapJsonishListIfPossible(
+            "[ \"byon:(hosts=\\\"192.168.0.1\\\",user=bob)\", \"byon:(hosts=\\\"192.168.0.2\\\",user=bob2)\" ]"));
+        assertEquals(l.size(), 2, "l="+l);
+        assertTrue(l.get(0) instanceof FixedListMachineProvisioningLocation, "l="+l);
+        assertTrue(l.get(1) instanceof FixedListMachineProvisioningLocation, "l="+l);
+        assertEquals(((FixedListMachineProvisioningLocation<SshMachineLocation>)l.get(0)).obtain().getUser(), "bob");
+        assertEquals(((FixedListMachineProvisioningLocation<SshMachineLocation>)l.get(1)).obtain().getUser(), "bob2");
+    }
+
+    @Test(expectedExceptions={NoSuchElementException.class})
+    public void testRegistryCommaResolutionInListNotAllowed1() throws NoMachinesAvailableException {
+        // disallowed since 0.7.0
+        getLocationResolver().resolve(ImmutableList.of("localhost,localhost,localhost"));
+    }
+
+    @Test(expectedExceptions={IllegalArgumentException.class})
+    public void testRegistryCommaResolutionInListNotAllowed2() throws NoMachinesAvailableException {
+        // disallowed since 0.7.0
+        // fails because it interprets the entire string as a single spec, which does not parse
+        getLocationResolver().resolve(ImmutableList.of("localhost(),localhost()"));
+    }
+
+    @Test(expectedExceptions={IllegalArgumentException.class})
+    public void testRegistryCommaResolutionInListNotAllowed3() throws NoMachinesAvailableException {
+        // disallowed since 0.7.0
+        // fails because it interprets the entire string as a single spec, which does not parse
+        getLocationResolver().resolve(ImmutableList.of("localhost(name=a),localhost(name=b)"));
+    }
+
+    @Test(expectedExceptions={IllegalArgumentException.class})
+    public void testDoesNotAcceptsListOLists() {
+        ((BasicLocationRegistry)managementContext.getLocationRegistry()).resolve(ImmutableList.of(ImmutableList.of("localhost")));
+    }
+
+    @Test
+    public void testResolvesExplicitName() throws Exception {
+        Location location = resolve("localhost(name=myname)");
+        assertTrue(location instanceof LocalhostMachineProvisioningLocation);
+        assertEquals(location.getDisplayName(), "myname");
+    }
+    
+    @Test
+    public void testWithOldStyleColon() throws Exception {
+        Location location = resolve("localhost:(name=myname)");
+        assertTrue(location instanceof LocalhostMachineProvisioningLocation);
+        assertEquals(location.getDisplayName(), "myname");
+    }
+    
+    @Test
+    public void testResolvesPropertiesInSpec() throws Exception {
+        LocationInternal location = resolve("localhost(privateKeyFile=myprivatekeyfile,name=myname)");
+        assertTrue(location instanceof LocalhostMachineProvisioningLocation);
+        assertEquals(location.getDisplayName(), "myname");
+        assertEquals(location.config().getBag().getStringKey("privateKeyFile"), "myprivatekeyfile");
+    }
+    
+    @Test
+    public void testResolvesDefaultName() throws Exception {
+        Location location = resolve("localhost");
+        assertTrue(location instanceof LocalhostMachineProvisioningLocation);
+        assertEquals(location.getDisplayName(), "localhost");
+
+        Location location2 = resolve("localhost()");
+        assertTrue(location2 instanceof LocalhostMachineProvisioningLocation);
+        assertEquals(location2.getDisplayName(), "localhost");
+    }
+    
+    private BasicLocationRegistry getLocationResolver() {
+        return (BasicLocationRegistry) managementContext.getLocationRegistry();
+    }
+    
+    private LocationInternal resolve(String val) {
+        Location l = managementContext.getLocationRegistry().resolve(val);
+        Assert.assertNotNull(l);
+        return (LocationInternal) l;
+    }
+    
+    private void assertThrowsNoSuchElement(String val) {
+        try {
+            resolve(val);
+            fail();
+        } catch (NoSuchElementException e) {
+            // success
+        }
+
+        // and check the long form returns an Absent (not throwing)
+        Assert.assertTrue(managementContext.getLocationRegistry().resolve(val, false, null).isAbsent());
+    }
+    
+    private void assertThrowsIllegalArgument(String val) {
+        try {
+            resolve(val);
+            fail();
+        } catch (IllegalArgumentException e) {
+            // success
+        }
+        
+        // and check the long form returns an Absent (not throwing)
+        Assert.assertTrue(managementContext.getLocationRegistry().resolve(val, false, null).isAbsent());
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/localhost/LocalhostMachineProvisioningLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/localhost/LocalhostMachineProvisioningLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/core/localhost/LocalhostMachineProvisioningLocationTest.java
new file mode 100644
index 0000000..4735350
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/localhost/LocalhostMachineProvisioningLocationTest.java
@@ -0,0 +1,215 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core.localhost;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.fail;
+
+import java.net.ServerSocket;
+
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.net.Networking;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.api.location.PortRange;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.location.geo.HostGeoInfo;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+
+public class LocalhostMachineProvisioningLocationTest {
+
+    private static final Logger log = LoggerFactory.getLogger(LocalhostMachineProvisioningLocationTest.class);
+    
+    private LocalManagementContext mgmt;
+
+    @BeforeMethod
+    @AfterClass
+    protected void clearStatics() {
+        LocalhostMachineProvisioningLocation.clearStaticData();
+    }
+    
+    @BeforeClass
+    protected void setup() {
+        mgmt = LocalManagementContextForTests.newInstance();
+    }
+    
+    @AfterClass
+    protected void teardown() {
+        Entities.destroyAll(mgmt);
+    }
+    
+    protected LocalhostMachineProvisioningLocation newLocalhostProvisioner() {
+        return mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class));
+    }
+    
+    protected LocalhostMachineProvisioningLocation newLocalhostProvisionerWithAddress(String address) {
+        return mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class)
+            .configure("address", address));
+    }
+    
+    @Test
+    public void defaultInvocationCanProvisionALocalhostInstance() throws Exception {
+        LocalhostMachineProvisioningLocation provisioner = mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class));
+        SshMachineLocation machine = provisioner.obtain();
+        assertNotNull(machine);
+        assertEquals(machine.getAddress(), Networking.getLocalHost());
+    }
+
+    @Test
+    public void testUsesLocationNameProvided() throws Exception {
+        LocalhostMachineProvisioningLocation provisioner = newLocalhostProvisionerWithAddress("localhost");
+        assertEquals(((SshMachineLocation)provisioner.obtain()).getAddress().getHostName(), "localhost");
+
+        LocalhostMachineProvisioningLocation provisioner2 = newLocalhostProvisionerWithAddress("1.2.3.4");
+        assertEquals(((SshMachineLocation)provisioner2.obtain()).getAddress().getHostName(), "1.2.3.4");
+        
+        LocalhostMachineProvisioningLocation provisioner3 = newLocalhostProvisionerWithAddress("127.0.0.1");
+        assertEquals(((SshMachineLocation)provisioner3.obtain()).getAddress().getHostName(), "127.0.0.1");
+    }
+    
+    public void provisionWithASpecificNumberOfInstances() throws NoMachinesAvailableException {
+        LocalhostMachineProvisioningLocation provisioner = mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class)
+            .configure("count", 2));
+
+        // first machine
+        SshMachineLocation first = provisioner.obtain();
+        assertNotNull(first);
+        assertEquals(first.getAddress(), Networking.getLocalHost());
+
+        // second machine
+        SshMachineLocation second = provisioner.obtain();
+        assertNotNull(second);
+        assertEquals(second.getAddress(), Networking.getLocalHost());
+
+        // third machine - fails
+        try {
+            SshMachineLocation third = provisioner.obtain();
+            fail("did not throw expected exception; got "+third);
+        } catch (NoMachinesAvailableException e) {
+            /* expected */
+        }
+    }
+    
+    @Test
+    public void obtainTwoAddressesInRangeThenDontObtain() throws Exception {
+        LocalhostMachineProvisioningLocation p = newLocalhostProvisioner();
+        SshMachineLocation m = p.obtain();
+
+        // Find two ports that are free, rather than risk false-negatives if a port was left open by something else.
+        int start = 48311;
+        while (true) {
+            if (Networking.isPortAvailable(m.getAddress(), start) && Networking.isPortAvailable(m.getAddress(), start+1)) {
+                break;
+            } else {
+                start++;
+            }
+        }
+        PortRange r = PortRanges.fromString(""+start+"-"+(start+1));
+        
+        try {
+            int i1 = m.obtainPort(r);
+            Assert.assertEquals(i1, start);
+            int i2 = m.obtainPort(r);
+            Assert.assertEquals(i2, start+1);
+            
+            //should fail
+            int i3 = m.obtainPort(r);
+            Assert.assertEquals(i3, -1);
+
+            //releasing and reapplying should succed
+            m.releasePort(i2);
+            int i4 = m.obtainPort(r);
+            Assert.assertEquals(i4, i2);
+
+        } finally {
+            m.releasePort(start);
+            m.releasePort(start+1);
+        }
+    }
+    
+    @Test
+    public void obtainLowNumberedPortsAutomatically() throws Exception {
+        LocalhostMachineProvisioningLocation p = newLocalhostProvisioner();
+        SshMachineLocation m = p.obtain();
+        int start = 983;  //random rarely used port, not that it matters
+        try {
+            int actual = m.obtainPort(PortRanges.fromInteger(start));
+            Assert.assertEquals(actual, start);
+        } finally {
+            m.releasePort(start);
+        }
+
+    }
+
+    @Test
+    public void obtainPortFailsIfInUse() throws Exception {
+        LocalhostMachineProvisioningLocation p = newLocalhostProvisioner();
+        SshMachineLocation m = p.obtain();
+        
+        // Find two ports that are free, rather than risk false-negatives if a port was left open by something else.
+        int start = 48311;
+        while (true) {
+            if (Networking.isPortAvailable(m.getAddress(), start) && Networking.isPortAvailable(m.getAddress(), start+1)) {
+                break;
+            } else {
+                start++;
+            }
+        }
+        PortRange r = PortRanges.fromString(""+start+"-"+(start+1));
+
+        ServerSocket ss = null;
+        try {
+            ss = new ServerSocket(start, 0, m.getAddress());
+            int i1 = m.obtainPort(r);
+            Assert.assertEquals(i1, start+1);
+        } finally {
+            if (ss!=null) ss.close();
+            m.releasePort(start);
+            m.releasePort(start+1);
+        }
+    }
+
+    @Test
+    public void obtainLocationWithGeography() throws Exception {
+        mgmt.getBrooklynProperties().put("brooklyn.location.named.lhx", "localhost");
+        // bogus location so very little chance of it being what maxmind returns!
+        mgmt.getBrooklynProperties().put("brooklyn.location.named.lhx.latitude", 42d);
+        mgmt.getBrooklynProperties().put("brooklyn.location.named.lhx.longitude", -20d);
+        MachineProvisioningLocation<?> p = (MachineProvisioningLocation<?>) mgmt.getLocationRegistry().resolve("named:lhx");
+        SshMachineLocation m = (SshMachineLocation) p.obtain(MutableMap.of());
+        HostGeoInfo geo = HostGeoInfo.fromLocation(m);
+        log.info("Geo info for "+m+" is: "+geo);
+        Assert.assertEquals(geo.latitude, 42d, 0.00001);
+        Assert.assertEquals(geo.longitude, -20d, 0.00001);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/localhost/LocalhostProvisioningAndAccessTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/localhost/LocalhostProvisioningAndAccessTest.java b/core/src/test/java/org/apache/brooklyn/location/core/localhost/LocalhostProvisioningAndAccessTest.java
new file mode 100644
index 0000000..3bb594e
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/localhost/LocalhostProvisioningAndAccessTest.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core.localhost;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.util.Arrays;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class LocalhostProvisioningAndAccessTest {
+
+    private LocalManagementContext mgmt;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        mgmt = new LocalManagementContext(BrooklynProperties.Factory.newDefault());
+    }
+    
+    @AfterMethod(alwaysRun = true)
+    public void tearDown(){
+        if (mgmt != null) Entities.destroyAll(mgmt);
+    }
+
+    @Test(groups="Integration")
+    public void testProvisionAndConnect() throws Exception {
+        Location location = mgmt.getLocationRegistry().resolve("localhost");
+        assertTrue(location instanceof LocalhostMachineProvisioningLocation);
+        SshMachineLocation m = ((LocalhostMachineProvisioningLocation)location).obtain();
+        int result = m.execCommands("test", Arrays.asList("echo hello world"));
+        assertEquals(result, 0);
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/geo/HostGeoInfoTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/geo/HostGeoInfoTest.java b/core/src/test/java/org/apache/brooklyn/location/geo/HostGeoInfoTest.java
index 2ca5807..56c1b41 100644
--- a/core/src/test/java/org/apache/brooklyn/location/geo/HostGeoInfoTest.java
+++ b/core/src/test/java/org/apache/brooklyn/location/geo/HostGeoInfoTest.java
@@ -22,7 +22,7 @@ import static org.testng.AssertJUnit.assertEquals;
 import static org.testng.AssertJUnit.assertNotNull;
 
 import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.testng.annotations.Test;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/geo/HostGeoLookupIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/geo/HostGeoLookupIntegrationTest.java b/core/src/test/java/org/apache/brooklyn/location/geo/HostGeoLookupIntegrationTest.java
index c80534f..1990905 100644
--- a/core/src/test/java/org/apache/brooklyn/location/geo/HostGeoLookupIntegrationTest.java
+++ b/core/src/test/java/org/apache/brooklyn/location/geo/HostGeoLookupIntegrationTest.java
@@ -24,8 +24,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.time.Duration;
 
 import com.google.common.base.Objects;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/ssh/SshMachineLocationIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/ssh/SshMachineLocationIntegrationTest.java b/core/src/test/java/org/apache/brooklyn/location/ssh/SshMachineLocationIntegrationTest.java
new file mode 100644
index 0000000..cd9f724
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/ssh/SshMachineLocationIntegrationTest.java
@@ -0,0 +1,141 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.ssh;
+
+import java.io.ByteArrayOutputStream;
+import java.security.KeyPair;
+import java.util.Arrays;
+import java.util.Map;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.crypto.SecureKeys;
+import org.apache.brooklyn.util.core.internal.ssh.SshTool;
+import org.apache.brooklyn.util.core.internal.ssh.sshj.SshjTool;
+import org.apache.brooklyn.util.core.internal.ssh.sshj.SshjTool.SshjToolBuilder;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Preconditions;
+
+import static org.testng.Assert.assertEquals;
+
+public class SshMachineLocationIntegrationTest {
+
+    protected TestApplication app;
+    protected ManagementContext mgmt;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setup() throws Exception {
+        mgmt = LocalManagementContextForTests.builder(true)
+            .useDefaultProperties()
+            .build();
+        app = TestApplication.Factory.newManagedInstanceForTests(mgmt);
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (mgmt != null) Entities.destroyAll(mgmt);
+        mgmt = null;
+    }
+
+    // Note: requires `named:localhost-passphrase` set up with a key whose passphrase is "localhost"
+    // * create the key with:
+    //      ssh-keygen -t rsa -N "brooklyn" -f ~/.ssh/id_rsa_passphrase
+    //      ssh-copy-id localhost
+    // * create brooklyn.properties, containing:
+    //      brooklyn.location.named.localhost-passphrase=localhost
+    //      brooklyn.location.named.localhost-passphrase.privateKeyFile=~/.ssh/id_rsa_passphrase
+    //      brooklyn.location.named.localhost-passphrase.privateKeyPassphrase=brooklyn
+    @Test(groups = "Integration")
+    public void testExtractingConnectablePassphraselessKey() throws Exception {
+        LocalhostMachineProvisioningLocation lhp = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("named:localhost-passphrase", true, null).orNull();
+        Preconditions.checkNotNull(lhp, "This test requires a localhost named location called 'localhost-passphrase' (which should have a passphrase set)");
+        SshMachineLocation sm = lhp.obtain();
+        
+        SshjToolBuilder builder = SshjTool.builder().host(sm.getAddress().getHostName()).user(sm.getUser());
+        
+        KeyPair data = sm.findKeyPair();
+        if (data!=null) builder.privateKeyData(SecureKeys.toPem(data));
+        String password = sm.findPassword();
+        if (password!=null) builder.password(password);
+        SshjTool tool = builder.build();
+        tool.connect();
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        int result = tool.execCommands(MutableMap.<String,Object>of("out", out), Arrays.asList("date"));
+        Assert.assertTrue(out.toString().contains(" 20"), "out="+out);
+        assertEquals(result, 0);
+    }
+
+    @Test(groups = "Integration")
+    public void testExecScriptScriptDirFlagIsRespected() throws Exception {
+        // For explanation of (some of) the magic behind this command, see http://stackoverflow.com/a/229606/68898
+        final String command = "if [[ \"$0\" == \"/var/tmp/\"* ]]; then true; else false; fi";
+
+        LocalhostMachineProvisioningLocation lhp = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost", true, null).orNull();
+        SshMachineLocation sm = lhp.obtain();
+
+        Map<String, Object> props = ImmutableMap.<String, Object>builder()
+                .put(SshTool.PROP_SCRIPT_DIR.getName(), "/var/tmp")
+                .build();
+        int rc = sm.execScript(props, "Test script directory execution", ImmutableList.of(command));
+        assertEquals(rc, 0);
+    }
+
+    @Test(groups = "Integration")
+    public void testLocationScriptDirConfigIsRespected() throws Exception {
+        // For explanation of (some of) the magic behind this command, see http://stackoverflow.com/a/229606/68898
+        final String command = "if [[ \"$0\" == \"/var/tmp/\"* ]]; then true; else false; fi";
+
+        Map<String, Object> locationConfig = ImmutableMap.<String, Object>builder()
+                .put(SshMachineLocation.SCRIPT_DIR.getName(), "/var/tmp")
+                .build();
+
+        LocalhostMachineProvisioningLocation lhp = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost", locationConfig);
+        SshMachineLocation sm = lhp.obtain();
+
+        int rc = sm.execScript("Test script directory execution", ImmutableList.of(command));
+        assertEquals(rc, 0);
+    }
+    
+    @Test(groups = "Integration")
+    public void testMissingLocationScriptDirIsAlsoOkay() throws Exception {
+        final String command = "echo hello";
+
+        Map<String, Object> locationConfig = ImmutableMap.<String, Object>builder()
+//                .put(SshMachineLocation.SCRIPT_DIR.getName(), "/var/tmp")
+                .build();
+
+        LocalhostMachineProvisioningLocation lhp = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost", locationConfig);
+        SshMachineLocation sm = lhp.obtain();
+
+        int rc = sm.execScript("Test script directory execution", ImmutableList.of(command));
+        assertEquals(rc, 0);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/ssh/SshMachineLocationPerformanceTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/ssh/SshMachineLocationPerformanceTest.java b/core/src/test/java/org/apache/brooklyn/location/ssh/SshMachineLocationPerformanceTest.java
new file mode 100644
index 0000000..27ca938
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/ssh/SshMachineLocationPerformanceTest.java
@@ -0,0 +1,172 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.ssh;
+
+import java.io.ByteArrayOutputStream;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.test.PerformanceTestUtils;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.internal.ssh.SshTool;
+import org.apache.brooklyn.util.net.Networking;
+import org.apache.brooklyn.util.stream.Streams;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.apache.brooklyn.util.time.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Stopwatch;
+import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+
+/**
+ * Test the performance of different variants of invoking the sshj tool.
+ * 
+ * Intended for human-invocation and inspection, to see which parts are most expensive.
+ */
+public class SshMachineLocationPerformanceTest {
+
+    private static final Logger LOG = LoggerFactory.getLogger(SshMachineLocationPerformanceTest.class);
+    
+    private SshMachineLocation machine;
+    private ListeningExecutorService executor;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        machine = new SshMachineLocation(MutableMap.of("address", "localhost"));
+        executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void afterMethod() throws Exception {
+        if (executor != null) executor.shutdownNow();
+        Streams.closeQuietly(machine);
+    }
+
+    @Test(groups = {"Integration"})
+    public void testConsecutiveSmallCommands() throws Exception {
+        runExecManyCommands(ImmutableList.of("true"), "small-cmd", 10);
+    }
+
+    // Mimics SshSensorAdapter's polling
+    @Test(groups = {"Integration"})
+    public void testConsecutiveSmallCommandsWithCustomStdoutAndErr() throws Exception {
+        final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
+        final ByteArrayOutputStream stderr = new ByteArrayOutputStream();
+        
+        Runnable task = new Runnable() {
+            @Override public void run() {
+                machine.execScript(ImmutableMap.of("out", stdout, "err", stderr), "test", ImmutableList.of("true"));
+            }};
+        runMany(task, "small-cmd-custom-stdout", 1, 10);
+    }
+
+    @Test(groups = {"Integration"})
+    public void testConcurrentSmallCommands() throws Exception {
+        runExecManyCommands(ImmutableList.of("true"), "small-cmd", 10, 10);
+    }
+
+    @Test(groups = {"Integration"})
+    public void testConsecutiveBigStdoutCommands() throws Exception {
+        runExecManyCommands(ImmutableList.of("head -c 100000 /dev/urandom"), "big-stdout", 10);
+    }
+
+    @Test(groups = {"Integration"})
+    public void testConsecutiveBigStdinCommands() throws Exception {
+        String bigstr = Identifiers.makeRandomId(100000);
+        runExecManyCommands(ImmutableList.of("echo "+bigstr+" | wc -c"), "big-stdin", 10);
+    }
+
+    @Test(groups = {"Integration"})
+    public void testConsecutiveSmallCommandsWithDifferentProperties() throws Exception {
+        final Map<String, ?> emptyProperties = Collections.emptyMap();
+        final Map<String, ?> customProperties = MutableMap.of(
+                "address", Networking.getLocalHost(),
+                SshTool.PROP_SESSION_TIMEOUT.getName(), 20000,
+                SshTool.PROP_CONNECT_TIMEOUT.getName(), 50000,
+                SshTool.PROP_SCRIPT_HEADER.getName(), "#!/bin/bash");
+
+        Runnable task = new Runnable() {
+            @Override public void run() {
+                if (Math.random() < 0.5) {
+                    machine.execScript(emptyProperties, "test", ImmutableList.of("true"));
+                } else {
+                    machine.execScript(customProperties, "test", ImmutableList.of("true"));
+                }
+            }};
+        runMany(task, "small-cmd-custom-ssh-properties", 1, 10);
+    }
+
+    private void runExecManyCommands(final List<String> cmds, String context, int iterations) throws Exception {
+        runExecManyCommands(cmds, context, 1, iterations);
+    }
+    
+    private void runExecManyCommands(final List<String> cmds, String context, int concurrentRuns, int iterations) throws Exception {
+        Runnable task = new Runnable() {
+                @Override public void run() {
+                    execScript(cmds);
+                }};
+        runMany(task, context, concurrentRuns, iterations);
+    }
+    
+    private void runMany(final Runnable task, final String context, int concurrentRuns, int iterations) throws Exception {
+        long preCpuTime = PerformanceTestUtils.getProcessCpuTime();
+        Stopwatch stopwatch = Stopwatch.createStarted();
+
+        for (int i = 0; i < iterations; i++) {
+            List<ListenableFuture<?>> futures = Lists.newArrayList();
+            for (int j = 0; j < concurrentRuns; j++) {
+                futures.add(executor.submit(new Runnable() {
+                    public void run() {
+                        try {
+                            task.run();
+                        } catch (Exception e) {
+                            LOG.error("Error for "+context+", executing "+task, e);
+                            throw Throwables.propagate(e);
+                        }
+                    }}));
+            }
+            Futures.allAsList(futures).get();
+            
+            long postCpuTime = PerformanceTestUtils.getProcessCpuTime();
+            long elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
+            double fractionCpu = (elapsedTime > 0) ? ((double)postCpuTime-preCpuTime) / TimeUnit.MILLISECONDS.toNanos(elapsedTime) : -1;
+            LOG.info("Executing {}; completed {}; took {}; fraction cpu {}",
+                    new Object[] {context, (i+1), Time.makeTimeStringRounded(elapsedTime), fractionCpu});
+        }
+    }
+
+    private int execScript(List<String> cmds) {
+        return machine.execScript("mysummary", cmds);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/ssh/SshMachineLocationReuseIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/ssh/SshMachineLocationReuseIntegrationTest.java b/core/src/test/java/org/apache/brooklyn/location/ssh/SshMachineLocationReuseIntegrationTest.java
new file mode 100644
index 0000000..e129dc1
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/ssh/SshMachineLocationReuseIntegrationTest.java
@@ -0,0 +1,172 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.ssh;
+
+import static org.testng.Assert.assertEquals;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.internal.ssh.SshTool;
+import org.apache.brooklyn.util.core.internal.ssh.sshj.SshjTool;
+import org.apache.brooklyn.util.net.Networking;
+import org.apache.brooklyn.util.stream.Streams;
+import org.apache.brooklyn.util.time.Duration;
+
+import com.google.common.collect.ImmutableList;
+
+/**
+ * Tests the re-use of SshTools in SshMachineLocation
+ */
+public class SshMachineLocationReuseIntegrationTest {
+
+    public static class RecordingSshjTool extends SshjTool {
+        public static final AtomicBoolean forbidden = new AtomicBoolean(false); 
+        public static final AtomicInteger connectionCount = new AtomicInteger(0);
+        public static final AtomicInteger disconnectionCount = new AtomicInteger();
+        
+        public RecordingSshjTool(Map<String, ?> map) {
+            super(map);
+        }
+
+        @Override
+        public void connect() {
+            if (forbidden.get()) throw new IllegalStateException("forbidden at this time");
+            connectionCount.incrementAndGet();
+            super.connect();
+        }
+
+        @Override
+        public void disconnect() {
+            disconnectionCount.incrementAndGet();
+            super.disconnect();
+        }
+
+        public static void reset() {
+            forbidden.set(false);
+            connectionCount.set(0);
+            disconnectionCount.set(0);
+        }
+
+        @Override
+        public int execCommands(Map<String, ?> props, List<String> commands, Map<String, ?> env) {
+            if (forbidden.get()) throw new IllegalStateException("forbidden at this time");
+            return super.execCommands(props, commands, env);
+        }
+        
+        @Override
+        public int execScript(Map<String, ?> props, List<String> commands, Map<String, ?> env) {
+            if (forbidden.get()) throw new IllegalStateException("forbidden at this time");
+            return super.execScript(props, commands, env);
+        }
+        
+        @Override
+        public int execShellDirect(Map<String, ?> props, List<String> commands, Map<String, ?> env) {
+            if (forbidden.get()) throw new IllegalStateException("forbidden at this time");
+            return super.execShellDirect(props, commands, env);
+        }
+    }
+
+    private SshMachineLocation host;
+    private LocalManagementContext managementContext;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        managementContext = new LocalManagementContext();
+        host = managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure("address", Networking.getLocalHost())
+                .configure(SshTool.PROP_TOOL_CLASS, RecordingSshjTool.class.getName()));
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (host != null) Streams.closeQuietly(host);
+        if (managementContext != null) Entities.destroyAll(managementContext);
+        RecordingSshjTool.reset();
+    }
+
+    @Test(groups = "Integration")
+    public void testBasicReuse() throws Exception {
+        host.execScript("mysummary", ImmutableList.of("exit"));
+        host.execScript("mysummary", ImmutableList.of("exit"));
+        assertEquals(RecordingSshjTool.connectionCount.get(), 1, "Expected one SSH connection to have been recorded");
+    }
+
+    @Test(groups = "Integration")
+    public void testReuseWithInterestingProps() throws Exception {
+        host.execScript(customSshConfigKeys(), "mysummary", ImmutableList.of("exit"));
+        host.execScript(customSshConfigKeys(), "mysummary", ImmutableList.of("exit"));
+        assertEquals(RecordingSshjTool.connectionCount.get(), 1, "Expected one SSH connection to have been recorded");
+    }
+
+    @Test(groups = "Integration")
+    public void testNewConnectionForDifferentProps() throws Exception {
+        host.execScript("mysummary", ImmutableList.of("exit"));
+        host.execScript(customSshConfigKeys(), "mysummary", ImmutableList.of("exit"));
+        assertEquals(RecordingSshjTool.connectionCount.get(), 2, "Expected two SSH connections to have been recorded");
+    }
+
+    @Test(groups = "Integration")
+    public void testSshToolReusedWhenConfigDiffers() throws Exception {
+        Map<String, Object> props = customSshConfigKeys();
+        host.execScript(props, "mysummary", ImmutableList.of("exit"));
+
+        // Use another output stream for second request
+        props.put(SshTool.PROP_SCRIPT_HEADER.getName(), "#!/bin/bash -e\n");
+        host.execScript(props, "mysummary", ImmutableList.of("exit"));
+        assertEquals(RecordingSshjTool.connectionCount.get(), 1, "Expected one SSH connection to have been recorded even though out script header differed.");
+    }
+
+    @Test(groups = "Integration")
+    public void testSshCacheExpiresEvenIfNotUsed() throws Exception {
+        SshMachineLocation host2 = managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure("address", InetAddress.getLocalHost())
+                .configure(SshMachineLocation.SSH_CACHE_EXPIRY_DURATION, Duration.ONE_SECOND)
+                .configure(SshTool.PROP_TOOL_CLASS, RecordingSshjTool.class.getName()));
+        
+        Map<String, Object> props = customSshConfigKeys();
+        host2.execScript(props, "mysummary", ImmutableList.of("exit"));
+
+        Asserts.succeedsEventually(new Runnable() {
+            @Override public void run() {
+                assertEquals(RecordingSshjTool.disconnectionCount.get(), 1);
+            }});
+    }
+
+    public Map<String, Object> customSshConfigKeys() throws UnknownHostException {
+        return MutableMap.<String, Object>of(
+                "address", Networking.getLocalHost(),
+                SshTool.PROP_SESSION_TIMEOUT.getName(), 20000,
+                SshTool.PROP_CONNECT_TIMEOUT.getName(), 50000,
+                SshTool.PROP_SCRIPT_HEADER.getName(), "#!/bin/bash");
+    }
+}


[67/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)


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

Branch: refs/heads/master
Commit: a1ad34d718e37bbab7108956a2f3f9959be68000
Parents: 64c2b2e
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Tue Aug 18 22:38:46 2015 +0100
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Wed Aug 19 00:52:55 2015 +0100

----------------------------------------------------------------------
 .../brooklyn/core/catalog/CatalogLoadMode.java  |    2 +-
 .../catalog/internal/BasicBrooklynCatalog.java  |    2 +-
 .../core/internal/BrooklynInitialization.java   |    2 +-
 .../mgmt/ha/HighAvailabilityManagerImpl.java    |   14 +-
 ...ntPlaneSyncRecordPersisterToObjectStore.java |   18 +-
 .../ha/dto/BasicManagementNodeSyncRecord.java   |  194 ++++
 .../ha/dto/ManagementPlaneSyncRecordImpl.java   |   99 ++
 .../internal/AbstractManagementContext.java     |    2 +-
 .../mgmt/internal/LocalLocationManager.java     |    4 +-
 .../core/mgmt/internal/LocalUsageManager.java   |    6 +-
 .../BrooklynMementoPersisterToObjectStore.java  |  697 ++++++++++++
 .../mgmt/persist/BrooklynPersistenceUtils.java  |  269 +++++
 .../persist/CatalogItemLibrariesConverter.java  |   68 ++
 .../core/mgmt/persist/FileBasedObjectStore.java |  425 +++++++
 .../persist/FileBasedStoreObjectAccessor.java   |  132 +++
 .../mgmt/persist/LocationWithObjectStore.java   |   27 +
 .../core/mgmt/persist/MementoSerializer.java    |   52 +
 .../brooklyn/core/mgmt/persist/PersistMode.java |   26 +
 .../persist/PersistenceActivityMetrics.java     |   83 ++
 .../mgmt/persist/PersistenceObjectStore.java    |  142 +++
 .../mgmt/persist/RetryingMementoSerializer.java |   95 ++
 .../persist/StoreObjectAccessorLocking.java     |  218 ++++
 .../core/mgmt/persist/XmlMementoSerializer.java |  505 +++++++++
 .../rebind/ActivePartialRebindIteration.java    |    4 +-
 .../mgmt/rebind/BasicLocationRebindSupport.java |    2 +-
 .../rebind/ImmediateDeltaChangeListener.java    |    2 +-
 .../mgmt/rebind/InitialFullRebindIteration.java |    2 +-
 .../rebind/PeriodicDeltaChangeListener.java     |    4 +-
 .../core/mgmt/rebind/RebindIteration.java       |    6 +-
 .../core/mgmt/rebind/RebindManagerImpl.java     |    8 +-
 .../mgmt/rebind/dto/MementosGenerators.java     |    4 +-
 .../BrooklynMementoPersisterToObjectStore.java  |  697 ------------
 .../persister/BrooklynPersistenceUtils.java     |  269 -----
 .../CatalogItemLibrariesConverter.java          |   68 --
 .../rebind/persister/FileBasedObjectStore.java  |  425 -------
 .../persister/FileBasedStoreObjectAccessor.java |  132 ---
 .../persister/LocationWithObjectStore.java      |   27 -
 .../rebind/persister/MementoSerializer.java     |   52 -
 .../core/mgmt/rebind/persister/PersistMode.java |   26 -
 .../persister/PersistenceActivityMetrics.java   |   83 --
 .../persister/PersistenceObjectStore.java       |  142 ---
 .../persister/RetryingMementoSerializer.java    |   95 --
 .../persister/StoreObjectAccessorLocking.java   |  218 ----
 .../rebind/persister/XmlMementoSerializer.java  |  505 ---------
 .../dto/BasicManagementNodeSyncRecord.java      |  194 ----
 .../dto/ManagementPlaneSyncRecordImpl.java      |   99 --
 .../rebind/transformer/CompoundTransformer.java |    2 +-
 .../objs/proxy/InternalLocationFactory.java     |    4 +-
 .../brooklyn/effector/core/EffectorTasks.java   |    6 +-
 .../brooklyn/entity/core/AbstractEntity.java    |    2 +-
 .../apache/brooklyn/entity/core/Entities.java   |    4 +-
 .../brooklyn/entity/core/EntitySuppliers.java   |    4 +-
 .../drivers/ReflectiveEntityDriverFactory.java  |    4 +-
 .../entity/group/DynamicClusterImpl.java        |    2 +-
 .../brooklyn/entity/stock/BasicStartable.java   |    2 +-
 .../entity/stock/BasicStartableImpl.java        |    2 +-
 .../location/access/BrooklynAccessUtils.java    |    6 +-
 .../location/access/PortForwardManagerImpl.java |    2 +-
 .../PortForwardManagerLocationResolver.java     |    8 +-
 .../location/basic/AbstractLocation.java        |  707 ------------
 .../basic/AbstractLocationResolver.java         |  188 ----
 .../AggregatingMachineProvisioningLocation.java |  139 ---
 .../location/basic/BasicHardwareDetails.java    |   56 -
 .../location/basic/BasicLocationDefinition.java |   85 --
 .../location/basic/BasicLocationRegistry.java   |  479 --------
 .../location/basic/BasicMachineDetails.java     |  180 ---
 .../location/basic/BasicMachineMetadata.java    |   84 --
 .../brooklyn/location/basic/BasicOsDetails.java |  123 ---
 .../location/basic/ByonLocationResolver.java    |  250 -----
 .../location/basic/CatalogLocationResolver.java |   79 --
 .../basic/DefinedLocationByIdResolver.java      |   74 --
 .../basic/DeprecatedKeysMappingBuilder.java     |   66 --
 .../FixedListMachineProvisioningLocation.java   |  474 --------
 .../location/basic/HasSubnetHostname.java       |   32 -
 .../location/basic/HostLocationResolver.java    |   90 --
 .../basic/LocalhostLocationResolver.java        |   74 --
 .../LocalhostMachineProvisioningLocation.java   |  346 ------
 ...calhostPropertiesFromBrooklynProperties.java |   56 -
 .../location/basic/LocationConfigKeys.java      |   79 --
 .../location/basic/LocationConfigUtils.java     |  558 ----------
 .../location/basic/LocationDynamicType.java     |   39 -
 .../location/basic/LocationInternal.java        |   93 --
 .../location/basic/LocationPredicates.java      |  108 --
 ...ocationPropertiesFromBrooklynProperties.java |  223 ----
 .../location/basic/LocationTypeSnapshot.java    |   40 -
 .../brooklyn/location/basic/Locations.java      |  158 ---
 .../brooklyn/location/basic/Machines.java       |  188 ----
 .../brooklyn/location/basic/MultiLocation.java  |  166 ---
 .../location/basic/MultiLocationResolver.java   |  145 ---
 .../location/basic/NamedLocationResolver.java   |   96 --
 .../brooklyn/location/basic/PortRanges.java     |  257 -----
 .../basic/RegistryLocationResolver.java         |   42 -
 .../basic/SingleMachineLocationResolver.java    |   77 --
 .../SingleMachineProvisioningLocation.java      |   91 --
 .../location/basic/SshMachineLocation.java      | 1032 -----------------
 .../location/basic/SupportsPortForwarding.java  |   39 -
 .../location/basic/WinRmMachineLocation.java    |  361 ------
 .../location/byon/ByonLocationResolver.java     |  253 +++++
 .../FixedListMachineProvisioningLocation.java   |  476 ++++++++
 .../location/byon/HostLocationResolver.java     |   93 ++
 .../byon/SingleMachineLocationResolver.java     |   81 ++
 .../byon/SingleMachineProvisioningLocation.java |   91 ++
 ...bstractCloudMachineProvisioningLocation.java |    2 +-
 .../cloud/AvailabilityZoneExtension.java        |    2 +-
 .../location/cloud/CloudLocationConfig.java     |    2 +-
 .../location/core/AbstractLocation.java         |  709 ++++++++++++
 .../location/core/AbstractLocationResolver.java |  188 ++++
 .../AggregatingMachineProvisioningLocation.java |  141 +++
 .../location/core/BasicHardwareDetails.java     |   56 +
 .../location/core/BasicLocationDefinition.java  |   85 ++
 .../location/core/BasicLocationRegistry.java    |  489 +++++++++
 .../location/core/BasicMachineDetails.java      |  183 ++++
 .../location/core/BasicMachineMetadata.java     |   84 ++
 .../brooklyn/location/core/BasicOsDetails.java  |  123 +++
 .../location/core/CatalogLocationResolver.java  |   79 ++
 .../core/DefinedLocationByIdResolver.java       |   74 ++
 .../core/DeprecatedKeysMappingBuilder.java      |   66 ++
 .../location/core/HasSubnetHostname.java        |   32 +
 .../location/core/LocationConfigKeys.java       |   79 ++
 .../location/core/LocationConfigUtils.java      |  559 ++++++++++
 .../location/core/LocationPredicates.java       |  108 ++
 ...ocationPropertiesFromBrooklynProperties.java |  223 ++++
 .../brooklyn/location/core/Locations.java       |  160 +++
 .../apache/brooklyn/location/core/Machines.java |  191 ++++
 .../brooklyn/location/core/MultiLocation.java   |  166 +++
 .../location/core/MultiLocationResolver.java    |  145 +++
 .../location/core/NamedLocationResolver.java    |   97 ++
 .../brooklyn/location/core/PortRanges.java      |  257 +++++
 .../location/core/RegistryLocationResolver.java |   42 +
 .../location/core/SupportsPortForwarding.java   |   39 +
 .../core/internal/LocationDynamicType.java      |   40 +
 .../core/internal/LocationInternal.java         |   93 ++
 .../core/internal/LocationTypeSnapshot.java     |   40 +
 .../brooklyn/location/geo/HostGeoInfo.java      |    4 +-
 .../localhost/LocalhostLocationResolver.java    |   76 ++
 .../LocalhostMachineProvisioningLocation.java   |  352 ++++++
 ...calhostPropertiesFromBrooklynProperties.java |   57 +
 .../location/ssh/SshMachineLocation.java        | 1037 ++++++++++++++++++
 .../winrm/AdvertiseWinrmLoginPolicy.java        |   80 ++
 .../location/winrm/WinRmMachineLocation.java    |  362 ++++++
 .../brooklyn/sensor/core/HttpRequestSensor.java |    3 -
 .../core/PortAttributeSensorAndConfigKey.java   |    2 +-
 .../brooklyn/sensor/feed/ssh/SshFeed.java       |    6 +-
 .../brooklyn/sensor/feed/ssh/SshPollValue.java  |    2 +-
 .../windows/WindowsPerformanceCounterFeed.java  |    2 +-
 .../brooklyn/util/core/ResourceUtils.java       |    2 +-
 .../brooklyn/util/core/file/ArchiveTasks.java   |    2 +-
 .../brooklyn/util/core/file/ArchiveUtils.java   |    2 +-
 .../util/core/task/ssh/SshFetchTaskFactory.java |    2 +-
 .../util/core/task/ssh/SshFetchTaskWrapper.java |    2 +-
 .../util/core/task/ssh/SshPutTaskFactory.java   |    2 +-
 .../util/core/task/ssh/SshPutTaskStub.java      |    2 +-
 .../brooklyn/util/core/task/ssh/SshTasks.java   |    6 +-
 .../internal/AbstractSshExecTaskFactory.java    |    2 +-
 .../ssh/internal/PlainSshExecTaskFactory.java   |    2 +-
 .../core/task/system/ProcessTaskFactory.java    |    2 +-
 .../util/core/task/system/ProcessTaskStub.java  |    2 +-
 .../internal/AbstractProcessTaskFactory.java    |    2 +-
 .../system/internal/ExecWithLoggingHelpers.java |    2 +-
 .../internal/SystemProcessTaskFactory.java      |    2 +-
 ...pache.brooklyn.api.location.LocationResolver |   16 +-
 ...apListAndOtherStructuredConfigKeyTest.groovy |    2 +-
 .../HighAvailabilityManagerFileBasedTest.java   |    2 +-
 ...ilabilityManagerInMemoryIntegrationTest.java |    4 +-
 .../ha/HighAvailabilityManagerInMemoryTest.java |    8 +-
 .../HighAvailabilityManagerSplitBrainTest.java  |   10 +-
 .../ha/HighAvailabilityManagerTestFixture.java  |   10 +-
 .../brooklyn/core/mgmt/ha/HotStandbyTest.java   |   12 +-
 ...agementPlaneSyncRecordPersisterInMemory.java |    2 +-
 .../core/mgmt/ha/MasterChooserTest.java         |    2 +-
 .../brooklyn/core/mgmt/ha/WarmStandbyTest.java  |   10 +-
 .../core/mgmt/internal/AccessManagerTest.java   |    2 +-
 .../BrooklynMementoPersisterFileBasedTest.java  |   55 +
 ...ntoPersisterInMemorySizeIntegrationTest.java |  106 ++
 .../BrooklynMementoPersisterInMemoryTest.java   |   33 +
 .../BrooklynMementoPersisterTestFixture.java    |  165 +++
 .../mgmt/persist/FileBasedObjectStoreTest.java  |  101 ++
 .../FileBasedStoreObjectAccessorWriterTest.java |   65 ++
 .../core/mgmt/persist/InMemoryObjectStore.java  |  170 +++
 .../InMemoryStoreObjectAccessorWriterTest.java  |   36 +
 .../core/mgmt/persist/ListeningObjectStore.java |  254 +++++
 ...nceStoreObjectAccessorWriterTestFixture.java |  136 +++
 .../mgmt/persist/XmlMementoSerializerTest.java  |  455 ++++++++
 .../core/mgmt/rebind/RebindCatalogItemTest.java |    2 +-
 .../core/mgmt/rebind/RebindEnricherTest.java    |    2 +-
 .../core/mgmt/rebind/RebindEntityTest.java      |    2 +-
 .../core/mgmt/rebind/RebindFeedTest.java        |    4 +-
 .../rebind/RebindLocalhostLocationTest.java     |    4 +-
 .../core/mgmt/rebind/RebindLocationTest.java    |    2 +-
 .../core/mgmt/rebind/RebindOptions.java         |    2 +-
 .../core/mgmt/rebind/RebindPolicyTest.java      |    2 +-
 .../rebind/RebindSshMachineLocationTest.java    |    4 +-
 .../core/mgmt/rebind/RebindTestFixture.java     |    6 +-
 .../core/mgmt/rebind/RebindTestUtils.java       |    8 +-
 .../BrooklynMementoPersisterFileBasedTest.java  |   55 -
 ...ntoPersisterInMemorySizeIntegrationTest.java |  106 --
 .../BrooklynMementoPersisterInMemoryTest.java   |   33 -
 .../BrooklynMementoPersisterTestFixture.java    |  165 ---
 .../persister/FileBasedObjectStoreTest.java     |  101 --
 .../FileBasedStoreObjectAccessorWriterTest.java |   65 --
 .../rebind/persister/InMemoryObjectStore.java   |  170 ---
 .../InMemoryStoreObjectAccessorWriterTest.java  |   36 -
 .../rebind/persister/ListeningObjectStore.java  |  254 -----
 ...nceStoreObjectAccessorWriterTestFixture.java |  136 ---
 .../persister/XmlMementoSerializerTest.java     |  455 --------
 .../transformer/CompoundTransformerTest.java    |    6 +-
 .../policy/basic/PolicySubscriptionTest.java    |    2 +-
 .../core/server/entity/BrooklynMetricsTest.java |    2 +-
 .../apache/brooklyn/core/test/HttpService.java  |    2 +-
 .../core/test/entity/TestApplication.java       |    4 +-
 .../core/test/entity/TestApplicationImpl.java   |    4 +-
 .../core/test/location/TestPaasLocation.java    |    2 +-
 .../longevity/EntityCleanupLongevityTest.java   |    2 +-
 .../EntityCleanupLongevityTestFixture.java      |    2 +-
 .../test/qa/longevity/EntityCleanupTest.java    |    2 +-
 .../qa/performance/AbstractPerformanceTest.java |    2 +-
 .../EntityPersistencePerformanceTest.java       |    2 +-
 .../FilePersistencePerformanceTest.java         |    2 +-
 .../effector/core/EffectorBasicTest.java        |    2 +-
 .../core/AbstractApplicationLegacyTest.java     |    2 +-
 .../entity/core/AbstractEntityLegacyTest.java   |    2 +-
 .../brooklyn/entity/core/EntitiesTest.java      |    2 +-
 .../entity/core/EntitySetFromFlagTest.java      |    2 +-
 .../brooklyn/entity/core/EntitySpecTest.java    |    2 +-
 .../entity/core/EntitySubscriptionTest.java     |    2 +-
 .../entity/core/EntitySuppliersTest.java        |    2 +-
 .../EntityConfigMapUsageLegacyTest.java         |    2 +-
 .../core/internal/EntityConfigMapUsageTest.java |    2 +-
 .../drivers/BasicEntityDriverManagerTest.java   |    4 +-
 .../drivers/EntityDriverRegistryTest.java       |    2 +-
 .../ReflectiveEntityDriverFactoryTest.java      |    2 +-
 .../RegistryEntityDriverFactoryTest.java        |    4 +-
 .../downloads/BasicDownloadsRegistryTest.java   |    2 +-
 .../DownloadProducerFromLocalRepoTest.java      |    2 +-
 .../DownloadProducerFromPropertiesTest.java     |    2 +-
 .../downloads/DownloadSubstitutersTest.java     |    2 +-
 .../entity/group/DynamicClusterTest.java        |    2 +-
 ...DynamicClusterWithAvailabilityZonesTest.java |    4 +-
 .../entity/group/DynamicFabricTest.java         |    4 +-
 .../entity/group/DynamicMultiGroupTest.java     |    2 +-
 .../entity/group/DynamicRegionsFabricTest.java  |    2 +-
 .../apache/brooklyn/entity/group/GroupTest.java |    2 +-
 .../group/MembershipTrackingPolicyTest.java     |    2 +-
 .../entity/group/QuarantineGroupTest.java       |    2 +-
 .../BalancingNodePlacementStrategyTest.java     |    2 +-
 .../ProportionalZoneFailureDetectorTest.java    |    2 +-
 .../entity/hello/LocalEntitiesTest.java         |    2 +-
 .../entity/stock/BasicStartableTest.java        |    4 +-
 .../brooklyn/entity/stock/DataEntityTest.java   |    2 +-
 .../entity/trait/StartableMethodsTest.java      |    2 +-
 .../access/BrooklynAccessUtilsTest.java         |    4 +-
 .../access/PortForwardManagerRebindTest.java    |    8 +-
 .../location/access/PortForwardManagerTest.java |    2 +-
 .../location/basic/AbstractLocationTest.java    |  183 ----
 ...regatingMachineProvisioningLocationTest.java |  115 --
 .../basic/ByonLocationResolverTest.java         |  422 -------
 ...stMachineProvisioningLocationRebindTest.java |  128 ---
 ...ixedListMachineProvisioningLocationTest.java |  574 ----------
 .../basic/HostLocationResolverTest.java         |  125 ---
 .../basic/LegacyAbstractLocationTest.java       |  150 ---
 .../basic/LocalhostLocationResolverTest.java    |  264 -----
 ...ocalhostMachineProvisioningLocationTest.java |  212 ----
 .../LocalhostProvisioningAndAccessTest.java     |   57 -
 .../location/basic/LocationConfigTest.java      |  202 ----
 .../location/basic/LocationConfigUtilsTest.java |  154 ---
 .../location/basic/LocationExtensionsTest.java  |  186 ----
 .../location/basic/LocationManagementTest.java  |   80 --
 .../location/basic/LocationPredicatesTest.java  |   98 --
 ...ionPropertiesFromBrooklynPropertiesTest.java |  121 --
 .../location/basic/LocationRegistryTest.java    |  158 ---
 .../location/basic/MachineDetailsTest.java      |   80 --
 .../location/basic/MultiLocationRebindTest.java |  119 --
 .../basic/MultiLocationResolverTest.java        |  198 ----
 .../location/basic/MultiLocationTest.java       |  118 --
 .../location/basic/PaasLocationTest.java        |   35 -
 .../brooklyn/location/basic/PortRangesTest.java |  129 ---
 .../RecordingMachineLocationCustomizer.java     |   71 --
 .../location/basic/SimulatedLocation.java       |  136 ---
 .../SingleMachineLocationResolverTest.java      |  130 ---
 .../SingleMachineProvisioningLocationTest.java  |   63 --
 .../SshMachineLocationIntegrationTest.java      |  139 ---
 .../SshMachineLocationPerformanceTest.java      |  171 ---
 .../SshMachineLocationReuseIntegrationTest.java |  171 ---
 .../location/basic/SshMachineLocationTest.java  |  339 ------
 .../basic/TestPortSupplierLocation.java         |   89 --
 .../location/byon/ByonLocationResolverTest.java |  429 ++++++++
 ...stMachineProvisioningLocationRebindTest.java |  131 +++
 ...ixedListMachineProvisioningLocationTest.java |  578 ++++++++++
 .../location/byon/HostLocationResolverTest.java |  126 +++
 .../byon/SingleMachineLocationResolverTest.java |  132 +++
 .../SingleMachineProvisioningLocationTest.java  |   65 ++
 .../location/core/AbstractLocationTest.java     |  185 ++++
 ...regatingMachineProvisioningLocationTest.java |  117 ++
 .../core/LegacyAbstractLocationTest.java        |  151 +++
 .../location/core/LocationConfigTest.java       |  204 ++++
 .../location/core/LocationConfigUtilsTest.java  |  156 +++
 .../location/core/LocationExtensionsTest.java   |  187 ++++
 .../location/core/LocationManagementTest.java   |   82 ++
 .../location/core/LocationPredicatesTest.java   |  102 ++
 ...ionPropertiesFromBrooklynPropertiesTest.java |  122 +++
 .../location/core/LocationRegistryTest.java     |  161 +++
 .../location/core/MachineDetailsTest.java       |   83 ++
 .../location/core/MultiLocationRebindTest.java  |  122 +++
 .../core/MultiLocationResolverTest.java         |  203 ++++
 .../location/core/MultiLocationTest.java        |  121 ++
 .../location/core/PaasLocationTest.java         |   35 +
 .../brooklyn/location/core/PortRangesTest.java  |  130 +++
 .../RecordingMachineLocationCustomizer.java     |   71 ++
 .../location/core/SimulatedLocation.java        |  141 +++
 .../location/core/TestPortSupplierLocation.java |   90 ++
 .../LocalhostLocationResolverTest.java          |  269 +++++
 ...ocalhostMachineProvisioningLocationTest.java |  215 ++++
 .../LocalhostProvisioningAndAccessTest.java     |   59 +
 .../brooklyn/location/geo/HostGeoInfoTest.java  |    2 +-
 .../geo/HostGeoLookupIntegrationTest.java       |    4 +-
 .../ssh/SshMachineLocationIntegrationTest.java  |  141 +++
 .../ssh/SshMachineLocationPerformanceTest.java  |  172 +++
 .../SshMachineLocationReuseIntegrationTest.java |  172 +++
 .../location/ssh/SshMachineLocationTest.java    |  345 ++++++
 .../winrm/AdvertiseWinrmLoginPolicyTest.java    |   51 +
 .../winrm/WinRmMachineLocationTest.java         |   44 +
 ...stomAggregatingEnricherDeprecatedTest.groovy |    5 +-
 .../enricher/CustomAggregatingEnricherTest.java |    2 +-
 .../TransformingEnricherDeprecatedTest.groovy   |    2 +-
 .../enricher/TransformingEnricherTest.java      |    2 +-
 .../sensor/feed/function/FunctionFeedTest.java  |    2 +-
 .../feed/http/HttpFeedIntegrationTest.java      |    4 +-
 .../feed/shell/ShellFeedIntegrationTest.java    |    2 +-
 .../sensor/feed/ssh/SshFeedIntegrationTest.java |    4 +-
 .../WindowsPerformanceCounterFeedTest.java      |    2 +-
 .../util/core/file/ArchiveUtilsTest.java        |    2 +-
 .../util/core/http/HttpToolIntegrationTest.java |    2 +-
 .../core/ssh/BashCommandsIntegrationTest.java   |    4 +-
 .../util/core/task/ssh/SshTasksTest.java        |    4 +-
 .../brooklyn/demo/GlobalWebFabricExample.java   |    2 +-
 .../brooklyn/demo/CumulusRDFApplication.java    |    2 +-
 .../brooklyn/demo/SingleWebServerExample.java   |    2 +-
 .../demo/WebClusterDatabaseExample.java         |    2 +-
 .../demo/WebClusterDatabaseExampleApp.java      |    2 +-
 .../demo/WebClusterDatabaseExampleGroovy.groovy |    2 +-
 .../JcloudsBlobStoreBasedObjectStore.java       |  237 ----
 .../jclouds/JcloudsStoreObjectAccessor.java     |  127 ---
 .../policy/os/AdvertiseWinrmLoginPolicy.java    |   81 --
 .../brooklyn/policy/os/CreateUserPolicy.java    |  173 ---
 .../JcloudsBlobStoreBasedObjectStore.java       |  237 ++++
 .../jclouds/JcloudsStoreObjectAccessor.java     |  127 +++
 ...AbstractJcloudsSubnetSshMachineLocation.java |    3 +-
 .../location/jclouds/BrooklynMachinePool.java   |    2 +-
 .../jclouds/JcloudsByonLocationResolver.java    |   12 +-
 .../location/jclouds/JcloudsLocation.java       |   21 +-
 .../location/jclouds/JcloudsLocationConfig.java |    4 +-
 .../jclouds/JcloudsLocationResolver.java        |    8 +-
 .../jclouds/JcloudsMachineLocation.java         |    2 +-
 ...JcloudsPropertiesFromBrooklynProperties.java |    6 +-
 .../jclouds/JcloudsSshMachineLocation.java      |    8 +-
 .../jclouds/JcloudsWinRmMachineLocation.java    |    2 +-
 .../jclouds/SudoTtyFixingCustomizer.java        |    2 +-
 .../policy/jclouds/os/CreateUserPolicy.java     |  173 +++
 .../location/jclouds/sample/setup-server.sh     |   31 +
 .../resources/sample/script/setup-server.sh     |   31 -
 .../persister/jclouds/BlobStoreCleaner.java     |   71 --
 .../persister/jclouds/BlobStoreExpiryTest.java  |  196 ----
 .../BlobStorePersistencePerformanceTest.java    |  120 --
 .../rebind/persister/jclouds/BlobStoreTest.java |  150 ---
 ...nMementoPersisterJcloudsObjectStoreTest.java |   66 --
 ...tyToBlobStorePersistencePerformanceTest.java |   64 --
 ...ailabilityManagerJcloudsObjectStoreTest.java |   79 --
 .../JcloudsBlobStoreBasedObjectStoreTest.java   |  118 --
 .../jclouds/JcloudsExpect100ContinueTest.java   |  148 ---
 .../JcloudsObjectStoreAccessorWriterTest.java   |  181 ---
 .../os/AdvertiseWinrmLoginPolicyTest.java       |   50 -
 .../policy/os/CreateUserPolicyLiveTest.java     |  111 --
 .../policy/os/CreateUserPolicyTest.java         |  136 ---
 .../mgmt/persist/jclouds/BlobStoreCleaner.java  |   71 ++
 .../persist/jclouds/BlobStoreExpiryTest.java    |  196 ++++
 .../BlobStorePersistencePerformanceTest.java    |  121 ++
 .../mgmt/persist/jclouds/BlobStoreTest.java     |  150 +++
 ...nMementoPersisterJcloudsObjectStoreTest.java |   67 ++
 ...tyToBlobStorePersistencePerformanceTest.java |   65 ++
 ...ailabilityManagerJcloudsObjectStoreTest.java |   80 ++
 .../JcloudsBlobStoreBasedObjectStoreTest.java   |  118 ++
 .../jclouds/JcloudsExpect100ContinueTest.java   |  148 +++
 .../JcloudsObjectStoreAccessorWriterTest.java   |  182 +++
 .../jclouds/AbstractJcloudsLiveTest.java        |    2 +-
 .../jclouds/BailOutJcloudsLocation.java         |    4 +-
 .../jclouds/BrooklynMachinePoolLiveTest.java    |    2 +-
 .../jclouds/JcloudsAddressesLiveTest.java       |    4 +-
 .../JcloudsByonLocationResolverAwsLiveTest.java |    2 +-
 ...dsByonLocationResolverSoftlayerLiveTest.java |    2 +-
 .../JcloudsByonLocationResolverTest.java        |    2 +-
 .../jclouds/JcloudsLocationMetadataTest.java    |    2 +-
 .../JcloudsLocationRebindMachineLiveTest.java   |    2 +-
 .../jclouds/JcloudsLocationResolverTest.java    |    2 +-
 .../location/jclouds/JcloudsLocationTest.java   |    2 +-
 .../location/jclouds/JcloudsLoginLiveTest.java  |    2 +-
 .../location/jclouds/LiveTestEntity.java        |    2 +-
 .../jclouds/RebindJcloudsLocationTest.java      |    2 +-
 ...loudsLocationUserLoginAndConfigLiveTest.java |    2 +-
 ...hineProvisioningLocationJcloudsLiveTest.java |    2 +-
 .../provider/AbstractJcloudsLocationTest.java   |    2 +-
 .../AwsEc2LocationWindowsLiveTest.groovy        |    2 +-
 .../provider/CarrenzaLocationLiveTest.groovy    |    2 +-
 .../provider/RackspaceLocationLiveTest.java     |    2 +-
 .../jclouds/os/CreateUserPolicyLiveTest.java    |  112 ++
 .../policy/jclouds/os/CreateUserPolicyTest.java |  137 +++
 .../followthesun/DefaultFollowTheSunModel.java  |    2 +-
 .../policy/ha/SshMachineFailureDetector.java    |    4 +-
 .../autoscaling/AutoScalerPolicyRebindTest.java |    2 +-
 .../enricher/HttpLatencyDetectorTest.java       |    2 +-
 .../AbstractFollowTheSunPolicyTest.java         |    2 +-
 .../followthesun/FollowTheSunModelTest.java     |    3 +-
 .../FollowTheSunPolicySoakTest.java             |    2 +-
 .../followthesun/FollowTheSunPolicyTest.java    |    2 +-
 .../brooklyn/policy/ha/HaPolicyRebindTest.java  |    2 +-
 .../brooklyn/policy/ha/ServiceReplacerTest.java |    2 +-
 .../AbstractLoadBalancingPolicyTest.java        |    2 +-
 .../BalanceableWorkerPoolTest.java              |    2 +-
 .../ItemsInContainersGroupTest.java             |    2 +-
 .../entity/monitoring/zabbix/ZabbixFeed.java    |    2 +-
 .../monitoring/zabbix/ZabbixServerImpl.java     |    2 +-
 .../entity/brooklynnode/BrooklynNodeImpl.java   |    2 +-
 .../brooklynnode/BrooklynNodeSshDriver.java     |    2 +-
 .../entity/chef/ChefLifecycleEffectorTasks.java |    2 +-
 .../brooklyn/entity/chef/ChefServerTasks.java   |    2 +-
 .../brooklyn/entity/chef/ChefSoloDriver.java    |    2 +-
 .../entity/chef/KnifeConvergeTaskFactory.java   |    2 +-
 .../java/JavaSoftwareProcessSshDriver.java      |    2 +-
 .../apache/brooklyn/entity/java/JmxSupport.java |    4 +-
 .../apache/brooklyn/entity/java/UsesJmx.java    |    2 +-
 .../entity/java/VanillaJavaAppSshDriver.java    |    2 +-
 .../entity/machine/MachineEntityImpl.java       |    4 +-
 .../entity/machine/MachineInitTasks.java        |    2 +-
 .../entity/machine/pool/ServerPoolImpl.java     |    4 +-
 .../entity/machine/pool/ServerPoolLocation.java |    2 +-
 .../pool/ServerPoolLocationResolver.java        |    6 +-
 .../base/AbstractSoftwareProcessSshDriver.java  |    2 +-
 .../AbstractSoftwareProcessWinRmDriver.java     |    2 +-
 .../base/EmptySoftwareProcessSshDriver.java     |    2 +-
 .../SameServerDriverLifecycleEffectorTasks.java |    2 +-
 .../software/base/SoftwareProcessImpl.java      |    4 +-
 .../base/VanillaSoftwareProcessSshDriver.java   |    2 +-
 .../base/VanillaWindowsProcessWinRmDriver.java  |    2 +-
 .../MachineLifecycleEffectorTasks.java          |   10 +-
 .../software/base/lifecycle/ScriptHelper.java   |    2 +-
 .../system_service/InitdServiceInstaller.java   |    2 +-
 .../system_service/SystemServiceEnricher.java   |    2 +-
 .../brooklyn/sensor/ssh/SshEffectorTasks.java   |    4 +-
 ...pache.brooklyn.api.location.LocationResolver |    2 +-
 .../BrooklynClusterIntegrationTest.java         |    2 +-
 .../BrooklynNodeIntegrationTest.java            |    8 +-
 .../entity/brooklynnode/BrooklynNodeTest.java   |    2 +-
 .../entity/chef/ChefLiveTestSupport.java        |    2 +-
 .../AbstractChefToyMySqlEntityLiveTest.java     |    2 +-
 .../brooklyn/entity/java/EntityPollingTest.java |    2 +-
 .../brooklyn/entity/java/JavaOptsTest.java      |    2 +-
 ...SoftwareProcessSshDriverIntegrationTest.java |    2 +-
 .../entity/java/VanillaJavaAppRebindTest.java   |    2 +-
 .../entity/java/VanillaJavaAppTest.java         |    4 +-
 .../machine/pool/AbstractServerPoolTest.java    |    2 +-
 .../pool/ServerPoolLocationResolverTest.java    |    2 +-
 .../entity/machine/pool/ServerPoolTest.java     |    2 +-
 ...ctSoftwareProcessRestartIntegrationTest.java |    2 +-
 .../base/DoNothingSoftwareProcessDriver.java    |    2 +-
 .../base/MachineLifecycleEffectorTasksTest.java |  140 ---
 .../software/base/SameServerEntityTest.java     |    4 +-
 .../software/base/SoftwareEffectorTest.java     |    4 +-
 .../base/SoftwareProcessEntityLatchTest.java    |    4 +-
 .../base/SoftwareProcessEntityRebindTest.java   |    4 +-
 .../base/SoftwareProcessEntityTest.java         |    9 +-
 ...SoftwareProcessSshDriverIntegrationTest.java |    4 +-
 .../MachineLifecycleEffectorTasksTest.java      |  147 +++
 .../software/base/lifecycle/MyEntityImpl.java   |    2 +-
 .../base/lifecycle/NaiveScriptRunnerTest.java   |    2 +-
 .../base/lifecycle/ScriptHelperTest.java        |    4 +-
 .../base/lifecycle/StartStopSshDriverTest.java  |    2 +-
 .../mgmt/usage/LocationUsageTrackingTest.java   |    4 +-
 .../base/test/driver/MockSshDriver.java         |    2 +-
 ...rWithAvailabilityZonesMultiLocationTest.java |    4 +-
 .../location/MachineDetailsEc2LiveTest.java     |    6 +-
 .../MachineDetailsGoogleComputeLiveTest.java    |    6 +-
 .../test/location/WinRmMachineLocationTest.java |   44 -
 .../test/mysql/AbstractToyMySqlEntityTest.java  |    4 +-
 .../mysql/DynamicToyMySqlEntityBuilder.java     |    6 +-
 .../test/mysql/DynamicToyMySqlEntityTest.java   |    2 +-
 .../PortAttributeSensorAndConfigKeyTest.java    |    4 +-
 .../test/ssh/SshCommandIntegrationTest.java     |    2 +-
 .../SystemServiceEnricherTest.java              |    2 +-
 .../brooklyn/sensor/feed/jmx/JmxFeedTest.java   |    6 +-
 .../sensor/feed/jmx/RebindJmxFeedTest.java      |    4 +-
 .../sensor/ssh/SshEffectorTasksTest.java        |    4 +-
 .../entity/database/crate/CrateNode.java        |    2 +-
 .../database/crate/CrateNodeSshDriver.java      |    2 +-
 .../entity/database/mariadb/MariaDbNode.java    |    2 +-
 .../database/mariadb/MariaDbNodeImpl.java       |    4 +-
 .../database/mariadb/MariaDbSshDriver.java      |    2 +-
 .../entity/database/mysql/MySqlNode.java        |    2 +-
 .../entity/database/mysql/MySqlNodeImpl.java    |    4 +-
 .../entity/database/mysql/MySqlSshDriver.java   |    4 +-
 .../database/postgresql/PostgreSqlNode.java     |    2 +-
 .../PostgreSqlNodeChefImplFromScratch.java      |    4 +-
 .../postgresql/PostgreSqlSshDriver.java         |    2 +-
 .../database/rubyrep/RubyRepSshDriver.java      |    2 +-
 .../crate/CrateNodeIntegrationTest.java         |    2 +-
 .../mariadb/MariaDbIntegrationTest.java         |    2 +-
 .../mariadb/MariaDbLiveRackspaceTest.java       |    2 +-
 .../database/mysql/MySqlIntegrationTest.java    |    2 +-
 .../database/mysql/MySqlLiveRackspaceTest.java  |    2 +-
 .../database/postgresql/PostgreSqlChefTest.java |    4 +-
 .../postgresql/PostgreSqlIntegrationTest.java   |    2 +-
 .../postgresql/PostgreSqlRackspaceLiveTest.java |    4 +-
 .../PostgreSqlRebindIntegrationTest.java        |    2 +-
 .../database/rubyrep/RubyRepEc2LiveTest.java    |    2 +-
 .../rubyrep/RubyRepIntegrationTest.java         |    4 +-
 .../rubyrep/RubyRepRackspaceLiveTest.java       |    4 +-
 .../messaging/activemq/ActiveMQSshDriver.java   |    2 +-
 .../kafka/AbstractfKafkaSshDriver.java          |    2 +-
 .../entity/messaging/kafka/KafkaBroker.java     |    2 +-
 .../messaging/kafka/KafkaBrokerSshDriver.java   |    2 +-
 .../kafka/KafkaZooKeeperSshDriver.java          |    2 +-
 .../entity/messaging/qpid/QpidSshDriver.java    |    2 +-
 .../messaging/rabbit/RabbitDestination.java     |    2 +-
 .../messaging/rabbit/RabbitSshDriver.java       |    2 +-
 .../entity/messaging/storm/StormSshDriver.java  |    4 +-
 .../entity/zookeeper/ZooKeeperSshDriver.java    |    2 +-
 .../messaging/kafka/KafkaIntegrationTest.java   |    2 +-
 .../messaging/rabbit/RabbitIntegrationTest.java |    2 +-
 .../entity/monitoring/monit/MonitNodeImpl.java  |    2 +-
 .../entity/monitoring/monit/MonitSshDriver.java |    2 +-
 .../monitoring/monit/MonitIntegrationTest.java  |    2 +-
 .../entity/network/bind/BindDnsServer.java      |    2 +-
 .../entity/network/bind/BindDnsServerImpl.java  |    4 +-
 .../network/bind/BindDnsServerSshDriver.java    |    2 +-
 .../bind/DoNothingSoftwareProcessDriver.java    |    2 +-
 .../network/bind/TestBindDnsServerImpl.java     |    2 +-
 .../cassandra/CassandraDatacenterImpl.java      |    2 +-
 .../entity/nosql/cassandra/CassandraNode.java   |    2 +-
 .../nosql/cassandra/CassandraNodeImpl.java      |    2 +-
 .../nosql/cassandra/CassandraNodeSshDriver.java |    4 +-
 .../nosql/couchbase/CouchbaseNodeSshDriver.java |    2 +-
 .../CouchbaseSyncGatewaySshDriver.java          |    2 +-
 .../nosql/couchdb/CouchDBNodeSshDriver.java     |    2 +-
 .../nosql/elasticsearch/ElasticSearchNode.java  |    2 +-
 .../ElasticSearchNodeSshDriver.java             |    2 +-
 .../nosql/mongodb/AbstractMongoDBSshDriver.java |    2 +-
 .../nosql/mongodb/MongoDBClientSshDriver.java   |    2 +-
 .../entity/nosql/mongodb/MongoDBSshDriver.java  |    3 +-
 .../sharding/MongoDBConfigServerSshDriver.java  |    3 +-
 .../sharding/MongoDBRouterSshDriver.java        |    3 +-
 .../entity/nosql/redis/RedisStoreImpl.java      |    2 +-
 .../entity/nosql/redis/RedisStoreSshDriver.java |    2 +-
 .../entity/nosql/riak/RiakNodeSshDriver.java    |    2 +-
 .../brooklyn/entity/nosql/solr/SolrServer.java  |    2 +-
 .../entity/nosql/solr/SolrServerSshDriver.java  |    2 +-
 ...assandraDatacenterRebindIntegrationTest.java |    2 +-
 .../cassandra/CassandraDatacenterTest.java      |    2 +-
 .../nosql/cassandra/CassandraFabricTest.java    |    2 +-
 .../nosql/couchbase/CouchbaseOfflineTest.java   |    4 +-
 .../nosql/couchdb/AbstractCouchDBNodeTest.java  |    2 +-
 .../ElasticSearchNodeIntegrationTest.java       |    2 +-
 .../nosql/mongodb/MongoDBIntegrationTest.java   |    2 +-
 .../mongodb/MongoDBRebindIntegrationTest.java   |    2 +-
 .../MongoDBReplicaSetIntegrationTest.java       |    2 +-
 .../MongoDBConfigServerIntegrationTest.java     |    2 +-
 ...MongoDBShardedDeploymentIntegrationTest.java |    2 +-
 .../redis/RedisClusterIntegrationTest.java      |    2 +-
 .../nosql/redis/RedisIntegrationTest.java       |    2 +-
 .../nosql/riak/RiakNodeIntegrationTest.java     |    2 +-
 .../entity/osgi/karaf/KarafSshDriver.java       |    2 +-
 .../entity/osgi/karaf/KarafContainerTest.java   |    2 +-
 .../entity/proxy/AbstractControllerImpl.java    |    2 +-
 .../entity/proxy/nginx/NginxSshDriver.java      |    2 +-
 .../entity/webapp/JavaWebAppSshDriver.java      |    2 +-
 .../entity/webapp/jboss/JBoss6SshDriver.java    |    2 +-
 .../entity/webapp/jboss/JBoss7SshDriver.java    |    2 +-
 .../entity/webapp/jetty/Jetty6SshDriver.java    |    2 +-
 .../webapp/nodejs/NodeJsWebAppService.java      |    2 +-
 .../webapp/nodejs/NodeJsWebAppSshDriver.java    |    2 +-
 .../entity/webapp/tomcat/Tomcat7SshDriver.java  |    2 +-
 .../entity/webapp/tomcat/TomcatServer.java      |    2 +-
 .../entity/webapp/tomcat/TomcatSshDriver.java   |    2 +-
 .../entity/dns/AbstractGeoDnsServiceTest.java   |   12 +-
 .../geoscaling/GeoscalingIntegrationTest.java   |    2 +-
 .../entity/proxy/AbstractControllerTest.java    |    4 +-
 .../brooklyn/entity/proxy/UrlMappingTest.java   |    2 +-
 .../nginx/NginxClusterIntegrationTest.java      |    2 +-
 .../nginx/NginxHttpsSslIntegrationTest.java     |    2 +-
 .../proxy/nginx/NginxLightIntegrationTest.java  |    2 +-
 .../proxy/nginx/NginxRebindIntegrationTest.java |    2 +-
 .../nginx/NginxRebindWithHaIntegrationTest.java |    4 +-
 .../nginx/NginxUrlMappingIntegrationTest.java   |    2 +-
 .../proxy/nginx/NginxWebClusterEc2LiveTest.java |    2 +-
 .../AbstractWebAppFixtureIntegrationTest.java   |    2 +-
 ...lledDynamicWebAppClusterIntegrationTest.java |    2 +-
 .../ControlledDynamicWebAppClusterTest.java     |    2 +-
 .../entity/webapp/DynamicWebAppClusterTest.java |    2 +-
 .../entity/webapp/DynamicWebAppFabricTest.java  |    2 +-
 .../webapp/ElasticCustomLocationTest.java       |    2 +-
 ...ElasticJavaWebAppServiceIntegrationTest.java |    2 +-
 .../webapp/TomcatAutoScalerPolicyTest.java      |    2 +-
 .../webapp/WebAppConcurrentDeployTest.java      |    2 +-
 .../webapp/WebAppLiveIntegrationTest.groovy     |    5 +-
 ...namicWebAppClusterRebindIntegrationTest.java |    2 +-
 ...namicWebAppClusterRebindIntegrationTest.java |    2 +-
 ...Boss6ServerNonInheritingIntegrationTest.java |    2 +-
 ...Boss7ServerNonInheritingIntegrationTest.java |    2 +-
 .../JBoss7ServerRebindingIntegrationTest.java   |    2 +-
 ...ultiVersionWebAppFixtureIntegrationTest.java |    2 +-
 .../JettyWebAppFixtureIntegrationTest.java      |    2 +-
 .../NodeJsWebAppFixtureIntegrationTest.java     |    2 +-
 .../NodeJsWebAppSimpleIntegrationTest.java      |    4 +-
 ...mcat8ServerWebAppFixtureIntegrationTest.java |    2 +-
 ...ableRetrieveUsageMetricsIntegrationTest.java |    2 +-
 ...omcatServerWebAppFixtureIntegrationTest.java |    2 +-
 .../camp/brooklyn/ByonLocationsYamlTest.java    |   10 +-
 .../brooklyn/EmptySoftwareProcessYamlTest.java  |    2 +-
 .../camp/brooklyn/LocationsYamlTest.java        |    8 +-
 .../catalog/CatalogYamlLocationTest.java        |    2 +-
 .../org/apache/brooklyn/cli/CloudExplorer.java  |    2 +-
 .../main/java/org/apache/brooklyn/cli/Main.java |    4 +-
 .../java/org/apache/brooklyn/cli/CliTest.java   |    2 +-
 .../brooklyn/launcher/BrooklynLauncher.java     |   12 +-
 .../brooklyn/launcher/BrooklynWebServer.java    |    4 +-
 .../BrooklynLauncherHighAvailabilityTest.java   |    2 +-
 .../BrooklynLauncherRebindCatalogTest.java      |    2 +-
 .../BrooklynLauncherRebindTestFixture.java      |    6 +-
 .../BrooklynLauncherRebindTestToFiles.java      |    6 +-
 ...lynLauncherRebindToCloudObjectStoreTest.java |    9 +-
 .../brooklyn/launcher/BrooklynLauncherTest.java |    2 +-
 .../blueprints/AbstractBlueprintTest.java       |    2 +-
 .../qa/load/SimulatedJBoss7ServerImpl.java      |    2 +-
 .../qa/load/SimulatedMySqlNodeImpl.java         |    2 +-
 .../qa/load/SimulatedNginxControllerImpl.java   |    2 +-
 .../brooklyn/qa/load/SimulatedTheeTierApp.java  |    2 +-
 .../org/apache/brooklyn/qa/load/LoadTest.java   |    2 +-
 .../ApplicationResourceIntegrationTest.java     |    2 +-
 .../rest/client/BrooklynApiRestClientTest.java  |    2 +-
 .../rest/resources/LocationResource.java        |    2 +-
 .../brooklyn/rest/resources/ServerResource.java |    6 +-
 .../rest/transform/LocationTransformer.java     |    6 +-
 .../brooklyn/rest/util/EntityLocationUtils.java |    2 +-
 .../rest/resources/ApplicationResourceTest.java |    6 +-
 .../rest/resources/LocationResourceTest.java    |    2 +-
 .../rest/resources/UsageResourceTest.java       |    4 +-
 .../rest/testing/BrooklynRestApiTest.java       |    2 +-
 .../testing/mocks/RestMockSimpleEntity.java     |    2 +-
 .../rest/util/EntityLocationUtilsTest.java      |    4 +-
 .../test/osgi/entities/SimpleLocation.java      |    2 +-
 .../test/osgi/entities/more/MoreLocation.java   |    2 +-
 648 files changed, 20297 insertions(+), 20156 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/catalog/CatalogLoadMode.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/catalog/CatalogLoadMode.java b/core/src/main/java/org/apache/brooklyn/core/catalog/CatalogLoadMode.java
index 1bf6020..73f5a4e 100644
--- a/core/src/main/java/org/apache/brooklyn/core/catalog/CatalogLoadMode.java
+++ b/core/src/main/java/org/apache/brooklyn/core/catalog/CatalogLoadMode.java
@@ -19,7 +19,7 @@
 package org.apache.brooklyn.core.catalog;
 
 import org.apache.brooklyn.core.catalog.internal.CatalogInitialization;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
 import org.slf4j.LoggerFactory;
 
 /** @deprecated since 0.7.0 replaced by {@link CatalogInitialization} */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/catalog/internal/BasicBrooklynCatalog.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/catalog/internal/BasicBrooklynCatalog.java b/core/src/main/java/org/apache/brooklyn/core/catalog/internal/BasicBrooklynCatalog.java
index 1b197d4..4fd7878 100644
--- a/core/src/main/java/org/apache/brooklyn/core/catalog/internal/BasicBrooklynCatalog.java
+++ b/core/src/main/java/org/apache/brooklyn/core/catalog/internal/BasicBrooklynCatalog.java
@@ -54,7 +54,7 @@ import org.apache.brooklyn.core.catalog.internal.CatalogClasspathDo.CatalogScann
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
 import org.apache.brooklyn.core.objs.BrooklynObjectInternal.ConfigurationSupportInternal;
 import org.apache.brooklyn.core.server.BrooklynServerConfig;
-import org.apache.brooklyn.location.basic.BasicLocationRegistry;
+import org.apache.brooklyn.location.core.BasicLocationRegistry;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.collections.MutableSet;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/internal/BrooklynInitialization.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/internal/BrooklynInitialization.java b/core/src/main/java/org/apache/brooklyn/core/internal/BrooklynInitialization.java
index 715cff6..e28be77 100644
--- a/core/src/main/java/org/apache/brooklyn/core/internal/BrooklynInitialization.java
+++ b/core/src/main/java/org/apache/brooklyn/core/internal/BrooklynInitialization.java
@@ -20,7 +20,7 @@ package org.apache.brooklyn.core.internal;
 
 import java.util.concurrent.atomic.AtomicBoolean;
 
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.util.core.crypto.SecureKeys;
 import org.apache.brooklyn.util.core.flags.TypeCoercions;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerImpl.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerImpl.java
index 6f2bcba..df6f402 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerImpl.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerImpl.java
@@ -50,18 +50,18 @@ import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.core.internal.BrooklynFeatureEnablement;
 import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
 import org.apache.brooklyn.core.mgmt.ha.BasicMasterChooser.AlphabeticMasterChooser;
+import org.apache.brooklyn.core.mgmt.ha.dto.BasicManagementNodeSyncRecord;
+import org.apache.brooklyn.core.mgmt.ha.dto.ManagementPlaneSyncRecordImpl;
+import org.apache.brooklyn.core.mgmt.ha.dto.ManagementPlaneSyncRecordImpl.Builder;
 import org.apache.brooklyn.core.mgmt.internal.BrooklynObjectManagementMode;
 import org.apache.brooklyn.core.mgmt.internal.LocalEntityManager;
 import org.apache.brooklyn.core.mgmt.internal.LocationManagerInternal;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
 import org.apache.brooklyn.core.mgmt.internal.ManagementTransitionMode;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynPersistenceUtils;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceActivityMetrics;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynPersistenceUtils.CreateBackupMode;
 import org.apache.brooklyn.core.mgmt.rebind.RebindManagerImpl;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynPersistenceUtils;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceActivityMetrics;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynPersistenceUtils.CreateBackupMode;
-import org.apache.brooklyn.core.mgmt.rebind.plane.dto.BasicManagementNodeSyncRecord;
-import org.apache.brooklyn.core.mgmt.rebind.plane.dto.ManagementPlaneSyncRecordImpl;
-import org.apache.brooklyn.core.mgmt.rebind.plane.dto.ManagementPlaneSyncRecordImpl.Builder;
 import org.apache.brooklyn.core.server.BrooklynServerConfig;
 import org.apache.brooklyn.entity.core.EntityInternal;
 import org.apache.brooklyn.util.collections.MutableList;
@@ -1020,7 +1020,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager {
 
     protected ManagementNodeSyncRecord createManagementNodeSyncRecord(boolean useLocalTimestampAsRemoteTimestamp) {
         long timestamp = currentTimeMillis();
-        org.apache.brooklyn.core.mgmt.rebind.plane.dto.BasicManagementNodeSyncRecord.Builder builder = BasicManagementNodeSyncRecord.builder()
+        org.apache.brooklyn.core.mgmt.ha.dto.BasicManagementNodeSyncRecord.Builder builder = BasicManagementNodeSyncRecord.builder()
                 .brooklynVersion(BrooklynVersion.get())
                 .nodeId(ownNodeId)
                 .status(getNodeState())

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/ManagementPlaneSyncRecordPersisterToObjectStore.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/ManagementPlaneSyncRecordPersisterToObjectStore.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/ManagementPlaneSyncRecordPersisterToObjectStore.java
index 92093c6..8380a9f 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/ManagementPlaneSyncRecordPersisterToObjectStore.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/ManagementPlaneSyncRecordPersisterToObjectStore.java
@@ -33,14 +33,14 @@ import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
 import org.apache.brooklyn.api.mgmt.ha.ManagementNodeSyncRecord;
 import org.apache.brooklyn.api.mgmt.ha.ManagementPlaneSyncRecord;
 import org.apache.brooklyn.api.mgmt.ha.ManagementPlaneSyncRecordPersister;
-import org.apache.brooklyn.core.mgmt.rebind.persister.MementoSerializer;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.RetryingMementoSerializer;
-import org.apache.brooklyn.core.mgmt.rebind.persister.StoreObjectAccessorLocking;
-import org.apache.brooklyn.core.mgmt.rebind.persister.XmlMementoSerializer;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore.StoreObjectAccessorWithLock;
-import org.apache.brooklyn.core.mgmt.rebind.plane.dto.BasicManagementNodeSyncRecord;
-import org.apache.brooklyn.core.mgmt.rebind.plane.dto.ManagementPlaneSyncRecordImpl;
+import org.apache.brooklyn.core.mgmt.ha.dto.BasicManagementNodeSyncRecord;
+import org.apache.brooklyn.core.mgmt.ha.dto.ManagementPlaneSyncRecordImpl;
+import org.apache.brooklyn.core.mgmt.persist.MementoSerializer;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.RetryingMementoSerializer;
+import org.apache.brooklyn.core.mgmt.persist.StoreObjectAccessorLocking;
+import org.apache.brooklyn.core.mgmt.persist.XmlMementoSerializer;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore.StoreObjectAccessorWithLock;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.apache.brooklyn.util.text.Strings;
 import org.apache.brooklyn.util.time.Duration;
@@ -111,7 +111,7 @@ public class ManagementPlaneSyncRecordPersisterToObjectStore implements Manageme
     /**
      * @param mgmt not used much at present but handy to ensure we know it so that obj store is prepared
      * @param objectStore the objectStore use to read/write management-plane data;
-     *   this must have been {@link PersistenceObjectStore#prepareForSharedUse(org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode, HighAvailabilityMode)}
+     *   this must have been {@link PersistenceObjectStore#prepareForSharedUse(org.apache.brooklyn.core.mgmt.persist.PersistMode, HighAvailabilityMode)}
      * @param classLoader ClassLoader to use when deserializing data
      */
     public ManagementPlaneSyncRecordPersisterToObjectStore(ManagementContext mgmt, PersistenceObjectStore objectStore, ClassLoader classLoader) {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/dto/BasicManagementNodeSyncRecord.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/dto/BasicManagementNodeSyncRecord.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/dto/BasicManagementNodeSyncRecord.java
new file mode 100644
index 0000000..d8f18b1
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/dto/BasicManagementNodeSyncRecord.java
@@ -0,0 +1,194 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.ha.dto;
+
+import java.io.Serializable;
+import java.net.URI;
+
+import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
+import org.apache.brooklyn.api.mgmt.ha.ManagementNodeSyncRecord;
+import org.apache.brooklyn.core.BrooklynVersion;
+import org.apache.brooklyn.util.time.Time;
+import org.codehaus.jackson.annotate.JsonAutoDetect;
+import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
+
+import com.google.common.base.Objects;
+
+/**
+ * Represents the state of a management node within the Brooklyn management plane
+ * (DTO class).
+ * 
+ * @author aled
+ */
+@JsonAutoDetect(fieldVisibility=Visibility.ANY, getterVisibility=Visibility.NONE)
+public class BasicManagementNodeSyncRecord implements ManagementNodeSyncRecord, Serializable {
+
+    private static final long serialVersionUID = 4918161834047884244L;
+
+    public static Builder builder() {
+        return new Builder();
+    }
+
+    public static class Builder {
+        private String brooklynVersion = BrooklynVersion.get();
+        protected String nodeId;
+        protected URI uri;
+        protected ManagementNodeState status;
+        protected Long priority;
+        protected long localTimestamp;
+        protected Long remoteTimestamp;
+
+        protected Builder self() {
+            return (Builder) this;
+        }
+        public Builder brooklynVersion(String val) {
+            brooklynVersion = val; return self();
+        }
+        public Builder nodeId(String val) {
+            nodeId = val; return self();
+        }
+        public Builder uri(URI val) {
+            uri = val; return self();
+        }
+        public Builder status(ManagementNodeState val) {
+            status = val; return self();
+        }
+        public Builder priority(Long val) {
+            priority = val; return self();
+        }
+        public Builder localTimestamp(long val) {
+            localTimestamp = val; return self();
+        }
+        public Builder remoteTimestamp(Long val) {
+            remoteTimestamp = val; return self();
+        }
+        public Builder from(ManagementNodeSyncRecord other) {
+            return from(other, false);
+        }
+        public Builder from(ManagementNodeSyncRecord other, boolean ignoreNulls) {
+            if (ignoreNulls && other==null) return this;
+            if (other.getBrooklynVersion()!=null) brooklynVersion = other.getBrooklynVersion();
+            if (other.getNodeId()!=null) nodeId = other.getNodeId();
+            if (other.getUri()!=null) uri = other.getUri();
+            if (other.getStatus()!=null) status = other.getStatus();
+            if (other.getPriority()!=null) priority = other.getPriority();
+            if (other.getLocalTimestamp()>0) localTimestamp = other.getLocalTimestamp();
+            if (other.getRemoteTimestamp()!=null) remoteTimestamp = other.getRemoteTimestamp();
+            return this;
+        }
+        public ManagementNodeSyncRecord build() {
+            return new BasicManagementNodeSyncRecord(this);
+        }
+    }
+    
+    private String brooklynVersion;
+    private String nodeId;
+    private URI uri;
+    private ManagementNodeState status;
+    private Long priority;
+    private Long localTimestamp;
+    private Long remoteTimestamp;
+    
+    /** @deprecated since 0.7.0, use {@link #localTimestamp} or {@link #remoteTimestamp},
+     * but kept (or rather added back in) to support deserializing previous instances */
+    @Deprecated
+    private Long timestampUtc;
+
+
+    // for de-serialization
+    @SuppressWarnings("unused")
+    private BasicManagementNodeSyncRecord() {
+    }
+
+    // Trusts the builder to not mess around with mutability concurrently with build().
+    protected BasicManagementNodeSyncRecord(Builder builder) {
+        brooklynVersion = builder.brooklynVersion;
+        nodeId = builder.nodeId;
+        uri = builder.uri;
+        status = builder.status;
+        priority = builder.priority;
+        localTimestamp = builder.localTimestamp;
+        remoteTimestamp = builder.remoteTimestamp;
+    }
+
+    @Override
+    public String getBrooklynVersion() {
+        return brooklynVersion;
+    }
+    
+    @Override
+    public String getNodeId() {
+        return nodeId;
+    }
+    
+    @Override
+    public URI getUri() {
+        return uri;
+    }
+    
+    @Override
+    public ManagementNodeState getStatus() {
+        return status;
+    }
+    
+    @Override
+    public Long getPriority() {
+        return priority;
+    }
+    
+    @Override
+    public long getLocalTimestamp() {
+        if (localTimestamp!=null) return localTimestamp;
+        if (timestampUtc!=null) return timestampUtc;
+        throw new NullPointerException("localTimestamp not known for "+getNodeId());
+    }
+    
+    @Override
+    public Long getRemoteTimestamp() {
+        return remoteTimestamp;
+    }
+    
+    @Override
+    public String toString() {
+        return Objects.toStringHelper(this)
+                .add("nodeId", getNodeId())
+                .add("status", getStatus()).toString();
+    }
+    
+    @Override
+    public String toVerboseString() {
+        return Objects.toStringHelper(this)
+                .omitNullValues()
+                .add("brooklynVersion", getBrooklynVersion())
+                .add("nodeId", getNodeId())
+                .add("uri", getUri())
+                .add("status", getStatus())
+                .add("priority", getPriority())
+                .add("localTimestamp", getLocalTimestamp()+"="+Time.makeDateString(getLocalTimestamp()))
+                .add("remoteTimestamp", getRemoteTimestamp()+(getRemoteTimestamp()==null ? "" : 
+                    "="+Time.makeDateString(getRemoteTimestamp())))
+                .toString();
+    }
+
+    /** used here for store to inject remote timestamp */
+    public void setRemoteTimestamp(Long remoteTimestamp) {
+        this.remoteTimestamp = remoteTimestamp;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/dto/ManagementPlaneSyncRecordImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/dto/ManagementPlaneSyncRecordImpl.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/dto/ManagementPlaneSyncRecordImpl.java
new file mode 100644
index 0000000..dd89320
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/dto/ManagementPlaneSyncRecordImpl.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.ha.dto;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static com.google.common.base.Preconditions.checkState;
+
+import java.io.Serializable;
+import java.util.Map;
+
+import org.apache.brooklyn.api.mgmt.ha.ManagementNodeSyncRecord;
+import org.apache.brooklyn.api.mgmt.ha.ManagementPlaneSyncRecord;
+import org.apache.brooklyn.util.collections.MutableMap;
+
+import com.google.common.base.Objects;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Maps;
+
+public class ManagementPlaneSyncRecordImpl implements ManagementPlaneSyncRecord, Serializable {
+
+    private static final long serialVersionUID = -4207907303446336973L;
+
+    public static Builder builder() {
+        return new Builder();
+    }
+    
+    public static class Builder {
+        protected String masterNodeId;
+        protected final Map<String,ManagementNodeSyncRecord> nodes = MutableMap.of();
+        
+        public Builder masterNodeId(String val) {
+            masterNodeId = val; return this;
+        }
+        public Builder nodes(Iterable<ManagementNodeSyncRecord> vals) {
+            checkState(!Iterables.contains(checkNotNull(vals, "nodes must not be null"), null),  "nodes must not contain null: %s", vals);
+            for (ManagementNodeSyncRecord val: vals) nodes.put(val.getNodeId(), val);
+            return this;
+        }
+        public Builder node(ManagementNodeSyncRecord val) {
+            checkNotNull(val, "node must not be null"); 
+            nodes.put(val.getNodeId(), val);
+            return this;
+        }
+        public ManagementPlaneSyncRecord build() {
+            return new ManagementPlaneSyncRecordImpl(this);
+        }
+    }
+
+    private String masterNodeId;
+    private Map<String, ManagementNodeSyncRecord> managementNodes;
+    
+    private ManagementPlaneSyncRecordImpl(Builder builder) {
+        masterNodeId = builder.masterNodeId;
+        managementNodes = Maps.newLinkedHashMap();
+        for (ManagementNodeSyncRecord node : builder.nodes.values()) {
+            checkState(!managementNodes.containsKey(node.getNodeId()), "duplicate nodeId %s", node.getNodeId());
+            managementNodes.put(node.getNodeId(), node);
+        }
+    }
+
+    @Override
+    public String getMasterNodeId() {
+        return masterNodeId;
+    }
+    
+    @Override
+    public Map<String, ManagementNodeSyncRecord> getManagementNodes() {
+        return managementNodes;
+    }
+
+    @Override
+    public String toString() {
+        return Objects.toStringHelper(this)
+                .add("masterNodeId", masterNodeId)
+                .add("nodes", managementNodes.keySet())
+                .toString();
+    }
+
+    @Override
+    public String toVerboseString() {
+        return toString();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/AbstractManagementContext.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/AbstractManagementContext.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/AbstractManagementContext.java
index b5a5163..18e1540 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/AbstractManagementContext.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/AbstractManagementContext.java
@@ -69,7 +69,7 @@ import org.apache.brooklyn.entity.core.AbstractEntity;
 import org.apache.brooklyn.entity.core.EntityInternal;
 import org.apache.brooklyn.entity.drivers.BasicEntityDriverManager;
 import org.apache.brooklyn.entity.drivers.downloads.BasicDownloadsManager;
-import org.apache.brooklyn.location.basic.BasicLocationRegistry;
+import org.apache.brooklyn.location.core.BasicLocationRegistry;
 import org.apache.brooklyn.util.GroovyJavaMethods;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/LocalLocationManager.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/LocalLocationManager.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/LocalLocationManager.java
index 303f387..132ac8f 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/LocalLocationManager.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/LocalLocationManager.java
@@ -39,8 +39,8 @@ import org.apache.brooklyn.core.objs.proxy.InternalLocationFactory;
 import org.apache.brooklyn.entity.lifecycle.Lifecycle;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.AbstractLocation;
-import org.apache.brooklyn.location.basic.LocationInternal;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 import org.apache.brooklyn.util.core.task.Tasks;
 import org.apache.brooklyn.util.exceptions.Exceptions;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/LocalUsageManager.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/LocalUsageManager.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/LocalUsageManager.java
index dd32548..e236546 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/LocalUsageManager.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/LocalUsageManager.java
@@ -45,9 +45,9 @@ import org.apache.brooklyn.entity.core.EntityInternal;
 import org.apache.brooklyn.entity.lifecycle.Lifecycle;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.AbstractLocation;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
-import org.apache.brooklyn.location.basic.LocationInternal;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 import org.apache.brooklyn.util.core.flags.TypeCoercions;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.apache.brooklyn.util.javalang.Reflections;


[48/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/TestPortSupplierLocation.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/TestPortSupplierLocation.java b/core/src/test/java/org/apache/brooklyn/location/basic/TestPortSupplierLocation.java
deleted file mode 100644
index e7b6963..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/TestPortSupplierLocation.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
-import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-
-public class TestPortSupplierLocation extends BrooklynAppUnitTestSupport {
-
-    SimulatedLocation loc;
-    PortAttributeSensorAndConfigKey ps;
-    TestEntity entity;
-    
-    @BeforeMethod(alwaysRun=true)
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-        loc = app.newSimulatedLocation();
-        entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
-        app.start(ImmutableList.of(loc));
-        
-        ps = new PortAttributeSensorAndConfigKey("some.port", "for testing", "1234+");
-    }
-
-    @Test
-    public void testObtainsPort() throws Exception {
-        ConfigToAttributes.apply(entity, ps);
-        
-        int p = entity.getAttribute(ps);
-        assertEquals(p, 1234);
-        
-        //sensor access should keep the same value
-        p = entity.getAttribute(ps);
-        assertEquals(p, 1234);
-    }
-    
-    @Test
-    public void testRepeatedConvertAccessIncrements() throws Exception {
-        int p = ps.getAsSensorValue(entity);
-        assertEquals(p, 1234);
-
-        //but direct access should see it as being reserved (not required behaviour, but it is the current behaviour)
-        int p2 = ps.getAsSensorValue(entity);
-        assertEquals(p2, 1235);
-    }
-
-    @Test
-    public void testNullBeforeSetting() throws Exception {
-        // currently getting the attribute before explicitly setting return null; i.e. no "auto-set" -- 
-        // but this behaviour may be changed
-        Integer p = entity.getAttribute(ps);
-        assertEquals(p, null);
-    }
-
-    @Test
-    public void testSimulatedRestrictedPermitted() throws Exception {
-        loc.setPermittedPorts(PortRanges.fromString("1240+"));
-        
-        ConfigToAttributes.apply(entity, ps);
-        int p = entity.getAttribute(ps);
-        assertEquals((int)p, 1240);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/byon/ByonLocationResolverTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/byon/ByonLocationResolverTest.java b/core/src/test/java/org/apache/brooklyn/location/byon/ByonLocationResolverTest.java
new file mode 100644
index 0000000..8d89a40
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/byon/ByonLocationResolverTest.java
@@ -0,0 +1,429 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.byon;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
+import java.net.InetAddress;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Set;
+
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.core.BasicLocationRegistry;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.apache.brooklyn.location.core.NamedLocationResolver;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.location.winrm.WinRmMachineLocation;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.net.Networking;
+import org.apache.brooklyn.util.net.UserAndHostAndPort;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.text.StringPredicates;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
+import com.google.common.base.Predicate;
+import com.google.common.base.Predicates;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+
+public class ByonLocationResolverTest {
+
+    private static final Logger log = LoggerFactory.getLogger(ByonLocationResolverTest.class);
+    
+    private BrooklynProperties brooklynProperties;
+    private LocalManagementContext managementContext;
+    private Predicate<CharSequence> defaultNamePredicate;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        managementContext = LocalManagementContextForTests.newInstance();
+        brooklynProperties = managementContext.getBrooklynProperties();
+        defaultNamePredicate = StringPredicates.startsWith(FixedListMachineProvisioningLocation.class.getSimpleName());
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (managementContext != null) Entities.destroyAll(managementContext);
+    }
+    
+    @Test
+    public void testTakesByonScopedProperties() {
+        brooklynProperties.put("brooklyn.location.byon.privateKeyFile", "myprivatekeyfile");
+        brooklynProperties.put("brooklyn.location.byon.publicKeyFile", "mypublickeyfile");
+        brooklynProperties.put("brooklyn.location.byon.privateKeyData", "myprivateKeyData");
+        brooklynProperties.put("brooklyn.location.byon.publicKeyData", "myPublicKeyData");
+        brooklynProperties.put("brooklyn.location.byon.privateKeyPassphrase", "myprivateKeyPassphrase");
+
+        Map<String, Object> conf = resolve("byon(hosts=\"1.1.1.1\")").config().getBag().getAllConfig();
+        
+        assertEquals(conf.get("privateKeyFile"), "myprivatekeyfile");
+        assertEquals(conf.get("publicKeyFile"), "mypublickeyfile");
+        assertEquals(conf.get("privateKeyData"), "myprivateKeyData");
+        assertEquals(conf.get("publicKeyData"), "myPublicKeyData");
+        assertEquals(conf.get("privateKeyPassphrase"), "myprivateKeyPassphrase");
+    }
+
+    @Test
+    public void testNamedByonLocation() throws Exception {
+        brooklynProperties.put("brooklyn.location.named.mynamed", "byon(hosts=\"1.1.1.1\")");
+        
+        FixedListMachineProvisioningLocation<MachineLocation> loc = resolve("named:mynamed");
+        assertEquals(loc.obtain().getAddress(), InetAddress.getByName("1.1.1.1"));
+    }
+
+    @Test
+    public void testPropertiesInSpec() throws Exception {
+        FixedListMachineProvisioningLocation<MachineLocation> loc = resolve("byon(privateKeyFile=myprivatekeyfile,hosts=\"1.1.1.1\")");
+        SshMachineLocation machine = (SshMachineLocation)loc.obtain();
+        
+        assertEquals(machine.config().getBag().getStringKey("privateKeyFile"), "myprivatekeyfile");
+        assertEquals(machine.getAddress(), Networking.getInetAddressWithFixedName("1.1.1.1"));
+    }
+
+    @Test
+    public void testPropertyScopePrecedence() throws Exception {
+        brooklynProperties.put("brooklyn.location.named.mynamed", "byon(hosts=\"1.1.1.1\")");
+        
+        // prefer those in "named" over everything else
+        brooklynProperties.put("brooklyn.location.named.mynamed.privateKeyFile", "privateKeyFile-inNamed");
+        brooklynProperties.put("brooklyn.location.byon.privateKeyFile", "privateKeyFile-inProviderSpecific");
+        brooklynProperties.put("brooklyn.localhost.privateKeyFile", "privateKeyFile-inGeneric");
+
+        // prefer those in provider-specific over generic
+        brooklynProperties.put("brooklyn.location.byon.publicKeyFile", "publicKeyFile-inProviderSpecific");
+        brooklynProperties.put("brooklyn.location.publicKeyFile", "publicKeyFile-inGeneric");
+
+        // prefer location-generic if nothing else
+        brooklynProperties.put("brooklyn.location.privateKeyData", "privateKeyData-inGeneric");
+
+        Map<String, Object> conf = resolve("named:mynamed").config().getBag().getAllConfig();
+        
+        assertEquals(conf.get("privateKeyFile"), "privateKeyFile-inNamed");
+        assertEquals(conf.get("publicKeyFile"), "publicKeyFile-inProviderSpecific");
+        assertEquals(conf.get("privateKeyData"), "privateKeyData-inGeneric");
+    }
+
+    @Test
+    public void testThrowsOnInvalid() throws Exception {
+        assertThrowsNoSuchElement("wrongprefix:(hosts=\"1.1.1.1\")");
+        assertThrowsIllegalArgument("byon"); // no hosts
+        assertThrowsIllegalArgument("byon()"); // no hosts
+        assertThrowsIllegalArgument("byon(hosts=\"\")"); // empty hosts
+        assertThrowsIllegalArgument("byon(hosts=\"1.1.1.1\""); // no closing bracket
+        assertThrowsIllegalArgument("byon(hosts=\"1.1.1.1\", name)"); // no value for name
+        assertThrowsIllegalArgument("byon(hosts=\"1.1.1.1\", name=)"); // no value for name
+    }
+    
+    @Test(expectedExceptions={IllegalArgumentException.class})
+    public void testRegistryCommaResolutionInListNotAllowed() throws NoMachinesAvailableException {
+        // disallowed since 0.7.0
+        // fails because it interprets the entire string as a single byon spec, which does not parse
+        managementContext.getLocationRegistry().resolve(ImmutableList.of("byon(hosts=\"192.168.0.1\",user=bob),byon(hosts=\"192.168.0.2\",user=bob2)"));
+    }
+
+    @Test
+    public void testResolvesHosts() throws Exception {
+        assertByonClusterEquals(resolve("byon(hosts=\"1.1.1.1\")"), ImmutableSet.of("1.1.1.1"));
+        assertByonClusterEquals(resolve("byon(hosts=\"1.1.1.1\")"), ImmutableSet.of("1.1.1.1"));
+        assertByonClusterEquals(resolve("byon(hosts=\"1.1.1.1,1.1.1.2\")"), ImmutableSet.of("1.1.1.1","1.1.1.2"));
+        assertByonClusterEquals(resolve("byon(hosts=\"1.1.1.1, 1.1.1.2\")"), ImmutableSet.of("1.1.1.1","1.1.1.2"));
+    }
+
+    @Test
+    public void testWithOldStyleColon() throws Exception {
+        assertByonClusterEquals(resolve("byon:(hosts=\"1.1.1.1\")"), ImmutableSet.of("1.1.1.1"));
+        assertByonClusterEquals(resolve("byon:(hosts=\"1.1.1.1\", name=myname)"), ImmutableSet.of("1.1.1.1"), "myname");
+    }
+
+    @Test
+    public void testUsesDisplayName() throws Exception {
+        assertByonClusterEquals(resolve("byon(hosts=\"1.1.1.1\", name=myname)"), ImmutableSet.of("1.1.1.1"), "myname");
+        assertByonClusterEquals(resolve("byon(hosts=\"1.1.1.1\", name=\"myname\")"), ImmutableSet.of("1.1.1.1"), "myname");
+    }
+
+    @Test
+    public void testResolvesHostsGlobExpansion() throws Exception {
+        assertByonClusterEquals(resolve("byon(hosts=\"1.1.1.{1,2}\")"), ImmutableSet.of("1.1.1.1","1.1.1.2"));
+        assertByonClusterEquals(resolve("byon(hosts=\"1.1.{1.1,2.{1,2}}\")"), 
+                ImmutableSet.of("1.1.1.1","1.1.2.1","1.1.2.2"));
+        assertByonClusterEquals(resolve("byon(hosts=\"1.1.{1,2}.{1,2}\")"), 
+                ImmutableSet.of("1.1.1.1","1.1.1.2","1.1.2.1","1.1.2.2"));
+    }
+
+    @Test(groups="Integration")
+    public void testNiceError() throws Exception {
+        Asserts.assertFailsWith(new Runnable() {
+            @Override public void run() {
+                FixedListMachineProvisioningLocation<MachineLocation> x =
+                        resolve("byon(hosts=\"1.1.1.{1,2}}\")");
+                log.error("got "+x+" but should have failed (your DNS is giving an IP for hostname '1.1.1.1}' (with the extra '}')");
+            }
+        }, new Predicate<Throwable>() {
+            @Override
+            public boolean apply(@Nullable Throwable input) {
+                String s = input.toString();
+                // words
+                if (!s.contains("Invalid host")) return false;
+                // problematic entry
+                if (!s.contains("1.1.1.1}")) return false;
+                // original spec
+                if (!s.contains("1.1.1.{1,2}}")) return false;
+                return true;
+            }
+        });
+    }
+
+    @Test
+    public void testResolvesUsernameAtHost() throws Exception {
+        assertByonClusterWithUsersEquals(resolve("byon(hosts=\"myuser@1.1.1.1\")"), 
+                ImmutableSet.of(UserAndHostAndPort.fromParts("myuser", "1.1.1.1", 22)));
+        assertByonClusterWithUsersEquals(resolve("byon(hosts=\"myuser@1.1.1.1,myuser2@1.1.1.1\")"), ImmutableSet.of(
+                UserAndHostAndPort.fromParts("myuser", "1.1.1.1", 22), UserAndHostAndPort.fromParts("myuser2", "1.1.1.1", 22)));
+        assertByonClusterWithUsersEquals(resolve("byon(hosts=\"myuser@1.1.1.1,myuser2@1.1.1.2\")"), ImmutableSet.of(
+                UserAndHostAndPort.fromParts("myuser", "1.1.1.1", 22), UserAndHostAndPort.fromParts("myuser2", "1.1.1.2", 22)));
+    }
+
+    @Test
+    public void testResolvesUserArg() throws Exception {
+        assertByonClusterWithUsersEquals(resolve("byon(hosts=\"1.1.1.1\",user=bob)"), 
+                ImmutableSet.of(UserAndHostAndPort.fromParts("bob", "1.1.1.1", 22)));
+        assertByonClusterWithUsersEquals(resolve("byon(user=\"bob\",hosts=\"myuser@1.1.1.1,1.1.1.1\")"), 
+                ImmutableSet.of(UserAndHostAndPort.fromParts("myuser", "1.1.1.1", 22), UserAndHostAndPort.fromParts("bob", "1.1.1.1", 22)));
+    }
+
+    @Test
+    public void testResolvesUserArg2() throws Exception {
+        String spec = "byon(hosts=\"1.1.1.1\",user=bob)";
+        FixedListMachineProvisioningLocation<MachineLocation> ll = resolve(spec);
+        SshMachineLocation l = (SshMachineLocation)ll.obtain();
+        Assert.assertEquals("bob", l.getUser());
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testResolvesUserArg3() throws Exception {
+        String spec = "byon(hosts=\"1.1.1.1\")";
+        managementContext.getLocationRegistry().getProperties().putAll(MutableMap.of(
+                "brooklyn.location.named.foo", spec,
+                "brooklyn.location.named.foo.user", "bob"));
+        ((BasicLocationRegistry)managementContext.getLocationRegistry()).updateDefinedLocations();
+        
+        MachineProvisioningLocation<SshMachineLocation> ll = (MachineProvisioningLocation<SshMachineLocation>)
+                new NamedLocationResolver().newLocationFromString(MutableMap.of(), "named:foo", managementContext.getLocationRegistry());
+        SshMachineLocation l = ll.obtain(MutableMap.of());
+        Assert.assertEquals("bob", l.getUser());
+    }
+
+    @Test
+    public void testResolvesPortArg() throws Exception {
+        assertByonClusterWithUsersEquals(resolve("byon(user=bob,port=8022,hosts=\"1.1.1.1\")"), 
+                ImmutableSet.of(UserAndHostAndPort.fromParts("bob", "1.1.1.1", 8022)));
+        assertByonClusterWithUsersEquals(resolve("byon(user=bob,port=8022,hosts=\"myuser@1.1.1.1,1.1.1.2:8901\")"), 
+                ImmutableSet.of(UserAndHostAndPort.fromParts("myuser", "1.1.1.1", 8022), UserAndHostAndPort.fromParts("bob", "1.1.1.2", 8901)));
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    /** private key should be inherited, so confirm that happens correctly */
+    public void testResolvesPrivateKeyArgInheritance() throws Exception {
+        String spec = "byon(hosts=\"1.1.1.1\")";
+        managementContext.getLocationRegistry().getProperties().putAll(MutableMap.of(
+                "brooklyn.location.named.foo", spec,
+                "brooklyn.location.named.foo.user", "bob",
+                "brooklyn.location.named.foo.privateKeyFile", "/tmp/x"));
+        ((BasicLocationRegistry)managementContext.getLocationRegistry()).updateDefinedLocations();
+        
+        MachineProvisioningLocation<SshMachineLocation> ll = (MachineProvisioningLocation<SshMachineLocation>) 
+                new NamedLocationResolver().newLocationFromString(MutableMap.of(), "named:foo", managementContext.getLocationRegistry());
+        
+        Assert.assertEquals("/tmp/x", ll.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE));
+        Assert.assertTrue(((LocationInternal)ll).config().getLocalRaw(LocationConfigKeys.PRIVATE_KEY_FILE).isPresent());
+        Assert.assertEquals("/tmp/x", ((LocationInternal)ll).config().getLocalBag().getStringKey(LocationConfigKeys.PRIVATE_KEY_FILE.getName()));
+        Assert.assertEquals("/tmp/x", ((LocationInternal)ll).config().getBag().get(LocationConfigKeys.PRIVATE_KEY_FILE));
+
+        SshMachineLocation l = ll.obtain(MutableMap.of());
+        
+        Assert.assertEquals("/tmp/x", l.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE));
+        
+        Assert.assertTrue(l.config().getRaw(LocationConfigKeys.PRIVATE_KEY_FILE).isPresent());
+        Assert.assertTrue(l.config().getLocalRaw(LocationConfigKeys.PRIVATE_KEY_FILE).isAbsent());
+
+        Assert.assertEquals("/tmp/x", l.config().getBag().getStringKey(LocationConfigKeys.PRIVATE_KEY_FILE.getName()));
+        Assert.assertEquals("/tmp/x", l.config().getBag().getStringKey(LocationConfigKeys.PRIVATE_KEY_FILE.getName()));
+
+        Assert.assertEquals("/tmp/x", l.config().getBag().get(LocationConfigKeys.PRIVATE_KEY_FILE));
+    }
+
+    @Test
+    public void testResolvesLocalTempDir() throws Exception {
+        String localTempDir = Os.mergePaths(Os.tmp(), "testResolvesUsernameAtHost");
+        brooklynProperties.put("brooklyn.location.byon.localTempDir", localTempDir);
+
+        FixedListMachineProvisioningLocation<MachineLocation> byon = resolve("byon(hosts=\"1.1.1.1\",osFamily=\"windows\")");
+        MachineLocation machine = byon.obtain();
+        assertEquals(machine.getConfig(SshMachineLocation.LOCAL_TEMP_DIR), localTempDir);
+    }
+
+    @Test
+    public void testMachinesObtainedInOrder() throws Exception {
+        List<String> ips = ImmutableList.of("1.1.1.1", "1.1.1.6", "1.1.1.3", "1.1.1.4", "1.1.1.5");
+        String spec = "byon(hosts=\""+Joiner.on(",").join(ips)+"\")";
+        
+        MachineProvisioningLocation<MachineLocation> ll = resolve(spec);
+
+        for (String expected : ips) {
+            MachineLocation obtained = ll.obtain(ImmutableMap.of());
+            assertEquals(obtained.getAddress().getHostAddress(), expected);
+        }
+    }
+    
+    @Test
+    public void testEmptySpec() throws Exception {
+        String spec = "byon";
+        Map<String, ?> flags = ImmutableMap.of(
+                "hosts", ImmutableList.of("1.1.1.1", "2.2.2.22"),
+                "name", "foo",
+                "user", "myuser"
+        );
+        MachineProvisioningLocation<MachineLocation> provisioner = resolve(spec, flags);
+        SshMachineLocation location1 = (SshMachineLocation)provisioner.obtain(ImmutableMap.of());
+        Assert.assertEquals("myuser", location1.getUser());
+        Assert.assertEquals("1.1.1.1", location1.getAddress().getHostAddress());
+    }
+
+    @Test
+    public void testWindowsMachines() throws Exception {
+        brooklynProperties.put("brooklyn.location.byon.user", "myuser");
+        brooklynProperties.put("brooklyn.location.byon.password", "mypassword");
+        String spec = "byon";
+        Map<String, ?> flags = ImmutableMap.of(
+                "hosts", ImmutableList.of("1.1.1.1", "2.2.2.2"),
+                "osfamily", "windows"
+        );
+        MachineProvisioningLocation<MachineLocation> provisioner = resolve(spec, flags);
+        WinRmMachineLocation location = (WinRmMachineLocation) provisioner.obtain(ImmutableMap.of());
+
+        assertEquals(location.config().get(WinRmMachineLocation.USER), "myuser");
+        assertEquals(location.config().get(WinRmMachineLocation.PASSWORD), "mypassword");
+        assertEquals(location.config().get(WinRmMachineLocation.ADDRESS).getHostAddress(), "1.1.1.1");
+    }
+
+    @Test
+    public void testNoneWindowsMachines() throws Exception {
+        String spec = "byon";
+        Map<String, ?> flags = ImmutableMap.of(
+                "hosts", ImmutableList.of("1.1.1.1", "2.2.2.2"),
+                "osfamily", "linux"
+        );
+        MachineProvisioningLocation<MachineLocation> provisioner = resolve(spec, flags);
+        MachineLocation location = provisioner.obtain(ImmutableMap.of());
+        assertTrue(location instanceof SshMachineLocation, "Expected location to be SshMachineLocation, found " + location);
+    }
+
+    @Test
+    public void testAdditionalConfig() throws Exception {
+        FixedListMachineProvisioningLocation<MachineLocation> loc = resolve("byon(mykey=myval,hosts=\"1.1.1.1\")");
+        MachineLocation machine = loc.obtain(ImmutableMap.of());
+        assertEquals(machine.getConfig(ConfigKeys.newConfigKey(String.class, "mykey")), "myval");
+    }
+
+    private void assertByonClusterEquals(FixedListMachineProvisioningLocation<? extends MachineLocation> cluster, Set<String> expectedHosts) {
+        assertByonClusterEquals(cluster, expectedHosts, defaultNamePredicate);
+    }
+    
+    private void assertByonClusterEquals(FixedListMachineProvisioningLocation<? extends MachineLocation> cluster, Set<String> expectedHosts, String expectedName) {
+        assertByonClusterEquals(cluster, expectedHosts, Predicates.equalTo(expectedName));
+    }
+    
+    private void assertByonClusterEquals(FixedListMachineProvisioningLocation<? extends MachineLocation> cluster, Set<String> expectedHosts, Predicate<? super String> expectedName) {
+        Set<String> actualHosts = ImmutableSet.copyOf(Iterables.transform(cluster.getMachines(), new Function<MachineLocation, String>() {
+            @Override public String apply(MachineLocation input) {
+                return input.getAddress().getHostName();
+            }}));
+        assertEquals(actualHosts, expectedHosts);
+        assertTrue(expectedName.apply(cluster.getDisplayName()), "name="+cluster.getDisplayName());
+    }
+
+    private void assertByonClusterWithUsersEquals(FixedListMachineProvisioningLocation<? extends MachineLocation> cluster, Set<UserAndHostAndPort> expectedHosts) {
+        assertByonClusterWithUsersEquals(cluster, expectedHosts, defaultNamePredicate);
+    }
+    
+    private void assertByonClusterWithUsersEquals(FixedListMachineProvisioningLocation<? extends MachineLocation> cluster, Set<UserAndHostAndPort> expectedHosts, Predicate<? super String> expectedName) {
+        Set<UserAndHostAndPort> actualHosts = ImmutableSet.copyOf(Iterables.transform(cluster.getMachines(), new Function<MachineLocation, UserAndHostAndPort>() {
+            @Override public UserAndHostAndPort apply(MachineLocation input) {
+                SshMachineLocation machine = (SshMachineLocation) input;
+                return UserAndHostAndPort.fromParts(machine.getUser(), machine.getAddress().getHostName(), machine.getPort());
+            }}));
+        assertEquals(actualHosts, expectedHosts);
+        assertTrue(expectedName.apply(cluster.getDisplayName()), "name="+cluster.getDisplayName());
+    }
+
+    private void assertThrowsNoSuchElement(String val) {
+        try {
+            resolve(val);
+            fail();
+        } catch (NoSuchElementException e) {
+            // success
+        }
+    }
+    
+    private void assertThrowsIllegalArgument(String val) {
+        try {
+            resolve(val);
+            fail();
+        } catch (IllegalArgumentException e) {
+            // success
+        }
+    }
+    
+    @SuppressWarnings("unchecked")
+    private FixedListMachineProvisioningLocation<MachineLocation> resolve(String val) {
+        return (FixedListMachineProvisioningLocation<MachineLocation>) managementContext.getLocationRegistry().resolve(val);
+    }
+    
+    @SuppressWarnings("unchecked")
+    private FixedListMachineProvisioningLocation<MachineLocation> resolve(String val, Map<?, ?> locationFlags) {
+        return (FixedListMachineProvisioningLocation<MachineLocation>) managementContext.getLocationRegistry().resolve(val, locationFlags);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/byon/FixedListMachineProvisioningLocationRebindTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/byon/FixedListMachineProvisioningLocationRebindTest.java b/core/src/test/java/org/apache/brooklyn/location/byon/FixedListMachineProvisioningLocationRebindTest.java
new file mode 100644
index 0000000..3068115
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/byon/FixedListMachineProvisioningLocationRebindTest.java
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.byon;
+
+import static org.testng.Assert.assertEquals;
+
+import java.io.File;
+import java.util.Set;
+
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.util.collections.MutableSet;
+import org.apache.brooklyn.util.os.Os;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Function;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+
+public class FixedListMachineProvisioningLocationRebindTest {
+
+    private FixedListMachineProvisioningLocation<SshMachineLocation> origLoc;
+    private ClassLoader classLoader = getClass().getClassLoader();
+    private ManagementContext origManagementContext;
+    private TestApplication origApp;
+    private TestApplication newApp;
+    private File mementoDir;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        mementoDir = Os.newTempDir(getClass());
+        origManagementContext = RebindTestUtils.newPersistingManagementContext(mementoDir, classLoader, 1);
+        
+        origLoc = new FixedListMachineProvisioningLocation.Builder(origManagementContext.getLocationManager())
+                .addAddresses("localhost", "127.0.0.1")
+                .user("myuser")
+                .keyFile("/path/to/myPrivateKeyFile")
+                .keyData("myKeyData")
+                .keyPassphrase("myKeyPassphrase")
+                .build();
+        origApp = ApplicationBuilder.newManagedApp(TestApplication.class, origManagementContext);
+        origApp.start(ImmutableList.of(origLoc));
+    }
+
+    @AfterMethod(alwaysRun = true)
+    public void tearDown() throws Exception {
+        if (origManagementContext != null) Entities.destroyAll(origManagementContext);
+        if (newApp != null) Entities.destroyAll(newApp.getManagementContext());
+        if (mementoDir != null) RebindTestUtils.deleteMementoDir(mementoDir);
+    }
+    
+    @Test
+    public void testRebindPreservesConfig() throws Exception {
+        newApp = rebind();
+        FixedListMachineProvisioningLocation<SshMachineLocation> newLoc = (FixedListMachineProvisioningLocation<SshMachineLocation>) Iterables.get(newApp.getLocations(), 0);
+        
+        assertEquals(newLoc.getId(), origLoc.getId());
+        assertEquals(newLoc.getDisplayName(), origLoc.getDisplayName());
+        assertEquals(newLoc.getHostGeoInfo(), origLoc.getHostGeoInfo());
+        assertEquals(newLoc.getConfig(LocationConfigKeys.USER), origLoc.getConfig(LocationConfigKeys.USER));
+        assertEquals(newLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_PASSPHRASE), origLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_PASSPHRASE));
+        assertEquals(newLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE), origLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE));
+        assertEquals(newLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_DATA), origLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_DATA));
+    }
+
+    @Test
+    public void testRebindParentRelationship() throws Exception {
+        newApp = rebind();
+        FixedListMachineProvisioningLocation<SshMachineLocation> newLoc = (FixedListMachineProvisioningLocation<SshMachineLocation>) Iterables.get(newApp.getLocations(), 0);
+        
+        assertLocationIdsEqual(newLoc.getChildren(), origLoc.getChildren());
+        assertEquals(Iterables.get(newLoc.getChildren(), 0).getParent(), newLoc);
+        assertEquals(Iterables.get(newLoc.getChildren(), 1).getParent(), newLoc);
+    }
+
+    @Test
+    public void testRebindPreservesInUseMachines() throws Exception {
+        SshMachineLocation inuseMachine = origLoc.obtain();
+        origApp.setAttribute(TestApplication.SERVICE_UP, true); // to force persist, and thus avoid race
+        
+        newApp = rebind();
+        FixedListMachineProvisioningLocation<SshMachineLocation> newLoc = (FixedListMachineProvisioningLocation<SshMachineLocation>) Iterables.get(newApp.getLocations(), 0);
+        
+        assertLocationIdsEqual(newLoc.getInUse(), origLoc.getInUse());
+        assertLocationIdsEqual(newLoc.getAvailable(), origLoc.getAvailable());
+    }
+
+    private TestApplication rebind() throws Exception {
+        RebindTestUtils.waitForPersisted(origApp);
+        return (TestApplication) RebindTestUtils.rebind(mementoDir, getClass().getClassLoader());
+    }
+    
+    private void assertLocationIdsEqual(Iterable<? extends Location> actual, Iterable<? extends Location> expected) {
+        Function<Location, String> locationIdFunction = new Function<Location, String>() {
+            @Override public String apply(@Nullable Location input) {
+                return (input != null) ? input.getId() : null;
+            }
+        };
+        Set<String> actualIds = MutableSet.copyOf(Iterables.transform(actual, locationIdFunction));
+        Set<String> expectedIds = MutableSet.copyOf(Iterables.transform(expected, locationIdFunction));
+        
+        assertEquals(actualIds, expectedIds);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/byon/FixedListMachineProvisioningLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/byon/FixedListMachineProvisioningLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/byon/FixedListMachineProvisioningLocationTest.java
new file mode 100644
index 0000000..f36ab1e
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/byon/FixedListMachineProvisioningLocationTest.java
@@ -0,0 +1,578 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.byon;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.fail;
+
+import java.net.Inet4Address;
+import java.net.UnknownHostException;
+import java.util.List;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.core.RecordingMachineLocationCustomizer;
+import org.apache.brooklyn.location.core.RecordingMachineLocationCustomizer.Call;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.net.Networking;
+import org.apache.brooklyn.util.stream.Streams;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Function;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+
+/**
+ * Provisions {@link SshMachineLocation}s in a specific location from a list of known machines
+ */
+public class FixedListMachineProvisioningLocationTest {
+    
+    private static final Logger LOG = LoggerFactory.getLogger(FixedListMachineProvisioningLocationTest.class);
+
+    SshMachineLocation machine;
+    LocalManagementContext mgmt;
+    FixedListMachineProvisioningLocation<SshMachineLocation> provisioner;
+    FixedListMachineProvisioningLocation<SshMachineLocation> provisioner2;
+    
+    @SuppressWarnings("unchecked")
+    @BeforeMethod(alwaysRun=true)
+    public void createProvisioner() throws UnknownHostException {
+        mgmt = LocalManagementContextForTests.newInstance();
+        
+        machine = mgmt.getLocationManager().createLocation(MutableMap.of("address", Inet4Address.getByName("192.168.144.200")), SshMachineLocation.class);
+        provisioner = mgmt.getLocationManager().createLocation(
+                MutableMap.of("machines", MutableList.of(machine)),
+                FixedListMachineProvisioningLocation.class);
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (provisioner != null) Streams.closeQuietly(provisioner);
+        if (provisioner2 != null) Streams.closeQuietly(provisioner2);
+        Entities.destroyAll(mgmt);
+    }
+    
+    @Test
+    public void testSetsChildLocations() throws NoMachinesAvailableException {
+        // Available machines should be listed as children
+        assertEquals(ImmutableList.copyOf(provisioner.getChildren()), ImmutableList.of(machine));
+        
+        // In-use machines should also be listed as children
+        provisioner.obtain();
+        assertEquals(ImmutableList.copyOf(provisioner.getChildren()), ImmutableList.of(machine));
+    }
+
+    @Test
+    public void canObtainMachine() throws NoMachinesAvailableException {
+        SshMachineLocation obtained = provisioner.obtain();
+        assertEquals(obtained, machine);
+    }
+
+    @SuppressWarnings("unused")
+    @Test(expectedExceptions = { NoMachinesAvailableException.class })
+    public void throwsExceptionIfNoMachinesAvailable() throws NoMachinesAvailableException {
+        SshMachineLocation machine1 = provisioner.obtain();
+        SshMachineLocation machine2 = provisioner.obtain();
+        fail("Did not throw NoMachinesAvailableException as expected");
+    }
+
+    @Test
+    public void canGetAMachineReturnItAndObtainItAgain() throws NoMachinesAvailableException {
+        SshMachineLocation obtained = provisioner.obtain();
+        provisioner.release(obtained);
+        SshMachineLocation obtained2 = provisioner.obtain();
+        assertEquals(obtained2, machine);
+    }
+
+    @Test
+    public void theBuilder() throws NoMachinesAvailableException {
+        provisioner2 =
+            new FixedListMachineProvisioningLocation.Builder(mgmt.getLocationManager()).
+                user("u1").
+                addAddress("192.168.0.1").
+                addAddress("u2@192.168.0.2").
+                addAddress("192.168.0.{3,4}").
+                addAddresses("192.168.0.{6-8}").
+                addAddressMultipleTimes("192.168.0.{8,7}", 2).
+                addAddress("u3@192.168.0.{11-20}").
+                build();
+        assertUserAndHost(provisioner2.obtain(), "u1", "192.168.0.1");
+        assertUserAndHost(provisioner2.obtain(), "u2", "192.168.0.2");
+        for (int i=3; i<=4; i++) assertUserAndHost(provisioner2.obtain(), "u1", "192.168.0."+i);
+        for (int i=6; i<=8; i++) assertUserAndHost(provisioner2.obtain(), "u1", "192.168.0."+i);
+        for (int j=0; j<2; j++)
+            for (int i=8; i>=7; i--) assertUserAndHost(provisioner2.obtain(), "u1", "192.168.0."+i);
+        for (int i=11; i<=20; i++) assertUserAndHost(provisioner2.obtain(), "u3", "192.168.0."+i);
+        try { 
+            provisioner2.obtain();
+            fail("Should not have obtained");  //throws error so not caught below
+        } catch (Exception e) {
+            /** expected */
+        }
+    }
+    
+    @Test
+    public void theBuilderLegacy() throws NoMachinesAvailableException {
+        provisioner2 =
+            new FixedListMachineProvisioningLocation.Builder(mgmt.getLocationManager()).
+                user("u1").
+                addAddress("192.168.0.1").
+                addAddress("u2@192.168.0.2").
+                addAddress("192.168.0.{3,4}").
+                addAddresses("192.168.0.{6-8}").
+                addAddressMultipleTimes("192.168.0.{8,7}", 2).
+                addAddress("u3@192.168.0.{11-20}").
+                build();
+        assertUserAndHost(provisioner2.obtain(), "u1", "192.168.0.1");
+        assertUserAndHost(provisioner2.obtain(), "u2", "192.168.0.2");
+        for (int i=3; i<=4; i++) assertUserAndHost(provisioner2.obtain(), "u1", "192.168.0."+i);
+        for (int i=6; i<=8; i++) assertUserAndHost(provisioner2.obtain(), "u1", "192.168.0."+i);
+        for (int j=0; j<2; j++)
+            for (int i=8; i>=7; i--) assertUserAndHost(provisioner2.obtain(), "u1", "192.168.0."+i);
+        for (int i=11; i<=20; i++) assertUserAndHost(provisioner2.obtain(), "u3", "192.168.0."+i);
+        try { 
+            provisioner2.obtain();
+            fail("Should not have obtained");  //throws error so not caught below
+        } catch (Exception e) {
+            /** expected */
+        }
+    }
+    
+    @Test(expectedExceptions = { IllegalStateException.class })
+    public void throwsExceptionIfTryingToReleaseUnallocationMachine() throws NoMachinesAvailableException, UnknownHostException {
+        @SuppressWarnings("unused")
+        SshMachineLocation obtained = provisioner.obtain();
+        provisioner.release(new SshMachineLocation(MutableMap.of("address", Inet4Address.getByName("192.168.144.201"))));
+        fail("Did not throw IllegalStateException as expected");
+    }
+    
+    @Test
+    public void testCanAddMachineToPool() throws UnknownHostException, NoMachinesAvailableException {
+        SshMachineLocation machine2 = new SshMachineLocation(
+                MutableMap.of("address", Inet4Address.getByName("192.168.144.200")));
+        provisioner2 = new FixedListMachineProvisioningLocation<SshMachineLocation>(
+                MutableMap.of("machines", MutableList.of()));
+        provisioner2.addMachine(machine2);
+        
+        assertEquals(ImmutableList.copyOf(provisioner2.getChildren()), ImmutableList.of(machine2));
+        assertEquals(ImmutableSet.copyOf(provisioner2.getAvailable()), ImmutableSet.of(machine2));
+        
+        SshMachineLocation obtained = provisioner2.obtain();
+        assertEquals(obtained, machine2);
+        
+        // Can only obtain the added machien once though (i.e. not added multiple times somehow)
+        try {
+            SshMachineLocation obtained2 = provisioner2.obtain();
+            fail("obtained="+obtained2);
+        } catch (NoMachinesAvailableException e) {
+            // success
+        }
+    }
+
+    @Test
+    public void testCanRemoveAvailableMachineFromPool() {
+        provisioner.removeMachine(machine);
+        
+        Assert.assertTrue(provisioner.getChildren().isEmpty());
+        Assert.assertTrue(provisioner.getAvailable().isEmpty());
+        
+        try {
+            SshMachineLocation obtained = provisioner.obtain();
+            fail("obtained="+obtained);
+        } catch (NoMachinesAvailableException e) {
+            // success
+        }
+    }
+
+    @Test
+    public void testCanRemoveObtainedMachineFromPoolSoNotReallocated() throws NoMachinesAvailableException {
+        SshMachineLocation obtained = provisioner.obtain();
+        provisioner.removeMachine(obtained);
+        
+        // Continue to know about the machine until it is returned
+        assertEquals(ImmutableList.copyOf(provisioner.getChildren()), ImmutableList.of(machine));
+        Assert.assertTrue(provisioner.getAvailable().isEmpty());
+
+        // When released, the machine is then removed entirely
+        provisioner.release(obtained);
+
+        Assert.assertTrue(provisioner.getChildren().isEmpty());
+        Assert.assertTrue(provisioner.getAvailable().isEmpty());
+
+        // So no machines left; cannot re-obtain
+        try {
+            SshMachineLocation obtained2 = provisioner.obtain();
+            fail("obtained="+obtained2);
+        } catch (NoMachinesAvailableException e) {
+            // success
+        }
+    }
+
+    @Test
+    public void testObtainDesiredMachineThrowsIfNotKnown() throws Exception {
+        SshMachineLocation machine2 = new SshMachineLocation(
+                MutableMap.of("address", Inet4Address.getByName("192.168.144.201")));
+        try {
+            SshMachineLocation obtained = provisioner.obtain(MutableMap.of("desiredMachine", machine2));
+            fail("obtained="+obtained);
+        } catch (IllegalStateException e) {
+            if (!e.toString().contains("machine unknown")) throw e;
+        }
+    }
+
+    @Test
+    public void testObtainDesiredMachineThrowsIfInUse() throws Exception {
+        provisioner.addMachine(new SshMachineLocation(
+                MutableMap.of("address", Inet4Address.getByName("192.168.144.201"))));
+        SshMachineLocation obtained = provisioner.obtain();
+        try {
+            SshMachineLocation obtained2 = provisioner.obtain(MutableMap.of("desiredMachine", obtained));
+            fail("obtained2="+obtained2);
+        } catch (IllegalStateException e) {
+            if (!e.toString().contains("machine in use")) throw e;
+        }
+    }
+
+    @Test
+    public void testObtainDesiredMachineReturnsDesired() throws Exception {
+        int desiredMachineIndex = 10;
+        SshMachineLocation desiredMachine = null;
+        for (int i = 0; i < 20; i++) {
+            SshMachineLocation newMachine = new SshMachineLocation(
+                    MutableMap.of("address", Inet4Address.getByName("192.168.144."+(201+i))));
+            if (i == desiredMachineIndex) desiredMachine = newMachine;
+            provisioner.addMachine(newMachine);
+        }
+        SshMachineLocation obtained = provisioner.obtain(MutableMap.of("desiredMachine", desiredMachine));
+        assertEquals(obtained, desiredMachine);
+    }
+
+    @Test
+    public void testAddAndRemoveChildUpdatesMachinesSet() throws Exception {
+        SshMachineLocation anotherMachine = new SshMachineLocation(
+                MutableMap.of("address", Inet4Address.getByName("192.168.144.201")));
+        provisioner.addChild(anotherMachine);
+        assertEquals(provisioner.getAllMachines(), ImmutableSet.of(machine, anotherMachine));
+        
+        provisioner.removeChild(anotherMachine);
+        assertEquals(provisioner.getAllMachines(), ImmutableSet.of(machine));
+    }
+    
+    @Test
+    public void testCanAddAlreadyParentedMachine() throws UnknownHostException, NoMachinesAvailableException {
+        provisioner.obtain(); // so no machines left
+        
+        FixedListMachineProvisioningLocation<SshMachineLocation> provisioner2 = new FixedListMachineProvisioningLocation.Builder(mgmt.getLocationManager())
+            .addAddress("1.2.3.4")
+            .build();
+        SshMachineLocation machine = provisioner2.obtain();
+        
+        provisioner.addMachine(machine);
+        assertEquals(provisioner.obtain(), machine);
+    }
+
+    @Test
+    public void testCanCreateWithAlreadyParentedMachine() throws UnknownHostException, NoMachinesAvailableException {
+        machine = provisioner.obtain();
+        
+        FixedListMachineProvisioningLocation<SshMachineLocation> provisioner2 = new FixedListMachineProvisioningLocation.Builder(mgmt.getLocationManager())
+            .add(machine)
+            .build();
+        assertEquals(provisioner2.obtain(), machine);
+    }
+
+    @Test
+    @SuppressWarnings("unchecked")
+    public void testMachinesObtainedInOrder() throws Exception {
+        List<SshMachineLocation> machines = ImmutableList.of(
+                mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.1"))),
+                mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.6"))),
+                mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.3"))),
+                mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.4"))),
+                mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.5"))));
+        
+        provisioner2 = mgmt.getLocationManager().createLocation(
+                MutableMap.of("machines", machines),
+                FixedListMachineProvisioningLocation.class);
+
+        for (SshMachineLocation expected : machines) {
+            assertEquals(provisioner2.obtain(), expected);
+        }
+    }
+    
+    @Test
+    @SuppressWarnings("unchecked")
+    public void testMachineChooser() throws Exception {
+        List<SshMachineLocation> machines = Lists.newArrayList();
+        for (int i = 0; i < 10; i++) {
+            machines.add(mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1."+i))));
+        }
+        final List<SshMachineLocation> desiredOrder = randomized(machines);
+        
+        Function<Iterable<? extends MachineLocation>, MachineLocation> chooser = new Function<Iterable<? extends MachineLocation>, MachineLocation>() {
+            @Override public MachineLocation apply(Iterable<? extends MachineLocation> input) {
+                for (SshMachineLocation contender : desiredOrder) {
+                    if (Iterables.contains(input, contender)) {
+                        return contender;
+                    }
+                }
+                Assert.fail("No intersection of input="+input+" and desiredOrder="+desiredOrder);
+                return null; // unreachable code
+            }
+        };
+        provisioner2 = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
+                .configure("machines", machines)
+                .configure(FixedListMachineProvisioningLocation.MACHINE_CHOOSER, chooser));
+
+        List<SshMachineLocation> result = Lists.newArrayList();
+        for (int i = 0; i < machines.size(); i++) {
+            result.add(provisioner2.obtain());
+        }
+        assertEquals(result, desiredOrder, "result="+result+"; desired="+desiredOrder);
+        LOG.debug("chooser's desiredOrder="+desiredOrder);
+    }
+    
+    @Test
+    @SuppressWarnings("unchecked")
+    public void testMachineChooserPassedToObtain() throws Exception {
+        List<SshMachineLocation> machines = Lists.newArrayList();
+        for (int i = 0; i < 10; i++) {
+            machines.add(mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1."+i))));
+        }
+        final List<SshMachineLocation> desiredOrder = randomized(machines);
+        
+        Function<Iterable<? extends MachineLocation>, MachineLocation> chooser = new Function<Iterable<? extends MachineLocation>, MachineLocation>() {
+            @Override public MachineLocation apply(Iterable<? extends MachineLocation> input) {
+                for (SshMachineLocation contender : desiredOrder) {
+                    if (Iterables.contains(input, contender)) {
+                        return contender;
+                    }
+                }
+                Assert.fail("No intersection of input="+input+" and desiredOrder="+desiredOrder);
+                return null; // unreachable code
+            }
+        };
+        provisioner2 = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
+                .configure("machines", machines));
+
+        List<SshMachineLocation> result = Lists.newArrayList();
+        for (int i = 0; i < machines.size(); i++) {
+            result.add(provisioner2.obtain(ImmutableMap.of(FixedListMachineProvisioningLocation.MACHINE_CHOOSER, chooser)));
+        }
+        assertEquals(result, desiredOrder, "result="+result+"; desired="+desiredOrder);
+        LOG.debug("chooser's desiredOrder="+desiredOrder);
+    }
+    
+    @Test
+    @SuppressWarnings("unchecked")
+    public void testMachineChooserNotCalledWhenNoMachines() throws Exception {
+        List<SshMachineLocation> machines = ImmutableList.of(
+                mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.1"))));
+        final AtomicInteger callCount = new AtomicInteger();
+        
+        Function<Iterable<? extends MachineLocation>, MachineLocation> chooser = new Function<Iterable<? extends MachineLocation>, MachineLocation>() {
+            @Override public MachineLocation apply(Iterable<? extends MachineLocation> input) {
+                callCount.incrementAndGet();
+                return Iterables.get(input, 0);
+            }
+        };
+        provisioner2 = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
+                .configure("machines", machines)
+                .configure(FixedListMachineProvisioningLocation.MACHINE_CHOOSER, chooser));
+        provisioner2.obtain();
+
+        // When no machines available should fail gracefully, without asking the "chooser"
+        try {
+            provisioner2.obtain();
+            fail("Expected "+NoMachinesAvailableException.class.getSimpleName());
+        } catch (NoMachinesAvailableException e) {
+            // Pass; sensible exception
+        }
+        assertEquals(callCount.get(), 1);
+    }
+    
+    @Test
+    @SuppressWarnings("unchecked")
+    public void testFailsWhenMachineChooserReturnsAlreadyAllocatedMachine() throws Exception {
+        final SshMachineLocation machine1 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.1")));
+        final SshMachineLocation machine2 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.2")));
+        List<SshMachineLocation> machines = ImmutableList.of(machine1, machine2);
+        
+        Function<Iterable<? extends MachineLocation>, MachineLocation> chooser = new Function<Iterable<? extends MachineLocation>, MachineLocation>() {
+            @Override public MachineLocation apply(Iterable<? extends MachineLocation> input) {
+                return machine1;
+            }
+        };
+        provisioner2 = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
+                .configure("machines", machines)
+                .configure(FixedListMachineProvisioningLocation.MACHINE_CHOOSER, chooser));
+        provisioner2.obtain();
+
+        // Should fail when tries to return same machine for a second time
+        try {
+            provisioner2.obtain();
+            fail("Expected "+IllegalStateException.class.getSimpleName());
+        } catch (IllegalStateException e) {
+            if (!e.toString().contains("Machine chooser attempted to choose ")) throw e;
+        }
+    }
+
+    @Test
+    @SuppressWarnings("unchecked")
+    public void testFailsWhenMachineChooserReturnsInvalidMachine() throws Exception {
+        final SshMachineLocation machine1 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("1.1.1.1")));
+        final SshMachineLocation machineOther = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class).configure("address", Networking.getInetAddressWithFixedName("2.2.2.1")));
+        List<SshMachineLocation> machines = ImmutableList.of(machine1);
+        
+        Function<Iterable<? extends MachineLocation>, MachineLocation> chooser = new Function<Iterable<? extends MachineLocation>, MachineLocation>() {
+            @Override public MachineLocation apply(Iterable<? extends MachineLocation> input) {
+                return machineOther;
+            }
+        };
+        provisioner2 = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
+                .configure("machines", machines)
+                .configure(FixedListMachineProvisioningLocation.MACHINE_CHOOSER, chooser));
+
+        // Call when no machines available should fail gracefully, without asking the "chooser"
+        try {
+            provisioner2.obtain();
+            fail("Expected "+IllegalStateException.class.getSimpleName());
+        } catch (IllegalStateException e) {
+            if (!e.toString().contains("Machine chooser attempted to choose ")) throw e;
+        }
+    }
+
+    @Test
+    @SuppressWarnings("unchecked")
+    public void testMachineCustomizerSetOnByon() throws Exception {
+        machine = mgmt.getLocationManager().createLocation(MutableMap.of("address", Inet4Address.getByName("192.168.144.200")), SshMachineLocation.class);
+        RecordingMachineLocationCustomizer customizer = new RecordingMachineLocationCustomizer();
+        
+        provisioner2 = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
+                .configure("machines", ImmutableList.of(machine))
+                .configure(FixedListMachineProvisioningLocation.MACHINE_LOCATION_CUSTOMIZERS.getName(), ImmutableList.of(customizer)));
+                
+        SshMachineLocation obtained = provisioner2.obtain();
+        Assert.assertEquals(Iterables.getOnlyElement(customizer.calls), new RecordingMachineLocationCustomizer.Call("customize", ImmutableList.of(obtained)));
+        
+        provisioner2.release(obtained);
+        assertEquals(customizer.calls.size(), 2);
+        Assert.assertEquals(Iterables.get(customizer.calls, 1), new RecordingMachineLocationCustomizer.Call("preRelease", ImmutableList.of(obtained)));
+    }
+
+    @Test
+    public void testMachineCustomizerSetOnObtainCall() throws Exception {
+        RecordingMachineLocationCustomizer customizer = new RecordingMachineLocationCustomizer();
+        
+        SshMachineLocation obtained = provisioner.obtain(ImmutableMap.of(FixedListMachineProvisioningLocation.MACHINE_LOCATION_CUSTOMIZERS, ImmutableList.of(customizer)));
+        Assert.assertEquals(Iterables.getOnlyElement(customizer.calls), new RecordingMachineLocationCustomizer.Call("customize", ImmutableList.of(obtained)));
+        
+        provisioner.release(obtained);
+        assertEquals(customizer.calls.size(), 2);
+        Assert.assertEquals(customizer.calls.get(1), new RecordingMachineLocationCustomizer.Call("preRelease", ImmutableList.of(obtained)));
+    }
+
+    @Test
+    public void testMachineGivenCustomFlagForDurationOfUsage() throws Exception {
+        boolean origContains = machine.config().getBag().getAllConfig().containsKey("mykey");
+        SshMachineLocation obtained = provisioner.obtain(ImmutableMap.of("mykey", "myNewVal"));
+        Object obtainedVal = obtained.config().getBag().getAllConfig().get("mykey");
+        provisioner.release(obtained);
+        boolean releasedContains = obtained.config().getBag().getAllConfig().containsKey("mykey");
+        
+        assertEquals(obtained, machine);
+        assertFalse(origContains);
+        assertEquals(obtainedVal, "myNewVal");
+        assertFalse(releasedContains);
+    }
+    
+    @Test
+    public void testMachineConfigRestoredToDefaultsOnRelease() throws Exception {
+        ConfigKey<String> mykey = ConfigKeys.newStringConfigKey("mykey");
+        
+        boolean origContains = machine.config().getBag().getAllConfig().containsKey("mykey");
+        SshMachineLocation obtained = provisioner.obtain();
+        obtained.config().set(mykey, "myNewVal");
+        Object obtainedVal = obtained.config().getBag().getAllConfig().get("mykey");
+        
+        provisioner.release(obtained);
+        boolean releasedContains = machine.config().getBag().getAllConfig().containsKey("mykey");
+        releasedContains |= (machine.config().get(mykey) != null);
+        
+        assertEquals(obtained, machine);
+        assertFalse(origContains);
+        assertEquals(obtainedVal, "myNewVal");
+        assertFalse(releasedContains);
+    }
+    
+    @Test
+    public void testMachineGivenOverriddenFlagForDurationOfUsage() throws Exception {
+        SshMachineLocation machine2 = new SshMachineLocation(
+                MutableMap.of("address", Inet4Address.getByName("192.168.144.200"), "mykey", "myval"));
+        provisioner2 = new FixedListMachineProvisioningLocation<SshMachineLocation>(
+                MutableMap.of("machines", MutableList.of(machine2)));
+
+        Object origVal = machine2.config().getBag().getAllConfig().get("mykey");
+        SshMachineLocation obtained = provisioner2.obtain(ImmutableMap.of("mykey", "myNewVal"));
+        Object obtainedVal = obtained.config().getBag().getAllConfig().get("mykey");
+        provisioner2.release(obtained);
+        Object releasedVal = obtained.config().getBag().getAllConfig().get("mykey");
+        
+        assertEquals(obtained, machine2);
+        assertEquals(origVal, "myval");
+        assertEquals(obtainedVal, "myNewVal");
+        assertEquals(releasedVal, "myval");
+    }
+
+    private static <T> List<T> randomized(Iterable<T> list) {
+        // TODO inefficient implementation, but don't care for small tests
+        Random random = new Random();
+        List<T> result = Lists.newLinkedList();
+        for (T element : list) {
+            int index = (result.isEmpty() ? 0 : random.nextInt(result.size()));
+            result.add(index, element);
+        }
+        return result;
+    }
+    
+    private static void assertUserAndHost(SshMachineLocation l, String user, String host) {
+        assertEquals(l.getUser(), user);
+        assertEquals(l.getAddress().getHostAddress(), host);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/byon/HostLocationResolverTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/byon/HostLocationResolverTest.java b/core/src/test/java/org/apache/brooklyn/location/byon/HostLocationResolverTest.java
new file mode 100644
index 0000000..24427f6
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/byon/HostLocationResolverTest.java
@@ -0,0 +1,126 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.byon;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.fail;
+
+import java.net.InetAddress;
+import java.util.Map;
+import java.util.NoSuchElementException;
+
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableMap;
+
+public class HostLocationResolverTest {
+    
+    private BrooklynProperties brooklynProperties;
+    private LocalManagementContext managementContext;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        managementContext = LocalManagementContextForTests.newInstance();
+        brooklynProperties = managementContext.getBrooklynProperties();
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (managementContext != null) Entities.destroyAll(managementContext);
+    }
+    
+    @Test
+    public void testThrowsOnInvalid() throws Exception {
+        assertThrowsNoSuchElement("wrongprefix:(hosts=\"1.1.1.1\")");
+        assertThrowsIllegalArgument("host");
+    }
+    
+    @Test
+    public void testThrowsOnInvalidTarget() throws Exception {
+        assertThrowsIllegalArgument("host:()");
+    }
+    
+    @Test
+    public void resolveHosts() {
+        resolve("host:(\"1.1.1.1\")");
+        resolve("host:(\"localhost\")");
+    }
+    
+    @Test(groups="Integration")
+    public void resolveRealHosts() {
+        // must be online to resolve this
+        resolve("host:(\"www.foo.com\")");
+    }
+    
+    @Test
+    public void testNamedByonLocation() throws Exception {
+        brooklynProperties.put("brooklyn.location.named.mynamed", "host:(\"1.1.1.1\")");
+        
+        MachineProvisioningLocation<SshMachineLocation> loc = resolve("named:mynamed");
+        assertEquals(loc.obtain(ImmutableMap.of()).getAddress(), InetAddress.getByName("1.1.1.1"));
+    }
+
+    @Test
+    public void testPropertyScopePrescedence() throws Exception {
+        brooklynProperties.put("brooklyn.location.named.mynamed", "host:(\"1.1.1.1\")");
+        
+        // prefer those in "named" over everything else
+        brooklynProperties.put("brooklyn.location.named.mynamed.privateKeyFile", "privateKeyFile-inNamed");
+        brooklynProperties.put("brooklyn.localhost.privateKeyFile", "privateKeyFile-inGeneric");
+
+        // prefer location-generic if nothing else
+        brooklynProperties.put("brooklyn.location.privateKeyData", "privateKeyData-inGeneric");
+
+        Map<String, Object> conf = resolve("named:mynamed").obtain(ImmutableMap.of()).config().getBag().getAllConfig();
+        
+        assertEquals(conf.get("privateKeyFile"), "privateKeyFile-inNamed");
+        assertEquals(conf.get("privateKeyData"), "privateKeyData-inGeneric");
+    }
+
+    private void assertThrowsNoSuchElement(String val) {
+        try {
+            resolve(val);
+            fail();
+        } catch (NoSuchElementException e) {
+            // success
+        }
+    }
+    
+    private void assertThrowsIllegalArgument(String val) {
+        try {
+            resolve(val);
+            fail();
+        } catch (IllegalArgumentException e) {
+            // success
+        }
+    }
+    
+    @SuppressWarnings("unchecked")
+    private MachineProvisioningLocation<SshMachineLocation> resolve(String val) {
+        return (MachineProvisioningLocation<SshMachineLocation>) managementContext.getLocationRegistry().resolve(val);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/byon/SingleMachineLocationResolverTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/byon/SingleMachineLocationResolverTest.java b/core/src/test/java/org/apache/brooklyn/location/byon/SingleMachineLocationResolverTest.java
new file mode 100644
index 0000000..8fbca63
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/byon/SingleMachineLocationResolverTest.java
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.byon;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.fail;
+
+import java.net.InetAddress;
+import java.util.Map;
+import java.util.NoSuchElementException;
+
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.byon.SingleMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableMap;
+
+public class SingleMachineLocationResolverTest {
+
+    private BrooklynProperties brooklynProperties;
+    private LocalManagementContext managementContext;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        managementContext = LocalManagementContextForTests.newInstance();
+        brooklynProperties = managementContext.getBrooklynProperties();
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (managementContext != null) Entities.destroyAll(managementContext);
+    }
+    
+    @Test
+    public void testThrowsOnInvalid() throws Exception {
+        assertThrowsNoSuchElement("wrongprefix:(hosts=\"1.1.1.1\")");
+        assertThrowsIllegalArgument("single");
+    }
+    
+    @Test
+    public void testThrowsOnInvalidTarget() throws Exception {
+        assertThrowsIllegalArgument("single()");
+        assertThrowsIllegalArgument("single(wrongprefix:(hosts=\"1.1.1.1\"))");
+        assertThrowsIllegalArgument("single(foo:bar)");
+    }
+
+    @Test
+    public void resolveHosts() {
+        resolve("single(target=localhost)");
+        resolve("single(target=byon(hosts=\"1.1.1.1\"))");
+
+        brooklynProperties.put("brooklyn.location.named.mynamed", "single(target=byon:(hosts=\"1.1.1.1\"))");
+        managementContext.clearLocationRegistry();
+        resolve("single(target=named:mynamed)");
+    }
+    
+    @Test
+    public void resolveWithOldColonFormat() {
+        resolve("single:(target=localhost)");
+    }
+    
+    @Test
+    public void testNamedByonLocation() throws Exception {
+        brooklynProperties.put("brooklyn.location.named.mynamed", "single(target=byon:(hosts=\"1.1.1.1\"))");
+        
+        SingleMachineProvisioningLocation<SshMachineLocation> loc = resolve("named:mynamed");
+        assertEquals(loc.obtain(ImmutableMap.of()).getAddress(), InetAddress.getByName("1.1.1.1"));
+    }
+
+    @Test
+    public void testPropertyScopePrescedence() throws Exception {
+        brooklynProperties.put("brooklyn.location.named.mynamed", "single(target=byon:(hosts=\"1.1.1.1\"))");
+        
+        // prefer those in "named" over everything else
+        brooklynProperties.put("brooklyn.location.named.mynamed.privateKeyFile", "privateKeyFile-inNamed");
+        brooklynProperties.put("brooklyn.localhost.privateKeyFile", "privateKeyFile-inGeneric");
+
+        // prefer location-generic if nothing else
+        brooklynProperties.put("brooklyn.location.privateKeyData", "privateKeyData-inGeneric");
+
+        Map<String, Object> conf = resolve("named:mynamed").obtain(ImmutableMap.of()).config().getBag().getAllConfig();
+        
+        assertEquals(conf.get("privateKeyFile"), "privateKeyFile-inNamed");
+        assertEquals(conf.get("privateKeyData"), "privateKeyData-inGeneric");
+    }
+
+    private void assertThrowsNoSuchElement(String val) {
+        try {
+            resolve(val);
+            fail();
+        } catch (NoSuchElementException e) {
+            // success
+        }
+    }
+    
+    private void assertThrowsIllegalArgument(String val) {
+        try {
+            resolve(val);
+            fail();
+        } catch (IllegalArgumentException e) {
+            // success
+        }
+    }
+    
+    @SuppressWarnings("unchecked")
+    private SingleMachineProvisioningLocation<SshMachineLocation> resolve(String val) {
+        return (SingleMachineProvisioningLocation<SshMachineLocation>) managementContext.getLocationRegistry().resolve(val);
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/byon/SingleMachineProvisioningLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/byon/SingleMachineProvisioningLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/byon/SingleMachineProvisioningLocationTest.java
new file mode 100644
index 0000000..27dee20
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/byon/SingleMachineProvisioningLocationTest.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.byon;
+
+import static org.testng.Assert.assertNotNull;
+
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.location.byon.SingleMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class SingleMachineProvisioningLocationTest {
+    
+    private static final Logger log = LoggerFactory.getLogger(SingleMachineProvisioningLocation.class);
+    
+    private LocalManagementContext managementContext;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        managementContext = LocalManagementContextForTests.newInstance();
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (managementContext != null) managementContext.terminate();
+    }
+    
+    @SuppressWarnings("unchecked") 
+    @Test
+    public void testLocalhostSingle() throws Exception {
+        SingleMachineProvisioningLocation<SshMachineLocation> l = (SingleMachineProvisioningLocation<SshMachineLocation>) 
+            managementContext.getLocationRegistry().resolve("single:(target='localhost')");
+        l.setManagementContext(managementContext);
+        
+        SshMachineLocation m1 = l.obtain();
+        
+        assertNotNull(m1);
+
+        log.info("GOT "+m1);
+        
+        l.release(m1);
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/core/AbstractLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/core/AbstractLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/core/AbstractLocationTest.java
new file mode 100644
index 0000000..eb9c906
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/core/AbstractLocationTest.java
@@ -0,0 +1,185 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.util.Collections;
+import java.util.Map;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.collections.MutableSet;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+public class AbstractLocationTest {
+
+    public static class ConcreteLocation extends AbstractLocation {
+        private static final long serialVersionUID = 3954199300889119970L;
+        @SetFromFlag(defaultVal="mydefault")
+        String myfield;
+
+        public ConcreteLocation() {
+            super();
+        }
+
+        public ConcreteLocation(Map<?,?> properties) {
+            super(properties);
+        }
+    }
+
+    private ManagementContext mgmt;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        mgmt = LocalManagementContextForTests.newInstance();
+    }
+    
+    @AfterMethod(alwaysRun = true)
+    public void tearDown(){
+        if (mgmt!=null) Entities.destroyAll(mgmt);
+    }
+
+    private ConcreteLocation createConcrete() {
+        return createConcrete(MutableMap.<String,Object>of());
+    }
+    private ConcreteLocation createConcrete(Map<String,?> flags) {
+        return createConcrete(null, flags);
+    }
+    @SuppressWarnings("deprecation")
+    private ConcreteLocation createConcrete(String id, Map<String,?> flags) {
+        return mgmt.getLocationManager().createLocation( LocationSpec.create(ConcreteLocation.class).id(id).configure(flags) );
+    }
+    
+    @Test
+    public void testEqualsUsesId() {
+        Location l1 = createConcrete("1", MutableMap.of("name", "bob"));
+        Location l1b = new ConcreteLocation(ImmutableMap.of("id", 1));
+        Location l2 = createConcrete("2", MutableMap.of("name", "frank"));
+        assertEquals(l1, l1b);
+        assertNotEquals(l1, l2);
+    }
+
+    @Test
+    public void nullNameAndParentLocationIsAcceptable() {
+        Location location = createConcrete(MutableMap.of("name", null, "parentLocation", null));
+        assertEquals(location.getDisplayName(), null);
+        assertEquals(location.getParent(), null);
+    }
+
+    @Test
+    public void testSettingParentLocation() {
+        Location location = createConcrete();
+        Location locationSub = createConcrete();
+        locationSub.setParent(location);
+        
+        assertEquals(ImmutableList.copyOf(location.getChildren()), ImmutableList.of(locationSub));
+        assertEquals(locationSub.getParent(), location);
+    }
+
+    @Test
+    public void testClearingParentLocation() {
+        Location location = createConcrete();
+        Location locationSub = createConcrete();
+        locationSub.setParent(location);
+        
+        locationSub.setParent(null);
+        assertEquals(ImmutableList.copyOf(location.getChildren()), Collections.emptyList());
+        assertEquals(locationSub.getParent(), null);
+    }
+    
+    @Test
+    public void testContainsLocation() {
+        Location location = createConcrete();
+        Location locationSub = createConcrete();
+        locationSub.setParent(location);
+        
+        assertTrue(location.containsLocation(location));
+        assertTrue(location.containsLocation(locationSub));
+        assertFalse(locationSub.containsLocation(location));
+    }
+
+
+    @Test
+    public void queryingNameReturnsNameGivenInConstructor() {
+        String name = "Outer Mongolia";
+        Location location = createConcrete(MutableMap.of("name", "Outer Mongolia"));
+        assertEquals(location.getDisplayName(), name);;
+    }
+
+    @Test
+    public void constructorParentLocationReturnsExpectedLocation() {
+        Location parent = createConcrete(MutableMap.of("name", "Middle Earth"));
+        Location child = createConcrete(MutableMap.of("name", "The Shire", "parentLocation", parent));
+        assertEquals(child.getParent(), parent);
+        assertEquals(ImmutableList.copyOf(parent.getChildren()), ImmutableList.of(child));
+    }
+
+    @Test
+    public void setParentLocationReturnsExpectedLocation() {
+        Location parent = createConcrete(MutableMap.of("name", "Middle Earth"));
+        Location child = createConcrete(MutableMap.of("name", "The Shire"));
+        child.setParent(parent);
+        assertEquals(child.getParent(), parent);
+        assertEquals(ImmutableList.copyOf(parent.getChildren()), ImmutableList.of(child));
+    }
+    
+    @Test
+    public void testAddChildToParentLocationReturnsExpectedLocation() {
+        ConcreteLocation parent = createConcrete();
+        Location child = createConcrete();
+        parent.addChild(child);
+        assertEquals(child.getParent(), parent);
+        assertEquals(ImmutableList.copyOf(parent.getChildren()), ImmutableList.of(child));
+    }
+
+    @Test
+    public void testFieldSetFromFlag() {
+        ConcreteLocation loc = createConcrete(MutableMap.of("myfield", "myval"));
+        assertEquals(loc.myfield, "myval");
+    }
+    
+    @Test
+    public void testFieldSetFromFlagUsesDefault() {
+        ConcreteLocation loc = createConcrete();
+        assertEquals(loc.myfield, "mydefault");
+    }
+
+    @Test
+    public void testLocationTags() throws Exception {
+        LocationInternal loc = mgmt.getLocationManager().createLocation(LocationSpec.create(ConcreteLocation.class).tag("x"));
+        assertEquals(loc.tags().getTags(), MutableSet.of("x"));
+    }
+
+}


[27/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynEntityMirror.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynEntityMirror.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynEntityMirror.java
new file mode 100644
index 0000000..ac884fa
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynEntityMirror.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.catalog.Catalog;
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.util.time.Duration;
+
+/** Provides an entity which can sit in one brooklyn domain and reflect the status of an entity 
+ * via the REST API of another domain.
+ * <p>
+ * Note tests for this depend on a REST server so are in other projects; search for *Mirror*Test,
+ * as well as *BrooklynNode*Test. */
+@Catalog(name="Brooklyn Entity Mirror", description="Provides an entity which can sit in one brooklyn "
+        + "domain and reflect the status of an entity via the REST API of another domain.")
+@ImplementedBy(BrooklynEntityMirrorImpl.class)
+public interface BrooklynEntityMirror extends Entity {
+
+    // caller must specify this:
+    public static final ConfigKey<String> MIRRORED_ENTITY_URL = ConfigKeys.newStringConfigKey("brooklyn.mirror.entity_url",
+        "URL for the entity in the remote Brooklyn mgmt endpoint");
+    
+    // caller may specify this for reference:
+    public static final ConfigKey<String> MIRRORED_ENTITY_ID = ConfigKeys.newStringConfigKey("brooklyn.mirror.entity_id",
+        "Brooklyn ID of the entity being mirrored");
+    
+    // must be specified if required (could be inherited if parent/config is available at init time, but it's not currently)
+    public static final ConfigKey<String> MANAGEMENT_USER = BrooklynNode.MANAGEMENT_USER;
+    public static final ConfigKey<String> MANAGEMENT_PASSWORD = BrooklynNode.MANAGEMENT_PASSWORD;
+    
+    public static final ConfigKey<Duration> POLL_PERIOD = ConfigKeys.newConfigKey(Duration.class, "brooklyn.mirror.poll_period",
+        "Frequency to poll for client sensors", Duration.FIVE_SECONDS);
+    
+    public static final AttributeSensor<String> MIRROR_STATUS = Sensors.newStringSensor("brooklyn.mirror.monitoring_status");
+    @SuppressWarnings("rawtypes")
+    public static final AttributeSensor<Map> MIRROR_SUMMARY = Sensors.newSensor(Map.class, "brooklyn.mirror.summary",
+        "The json map returned by the entity rest endpoint (ie the EntitySummary model)");
+    public static final AttributeSensor<String> MIRROR_CATALOG_ITEM_ID = Sensors.newStringSensor("brooklyn.mirror.catalog_item_id",
+        "The catalog item id of the mirrored entity in the remote brooklyn");
+    
+    public EntityHttpClient http();
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynEntityMirrorImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynEntityMirrorImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynEntityMirrorImpl.java
new file mode 100644
index 0000000..34479d6
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynEntityMirrorImpl.java
@@ -0,0 +1,194 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.concurrent.Callable;
+
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.effector.core.EffectorBody;
+import org.apache.brooklyn.entity.core.AbstractEntity;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.core.EntityDynamicType;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.sensor.feed.http.HttpFeed;
+import org.apache.brooklyn.sensor.feed.http.HttpPollConfig;
+import org.apache.brooklyn.util.collections.Jsonya;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.http.HttpToolResponse;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.net.Urls;
+import org.apache.http.HttpStatus;
+
+import com.google.common.base.Function;
+import com.google.common.base.Preconditions;
+import com.google.common.net.MediaType;
+import com.google.gson.Gson;
+
+public class BrooklynEntityMirrorImpl extends AbstractEntity implements BrooklynEntityMirror {
+    @SuppressWarnings("rawtypes")
+    private class MirrorSummary implements Function<HttpToolResponse, Map> {
+        @Override
+        public Map apply(HttpToolResponse input) {
+            Map<?, ?> entitySummary = new Gson().fromJson(input.getContentAsString(), Map.class);
+            String catalogItemId = (String)entitySummary.get("catalogItemId");
+            setAttribute(MIRROR_CATALOG_ITEM_ID, catalogItemId);
+            return entitySummary;
+        }
+    }
+
+    private HttpFeed mirror;
+    
+
+    //Passively mirror entity's state
+    @Override
+    protected void initEnrichers() {}
+
+    @Override
+    public void init() {
+        super.init();
+        connectSensorsAsync();
+
+        //start spinning, could take some time before MIRRORED_ENTITY_URL is available for first time mirroring
+        setAttribute(Attributes.SERVICE_STATE_ACTUAL, Lifecycle.STARTING);
+    }
+
+    @Override
+    public void rebind() {
+        super.rebind();
+        connectSensorsAsync();
+    }
+
+    protected void connectSensorsAsync() {
+        Callable<Void> asyncTask = new Callable<Void>() {
+            @Override
+            public Void call() throws Exception {
+                //blocks until available (could be a task)
+                String mirroredEntityUrl = getConfig(MIRRORED_ENTITY_URL);
+                Preconditions.checkNotNull(mirroredEntityUrl, "Required config: "+MIRRORED_ENTITY_URL);
+
+                connectSensors(mirroredEntityUrl);
+                return null;
+            }
+        };
+
+        DynamicTasks.queueIfPossible(
+                Tasks.<Void>builder()
+                    .name("Start entity mirror feed")
+                    .body(asyncTask)
+                    .build())
+            .orSubmitAsync(this);
+    }
+
+    protected void connectSensors(String mirroredEntityUrl) {
+        Function<HttpToolResponse, Void> mirrorSensors = new Function<HttpToolResponse,Void>() {
+            @SuppressWarnings("rawtypes")
+            @Override
+            public Void apply(HttpToolResponse input) {
+                Map sensors = new Gson().fromJson(input.getContentAsString(), Map.class);
+                for (Object kv: sensors.entrySet())
+                    setAttribute(Sensors.newSensor(Object.class, ""+((Map.Entry)kv).getKey()), ((Map.Entry)kv).getValue());
+                setAttribute(MIRROR_STATUS, "normal");
+                return null;
+            }
+        };
+
+        final BrooklynEntityMirrorImpl self = this;
+        mirror = HttpFeed.builder().entity(this)
+            .baseUri(mirroredEntityUrl)
+            .credentialsIfNotNull(getConfig(BrooklynNode.MANAGEMENT_USER), getConfig(BrooklynNode.MANAGEMENT_PASSWORD))
+            .period(getConfig(POLL_PERIOD))
+            .poll(HttpPollConfig.forMultiple()
+                .suburl("/sensors/current-state")
+                .onSuccess(mirrorSensors)
+                .onFailureOrException(new Function<Object, Void>() {
+                    @Override
+                    public Void apply(Object input) {
+                        ServiceStateLogic.updateMapSensorEntry(self, Attributes.SERVICE_PROBLEMS, "mirror-feed", "error contacting service");
+                        if (input instanceof HttpToolResponse) {
+                            int responseCode = ((HttpToolResponse)input).getResponseCode();
+                            if (responseCode == HttpStatus.SC_NOT_FOUND) {
+                                //the remote entity no longer exists
+                                Entities.unmanage(self);
+                            }
+                        }
+                        return null;
+                    }
+                }))
+            .poll(HttpPollConfig.forSensor(MIRROR_SUMMARY).onSuccess(new MirrorSummary())).build();
+
+        populateEffectors();
+    }
+
+    private void populateEffectors() {
+        HttpToolResponse result = http().get("/effectors");
+        Collection<?> cfgEffectors = new Gson().fromJson(result.getContentAsString(), Collection.class);
+        Collection<Effector<String>> remoteEntityEffectors = RemoteEffectorBuilder.of(cfgEffectors);
+        EntityDynamicType mutableEntityType = getMutableEntityType();
+        for (Effector<String> eff : remoteEntityEffectors) {
+            //remote already started
+            if ("start".equals(eff.getName())) continue;
+            mutableEntityType.addEffector(eff);
+        }
+    }
+
+    protected void disconnectSensors() {
+        if (mirror != null) mirror.stop();
+    }
+
+    @Override
+    public void destroy() {
+        disconnectSensors();
+    }
+
+    @Override
+    public EntityHttpClient http() {
+        return new EntityHttpClientImpl(this, MIRRORED_ENTITY_URL);
+    }
+
+    public static class RemoteEffector<T> extends EffectorBody<T> {
+        public final String remoteEffectorName;
+        public final Function<HttpToolResponse, T> resultParser;
+        
+        /** creates an effector implementation which POSTs to a remote effector endpoint, optionally converting
+         * the byte[] response (if resultParser is null then null is returned) */
+        public RemoteEffector(String remoteEffectorName, @Nullable Function<HttpToolResponse,T> resultParser) {
+            this.remoteEffectorName = remoteEffectorName;
+            this.resultParser = resultParser;
+        }
+
+        @Override
+        public T call(ConfigBag parameters) {
+            MutableMap<String, String> headers = MutableMap.of(com.google.common.net.HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString());
+            byte[] httpBody = Jsonya.of(parameters.getAllConfig()).toString().getBytes();
+            String effectorUrl = Urls.mergePaths("effectors", Urls.encode(remoteEffectorName));
+            HttpToolResponse result = ((BrooklynEntityMirror)entity()).http().post(effectorUrl, headers, httpBody);
+            if (resultParser!=null) return resultParser.apply(result);
+            else return null;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNode.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNode.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNode.java
new file mode 100644
index 0000000..51b1281
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNode.java
@@ -0,0 +1,312 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import java.net.InetAddress;
+import java.net.URI;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.api.catalog.Catalog;
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.BrooklynVersion;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.config.MapConfigKey;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.entity.java.UsesJava;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
+import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
+import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey.StringAttributeSensorAndConfigKey;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+import org.apache.brooklyn.util.net.Networking;
+import org.apache.brooklyn.util.ssh.BashCommands;
+import org.apache.brooklyn.util.time.Duration;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Function;
+import com.google.common.base.Functions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import com.google.common.reflect.TypeToken;
+
+@Catalog(name="Brooklyn Node", description="Deploys a Brooklyn management server")
+@ImplementedBy(BrooklynNodeImpl.class)
+public interface BrooklynNode extends SoftwareProcess, UsesJava {
+
+    @SuppressWarnings("serial")
+    @SetFromFlag("copyToRundir")
+    public static final BasicAttributeSensorAndConfigKey<Map<String,String>> COPY_TO_RUNDIR = new BasicAttributeSensorAndConfigKey<Map<String,String>>(
+            new TypeToken<Map<String,String>>() {}, "brooklynnode.copytorundir", "URLs of resources to be copied across to the server, giving the path they are to be copied to", MutableMap.<String,String>of());
+    
+    @SetFromFlag("version")
+    public static final ConfigKey<String> SUGGESTED_VERSION = ConfigKeys.newConfigKeyWithDefault(BrooklynConfigKeys.SUGGESTED_VERSION, "0.8.0-SNAPSHOT"); // BROOKLYN_VERSION
+
+    @SetFromFlag("distroUploadUrl")
+    public static final ConfigKey<String> DISTRO_UPLOAD_URL = ConfigKeys.newStringConfigKey(
+            "brooklynnode.distro.uploadurl", "URL for uploading the brooklyn distro (retrieved locally and pushed to remote install location. Takes precedence over downloadUrl, if non-null)", null);
+
+    // Note that download URL only supports versions in org.apache.brooklyn, so not 0.6.0 and earlier 
+    // (which used maven group io.brooklyn). Aled thinks we can live with that.
+    @SetFromFlag("downloadUrl")
+    BasicAttributeSensorAndConfigKey<String> DOWNLOAD_URL = new StringAttributeSensorAndConfigKey(
+            SoftwareProcess.DOWNLOAD_URL,
+            "<#if version?contains(\"SNAPSHOT\")>"+
+                "https://repository.apache.org/service/local/artifact/maven/redirect?r=snapshots&g=org.apache.brooklyn&v=${version}&a=brooklyn-dist&c=dist&e=tar.gz" +
+            "<#else>"+
+                "http://search.maven.org/remotecontent?filepath=org/apache/brooklyn/brooklyn-dist/${version}/brooklyn-dist-${version}-dist.tar.gz"+
+            "</#if>");
+
+    @SetFromFlag("subpathInArchive")
+    ConfigKey<String> SUBPATH_IN_ARCHIVE = ConfigKeys.newStringConfigKey("brooklynnode.download.archive.subpath",
+        "Path to the main directory in the archive being supplied for installation; "
+        + "to use the root of an archive, specify '.'; "
+        + "default value taken based on download URL (e.g. 'name' for 'http://path/name.tgz' or 'http://path/name-dist.tgz') "
+        + "falling back to an appropriate value for brooklyn, "
+        + "e.g. 'brooklyn-"+BrooklynVersion.INSTANCE.getVersion()+"'", null);
+
+    @SetFromFlag("managementUser")
+    ConfigKey<String> MANAGEMENT_USER = ConfigKeys.newConfigKey("brooklynnode.managementUser",
+            "The user for logging into the brooklyn web-console (also used for health-checks)",
+            "admin");
+
+    @SetFromFlag("managementPassword")
+    ConfigKey<String> MANAGEMENT_PASSWORD =
+            ConfigKeys.newStringConfigKey("brooklynnode.managementPassword", "Password for MANAGEMENT_USER", null);
+
+    /** useful e.g. with {@link BashCommands#generateKeyInDotSshIdRsaIfNotThere() } */
+    @SetFromFlag("extraCustomizationScript")
+    ConfigKey<String> EXTRA_CUSTOMIZATION_SCRIPT = ConfigKeys.newStringConfigKey("brooklynnode.customization.extraScript",
+        "Optional additional script commands to run as part of customization; this might e.g. ensure id_rsa is set up",
+        null);
+
+    static enum ExistingFileBehaviour {
+        DO_NOT_USE, USE_EXISTING, OVERWRITE, FAIL
+    }
+    
+    @SetFromFlag("onExistingProperties")
+    ConfigKey<ExistingFileBehaviour> ON_EXISTING_PROPERTIES_FILE = ConfigKeys.newConfigKey(ExistingFileBehaviour.class,
+        "brooklynnode.properties.file.ifExists",
+        "What to do in the case where a global brooklyn.properties already exists", 
+        ExistingFileBehaviour.FAIL);
+
+    @SetFromFlag("launchCommand")
+    ConfigKey<String> LAUNCH_COMMAND = ConfigKeys.newStringConfigKey("brooklynnode.launch.command",
+        "Path to the script to launch Brooklyn / the app relative to the subpath in the archive, defaulting to 'bin/brooklyn'", 
+        "bin/brooklyn");
+
+    @SetFromFlag("launchParameters")
+    ConfigKey<String> EXTRA_LAUNCH_PARAMETERS = ConfigKeys.newStringConfigKey("brooklynnode.launch.parameters.extra",
+        "Launch parameters passed on the CLI, in addition to 'launch' and parameters implied by other config keys (and placed afterwards on the command line)");
+
+    @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, "
+        + "but note it will not necessarily kill sub-processes", 
+        true);
+
+    @SetFromFlag("app")
+    public static final BasicAttributeSensorAndConfigKey<String> APP = new BasicAttributeSensorAndConfigKey<String>(
+            String.class, "brooklynnode.app", "Application (fully qualified class name) to launch using the brooklyn CLI", null);
+    
+    @SetFromFlag("locations")
+    public static final BasicAttributeSensorAndConfigKey<String> LOCATIONS = new BasicAttributeSensorAndConfigKey<String>(
+            String.class, "brooklynnode.locations", "Locations to use when launching the app", null);
+    
+    /**
+     * Exposed just for testing; remote path is not passed into the launched brooklyn so this won't be used!
+     * This will likely change in a future version.
+     */
+    @VisibleForTesting
+    @SetFromFlag("brooklynGlobalPropertiesRemotePath")
+    public static final ConfigKey<String> BROOKLYN_GLOBAL_PROPERTIES_REMOTE_PATH = ConfigKeys.newStringConfigKey(
+            "brooklynnode.brooklynproperties.global.remotepath", 
+            "Remote path for the global brooklyn.properties file to be uploaded", "${HOME}/.brooklyn/brooklyn.properties; "+
+                "only useful for testing as this path will not be used on the remote system");
+    
+    @SetFromFlag("brooklynGlobalPropertiesUri")
+    public static final ConfigKey<String> BROOKLYN_GLOBAL_PROPERTIES_URI = ConfigKeys.newStringConfigKey(
+            "brooklynnode.brooklynproperties.global.uri", "URI for the global brooklyn properties file (uploaded to ~/.brooklyn/brooklyn.properties)", null);
+
+    @SetFromFlag("brooklynGlobalPropertiesContents")
+    public static final ConfigKey<String> BROOKLYN_GLOBAL_PROPERTIES_CONTENTS = ConfigKeys.newStringConfigKey(
+            "brooklynnode.brooklynproperties.global.contents", "Contents for the global brooklyn properties file (uploaded to ~/.brooklyn/brooklyn.properties)", null);
+
+    @SetFromFlag("brooklynLocalPropertiesRemotePath")
+    public static final ConfigKey<String> BROOKLYN_LOCAL_PROPERTIES_REMOTE_PATH = ConfigKeys.newStringConfigKey(
+            "brooklynnode.brooklynproperties.local.remotepath", "Remote path for the launch-specific brooklyn.properties file to be uploaded", "${driver.runDir}/brooklyn-local.properties");
+    
+    @SetFromFlag("brooklynLocalPropertiesUri")
+    public static final ConfigKey<String> BROOKLYN_LOCAL_PROPERTIES_URI = ConfigKeys.newStringConfigKey(
+            "brooklynnode.brooklynproperties.local.uri", "URI for the launch-specific brooklyn properties file", null);
+
+    @SetFromFlag("brooklynLocalPropertiesContents")
+    public static final ConfigKey<String> BROOKLYN_LOCAL_PROPERTIES_CONTENTS = ConfigKeys.newStringConfigKey(
+            "brooklynnode.brooklynproperties.local.contents", "Contents for the launch-specific brooklyn properties file", null);
+    
+    // For use in testing primarily
+    /** @deprecated since 0.7.0; TODO this should support BOM files */
+    @Deprecated
+    @SetFromFlag("brooklynCatalogRemotePath")
+    public static final ConfigKey<String> BROOKLYN_CATALOG_REMOTE_PATH = ConfigKeys.newStringConfigKey(
+            "brooklynnode.brooklyncatalog.remotepath", "Remote path for the brooklyn catalog.xml file to be uploaded", "${HOME}/.brooklyn/catalog.xml");
+    
+    /** @deprecated since 0.7.0; TODO this should support BOM files */
+    @Deprecated
+    @SetFromFlag("brooklynCatalogUri")
+    public static final ConfigKey<String> BROOKLYN_CATALOG_URI = ConfigKeys.newStringConfigKey(
+            "brooklynnode.brooklyncatalog.uri", "URI for the brooklyn catalog.xml file (uploaded to ~/.brooklyn/catalog.xml)", null);
+
+    /** @deprecated since 0.7.0; TODO this should support BOM files */
+    @Deprecated
+    @SetFromFlag("brooklynCatalogContents")
+    public static final ConfigKey<String> BROOKLYN_CATALOG_CONTENTS = ConfigKeys.newStringConfigKey(
+            "brooklynnode.brooklyncatalog.contents", "Contents for the brooklyn catalog.xml file (uploaded to ~/.brooklyn/catalog.xml)", null);
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @SetFromFlag("enabledHttpProtocols")
+    public static final BasicAttributeSensorAndConfigKey<List<String>> ENABLED_HTTP_PROTOCOLS = new BasicAttributeSensorAndConfigKey(
+            List.class, "brooklynnode.webconsole.enabledHttpProtocols", "List of enabled protocols (e.g. http, https)", ImmutableList.of("http"));
+
+    @SetFromFlag("httpPort")
+    public static final PortAttributeSensorAndConfigKey HTTP_PORT = new PortAttributeSensorAndConfigKey(
+            "brooklynnode.webconsole.httpPort", "HTTP Port for the brooklyn web-console", "8081+");
+    
+    @SetFromFlag("httpsPort")
+    public static final PortAttributeSensorAndConfigKey HTTPS_PORT = new PortAttributeSensorAndConfigKey(
+            "brooklynnode.webconsole.httpsPort", "HTTPS Port for the brooklyn web-console", "8443+");
+
+    @SetFromFlag("noWebConsoleSecurity")
+    public static final BasicAttributeSensorAndConfigKey<Boolean> NO_WEB_CONSOLE_AUTHENTICATION = new BasicAttributeSensorAndConfigKey<Boolean>(
+            Boolean.class, "brooklynnode.webconsole.nosecurity", "Whether to start the web console with no security", false);
+
+    @SetFromFlag("bindAddress")
+    public static final BasicAttributeSensorAndConfigKey<InetAddress> WEB_CONSOLE_BIND_ADDRESS = new BasicAttributeSensorAndConfigKey<InetAddress>(
+            InetAddress.class, "brooklynnode.webconsole.address.bind", "Specifies the IP address of the NIC to bind the Brooklyn Management Console to (default 0.0.0.0)", Networking.ANY_NIC);
+
+    @SetFromFlag("publicAddress")
+    public static final BasicAttributeSensorAndConfigKey<InetAddress> WEB_CONSOLE_PUBLIC_ADDRESS = new BasicAttributeSensorAndConfigKey<InetAddress>(
+            InetAddress.class, "brooklynnode.webconsole.address.public", "Specifies the public IP address or hostname for the Brooklyn Management Console");
+
+    public static final AttributeSensor<Boolean> WEB_CONSOLE_ACCESSIBLE = Sensors.newBooleanSensor(
+        "brooklynnode.webconsole.up", "Whether the web console is responding normally");
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @SetFromFlag("classpath")
+    public static final BasicAttributeSensorAndConfigKey<List<String>> CLASSPATH = new BasicAttributeSensorAndConfigKey(
+            List.class, "brooklynnode.classpath", "classpath to use, as list of URL entries", Lists.newArrayList());
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @SetFromFlag("portMapper")
+    public static final ConfigKey<Function<? super Integer, ? extends Integer>> PORT_MAPPER = (ConfigKey) ConfigKeys.newConfigKey(Function.class,
+            "brooklynnode.webconsole.portMapper", "Function for mapping private to public ports, for use in inferring the brooklyn URI", Functions.<Integer>identity());
+
+    public static final AttributeSensor<URI> WEB_CONSOLE_URI = new BasicAttributeSensor<URI>(
+            URI.class, "brooklynnode.webconsole.url", "URL of the brooklyn web-console");
+
+    public static final AttributeSensor<ManagementNodeState> MANAGEMENT_NODE_STATE = new BasicAttributeSensor<ManagementNodeState>(
+            ManagementNodeState.class, "brooklynnode.ha.state", "High-availability state of the management node (MASTER, HOT_STANDBY, etc)");
+    
+    public static final ConfigKey<Duration> POLL_PERIOD = ConfigKeys.newConfigKey(Duration.class, "brooklynnode.poll_period",
+            "Frequency to poll for client sensors", Duration.seconds(2));
+
+    public interface DeployBlueprintEffector {
+        ConfigKey<Map<String,Object>> BLUEPRINT_CAMP_PLAN = new MapConfigKey<Object>(Object.class, "blueprintPlan",
+            "CAMP plan for the blueprint to be deployed; currently only supports Java map or JSON string (not yet YAML)");
+        ConfigKey<String> BLUEPRINT_TYPE = ConfigKeys.newStringConfigKey("blueprintType");
+        ConfigKey<Map<String,Object>> BLUEPRINT_CONFIG = new MapConfigKey<Object>(Object.class, "blueprintConfig");
+        Effector<String> DEPLOY_BLUEPRINT = Effectors.effector(String.class, "deployBlueprint")
+            .description("Deploy a blueprint, either given a plan (as Java map or JSON string for a map), or given URL and optional config")
+            .parameter(BLUEPRINT_TYPE)
+            .parameter(BLUEPRINT_CONFIG)
+            .parameter(BLUEPRINT_CAMP_PLAN)
+            .buildAbstract();
+    }
+
+    public static final Effector<String> DEPLOY_BLUEPRINT = DeployBlueprintEffector.DEPLOY_BLUEPRINT;
+
+    public interface ShutdownEffector {
+        ConfigKey<Boolean> STOP_APPS_FIRST = ConfigKeys.newBooleanConfigKey("stopAppsFirst", "Whether to stop apps before shutting down");
+        ConfigKey<Boolean> FORCE_SHUTDOWN_ON_ERROR = ConfigKeys.newBooleanConfigKey("forceShutdownOnError", "Force shutdown if apps fail to stop or timeout");
+        ConfigKey<Duration> SHUTDOWN_TIMEOUT = ConfigKeys.newConfigKey(Duration.class, "shutdownTimeout", "A maximum delay to wait for apps to gracefully stop before giving up or forcibly exiting");
+        ConfigKey<Duration> REQUEST_TIMEOUT = ConfigKeys.newConfigKey(Duration.class, "requestTimeout", "Maximum time to block the request for the shutdown to finish, 0 to wait infinitely");
+        ConfigKey<Duration> DELAY_FOR_HTTP_RETURN = ConfigKeys.newConfigKey(Duration.class, "delayForHttpReturn", "The delay before exiting the process, to permit the REST response to be returned");
+        Effector<Void> SHUTDOWN = Effectors.effector(Void.class, "shutdown")
+            .description("Shutdown the remote brooklyn instance (stops via the REST API only; leaves any VM)")
+            .parameter(STOP_APPS_FIRST)
+            .parameter(FORCE_SHUTDOWN_ON_ERROR)
+            .parameter(SHUTDOWN_TIMEOUT)
+            .parameter(REQUEST_TIMEOUT)
+            .parameter(DELAY_FOR_HTTP_RETURN)
+            .buildAbstract();
+    }
+
+    public static final Effector<Void> SHUTDOWN = ShutdownEffector.SHUTDOWN;
+
+    public interface StopNodeButLeaveAppsEffector {
+        ConfigKey<Duration> TIMEOUT = ConfigKeys.newConfigKey(Duration.class, "timeout", "How long to wait before giving up on stopping the node", Duration.ONE_HOUR);
+        Effector<Void> STOP_NODE_BUT_LEAVE_APPS = Effectors.effector(Void.class, "stopNodeButLeaveApps")
+                .description("Stop the Brooklyn process, and any VM created, and unmanage this entity; but if it was managing other applications, leave them running")
+                .parameter(TIMEOUT)
+                .buildAbstract();
+    }
+
+    public static final Effector<Void> STOP_NODE_BUT_LEAVE_APPS = StopNodeButLeaveAppsEffector.STOP_NODE_BUT_LEAVE_APPS;
+
+    public interface StopNodeAndKillAppsEffector {
+        ConfigKey<Duration> TIMEOUT = ConfigKeys.newConfigKey(Duration.class, "timeout", "How long to wait before giving up on stopping the node", Duration.ONE_HOUR);
+        Effector<Void> STOP_NODE_AND_KILL_APPS = Effectors.effector(Void.class, "stopNodeAndKillApps")
+                .description("Stop all apps managed by the Brooklyn process, stop the process, and any VM created, and unmanage this entity")
+                .parameter(TIMEOUT)
+                .buildAbstract();
+    }
+
+    public static final Effector<Void> STOP_NODE_AND_KILL_APPS = StopNodeAndKillAppsEffector.STOP_NODE_AND_KILL_APPS;
+
+    public interface SetHighAvailabilityPriorityEffector {
+        ConfigKey<Integer> PRIORITY = ConfigKeys.newIntegerConfigKey("priority", "HA priority");
+        Effector<Integer> SET_HIGH_AVAILABILITY_PRIORITY = Effectors.effector(Integer.class, "setHighAvailabilityPriority")
+                .description("Set the HA priority on the node, returning the old priority")
+                .parameter(PRIORITY)
+                .buildAbstract();
+    }
+
+    public static final Effector<Integer> SET_HIGH_AVAILABILITY_PRIORITY = SetHighAvailabilityPriorityEffector.SET_HIGH_AVAILABILITY_PRIORITY;
+
+    public interface SetHighAvailabilityModeEffector {
+        ConfigKey<HighAvailabilityMode> MODE = ConfigKeys.newConfigKey(HighAvailabilityMode.class, "mode", "HA mode");
+        Effector<ManagementNodeState> SET_HIGH_AVAILABILITY_MODE = Effectors.effector(ManagementNodeState.class, "setHighAvailabilityMode")
+                .description("Set the HA mode on the node, returning the existing state")
+                .parameter(MODE)
+                .buildAbstract();
+    }
+
+    public static final Effector<ManagementNodeState> SET_HIGH_AVAILABILITY_MODE = SetHighAvailabilityModeEffector.SET_HIGH_AVAILABILITY_MODE;
+
+    public EntityHttpClient http();
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeDriver.java
new file mode 100644
index 0000000..e45eab1
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeDriver.java
@@ -0,0 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessDriver;
+
+public interface BrooklynNodeDriver extends JavaSoftwareProcessDriver {
+
+    void clearInstallDir();
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeImpl.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeImpl.java
new file mode 100644
index 0000000..4e76f70
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeImpl.java
@@ -0,0 +1,522 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import java.net.URI;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.api.mgmt.TaskAdaptable;
+import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.render.RendererHints;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
+import org.apache.brooklyn.effector.core.EffectorBody;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.entity.brooklynnode.EntityHttpClient.ResponseCodePredicates;
+import org.apache.brooklyn.entity.brooklynnode.effector.BrooklynNodeUpgradeEffectorBody;
+import org.apache.brooklyn.entity.brooklynnode.effector.SetHighAvailabilityModeEffectorBody;
+import org.apache.brooklyn.entity.brooklynnode.effector.SetHighAvailabilityPriorityEffectorBody;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic.ServiceNotUpLogic;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.StopSoftwareParameters.StopMode;
+import org.apache.brooklyn.entity.software.base.lifecycle.MachineLifecycleEffectorTasks;
+import org.apache.brooklyn.entity.trait.Startable;
+import org.apache.http.HttpStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.location.access.BrooklynAccessUtils;
+import org.apache.brooklyn.location.basic.Locations;
+import org.apache.brooklyn.sensor.enricher.Enrichers;
+import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
+import org.apache.brooklyn.sensor.feed.http.HttpFeed;
+import org.apache.brooklyn.sensor.feed.http.HttpPollConfig;
+import org.apache.brooklyn.sensor.feed.http.HttpValueFunctions;
+import org.apache.brooklyn.sensor.feed.http.JsonFunctions;
+import org.apache.brooklyn.util.collections.Jsonya;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.http.HttpToolResponse;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.TaskTags;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.exceptions.PropagatedRuntimeException;
+import org.apache.brooklyn.util.guava.Functionals;
+import org.apache.brooklyn.util.javalang.Enums;
+import org.apache.brooklyn.util.javalang.JavaClassNames;
+import org.apache.brooklyn.util.repeat.Repeater;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Predicates;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.net.HostAndPort;
+import com.google.common.util.concurrent.Runnables;
+import com.google.gson.Gson;
+
+public class BrooklynNodeImpl extends SoftwareProcessImpl implements BrooklynNode {
+
+    private static final Logger log = LoggerFactory.getLogger(BrooklynNodeImpl.class);
+
+    static {
+        RendererHints.register(WEB_CONSOLE_URI, RendererHints.namedActionWithUrl());
+    }
+
+    private static class UnmanageTask implements Runnable {
+        private Task<?> latchTask;
+        private Entity unmanageEntity;
+
+        public UnmanageTask(@Nullable Task<?> latchTask, Entity unmanageEntity) {
+            this.latchTask = latchTask;
+            this.unmanageEntity = unmanageEntity;
+        }
+
+        public void run() {
+            if (latchTask != null) {
+                latchTask.blockUntilEnded();
+            } else {
+                log.debug("No latch task provided for UnmanageTask, falling back to fixed wait");
+                Time.sleep(Duration.FIVE_SECONDS);
+            }
+            synchronized (this) {
+                Entities.unmanage(unmanageEntity);
+            }
+        }
+    }
+
+    private HttpFeed httpFeed;
+    
+    public BrooklynNodeImpl() {
+        super();
+    }
+
+    public BrooklynNodeImpl(Entity parent) {
+        super(parent);
+    }
+    
+    @Override
+    public Class<?> getDriverInterface() {
+        return BrooklynNodeDriver.class;
+    }
+
+    @Override
+    public void init() {
+        super.init();
+        getMutableEntityType().addEffector(DeployBlueprintEffectorBody.DEPLOY_BLUEPRINT);
+        getMutableEntityType().addEffector(ShutdownEffectorBody.SHUTDOWN);
+        getMutableEntityType().addEffector(StopNodeButLeaveAppsEffectorBody.STOP_NODE_BUT_LEAVE_APPS);
+        getMutableEntityType().addEffector(StopNodeAndKillAppsEffectorBody.STOP_NODE_AND_KILL_APPS);
+        getMutableEntityType().addEffector(SetHighAvailabilityPriorityEffectorBody.SET_HIGH_AVAILABILITY_PRIORITY);
+        getMutableEntityType().addEffector(SetHighAvailabilityModeEffectorBody.SET_HIGH_AVAILABILITY_MODE);
+        getMutableEntityType().addEffector(BrooklynNodeUpgradeEffectorBody.UPGRADE);
+    }
+
+    @Override
+    protected void preStart() {
+        ServiceNotUpLogic.clearNotUpIndicator(this, SHUTDOWN.getName());
+    }
+
+    @Override
+    protected void preStopConfirmCustom() {
+        super.preStopConfirmCustom();
+        ConfigBag stopParameters = BrooklynTaskTags.getCurrentEffectorParameters();
+        if (Boolean.TRUE.equals(getAttribute(BrooklynNode.WEB_CONSOLE_ACCESSIBLE)) &&
+                stopParameters != null && !stopParameters.containsKey(ShutdownEffector.STOP_APPS_FIRST)) {
+            Preconditions.checkState(getChildren().isEmpty(), "Can't stop instance with running applications.");
+        }
+    }
+
+    @Override
+    protected void preStop() {
+        super.preStop();
+        if (MachineLifecycleEffectorTasks.canStop(getStopProcessModeParam(), this)) {
+            shutdownGracefully();
+        }
+    }
+
+    private StopMode getStopProcessModeParam() {
+        ConfigBag parameters = BrooklynTaskTags.getCurrentEffectorParameters();
+        if (parameters != null) {
+            return parameters.get(StopSoftwareParameters.STOP_PROCESS_MODE);
+        } else {
+            return StopSoftwareParameters.STOP_PROCESS_MODE.getDefaultValue();
+        }
+    }
+
+    @Override
+    protected void preRestart() {
+        super.preRestart();
+        //restart will kill the process, try to shut down before that
+        shutdownGracefully();
+        DynamicTasks.queue("pre-restart", new Runnable() { public void run() {
+            //set by shutdown - clear it so the entity starts cleanly. Does the indicator bring any value at all?
+            ServiceNotUpLogic.clearNotUpIndicator(BrooklynNodeImpl.this, SHUTDOWN.getName());
+        }});
+    }
+
+    private void shutdownGracefully() {
+        // Shutdown only if accessible: any of stop_* could have already been called.
+        // Don't check serviceUp=true because stop() will already have set serviceUp=false && expectedState=stopping
+        if (Boolean.TRUE.equals(getAttribute(BrooklynNode.WEB_CONSOLE_ACCESSIBLE))) {
+            queueShutdownTask();
+            queueWaitExitTask();
+        } else {
+            log.info("Skipping graceful shutdown call, because web-console not up for {}", this);
+        }
+    }
+
+    private void queueWaitExitTask() {
+        //give time to the process to die gracefully after closing the shutdown call
+        DynamicTasks.queue(Tasks.builder().name("wait for graceful stop").body(new Runnable() {
+            @Override
+            public void run() {
+                DynamicTasks.markInessential();
+                boolean cleanExit = Repeater.create()
+                    .until(new Callable<Boolean>() {
+                        @Override
+                        public Boolean call() throws Exception {
+                            return !getDriver().isRunning();
+                        }
+                    })
+                    .backoffTo(Duration.ONE_SECOND)
+                    .limitTimeTo(Duration.ONE_MINUTE)
+                    .run();
+                if (!cleanExit) {
+                    log.warn("Tenant " + this + " didn't stop cleanly after shutdown. Timeout waiting for process exit.");
+                }
+            }
+        }).build());
+    }
+
+    @Override
+    protected void postStop() {
+        super.postStop();
+        if (isMachineStopped()) {
+            // Don't unmanage in entity's task context as it will self-cancel the task. Wait for the stop effector to complete (and all parent entity tasks).
+            // If this is not enough (still getting Caused by: java.util.concurrent.CancellationException: null) then
+            // we could wait for BrooklynTaskTags.getTasksInEntityContext(ExecutionManager, this).isEmpty();
+            Task<?> stopEffectorTask = BrooklynTaskTags.getClosestEffectorTask(Tasks.current(), Startable.STOP);
+            Task<?> topEntityTask = getTopEntityTask(stopEffectorTask);
+            getManagementContext().getExecutionManager().submit(new UnmanageTask(topEntityTask, this));
+        }
+    }
+
+    private Task<?> getTopEntityTask(Task<?> stopEffectorTask) {
+        Entity context = BrooklynTaskTags.getContextEntity(stopEffectorTask);
+        Task<?> topTask = stopEffectorTask;
+        while (true) {
+            Task<?> parentTask = topTask.getSubmittedByTask();
+            Entity parentContext = BrooklynTaskTags.getContextEntity(parentTask);
+            if (parentTask == null || parentContext != context) {
+                return topTask;
+            } else {
+                topTask = parentTask;
+            }
+        }
+    }
+
+    private boolean isMachineStopped() {
+        // Don't rely on effector parameters, check if there is still a machine running.
+        // If the entity was previously stopped with STOP_MACHINE_MODE=StopMode.NEVER
+        // and a second time with STOP_MACHINE_MODE=StopMode.IF_NOT_STOPPED, then the
+        // machine is still running, but there is no deterministic way to infer this from
+        // the parameters alone.
+        return Locations.findUniqueSshMachineLocation(this.getLocations()).isAbsent();
+    }
+
+    private void queueShutdownTask() {
+        ConfigBag stopParameters = BrooklynTaskTags.getCurrentEffectorParameters();
+        ConfigBag shutdownParameters;
+        if (stopParameters != null) {
+            shutdownParameters = ConfigBag.newInstanceCopying(stopParameters);
+        } else {
+            shutdownParameters = ConfigBag.newInstance();
+        }
+        shutdownParameters.putIfAbsent(ShutdownEffector.REQUEST_TIMEOUT, Duration.ONE_MINUTE);
+        shutdownParameters.putIfAbsent(ShutdownEffector.FORCE_SHUTDOWN_ON_ERROR, Boolean.TRUE);
+        TaskAdaptable<Void> shutdownTask = Effectors.invocation(this, SHUTDOWN, shutdownParameters);
+        //Mark inessential so that even if it fails the process stop task will run afterwards to clean up.
+        TaskTags.markInessential(shutdownTask);
+        DynamicTasks.queue(shutdownTask);
+    }
+
+    public static class DeployBlueprintEffectorBody extends EffectorBody<String> implements DeployBlueprintEffector {
+        public static final Effector<String> DEPLOY_BLUEPRINT = Effectors.effector(BrooklynNode.DEPLOY_BLUEPRINT).impl(new DeployBlueprintEffectorBody()).build();
+        
+        // TODO support YAML parsing
+        // TODO define a new type YamlMap for the config key which supports coercing from string and from map
+        @SuppressWarnings("unchecked")
+        public static Map<String,Object> asMap(ConfigBag parameters, ConfigKey<?> key) {
+            Object v = parameters.getStringKey(key.getName());
+            if (v==null || (v instanceof String && Strings.isBlank((String)v)))
+                return null;
+            if (v instanceof Map) 
+                return (Map<String, Object>) v;
+            
+            if (v instanceof String) {
+                // TODO ideally, parse YAML 
+                return new Gson().fromJson((String)v, Map.class);
+            }
+            throw new IllegalArgumentException("Invalid "+JavaClassNames.simpleClassName(v)+" value for "+key+": "+v);
+        }
+        
+        @Override
+        public String call(ConfigBag parameters) {
+            if (log.isDebugEnabled())
+                log.debug("Deploying blueprint to "+entity()+": "+parameters);
+            String plan = extractPlanYamlString(parameters);
+            return submitPlan(plan);
+        }
+
+        protected String extractPlanYamlString(ConfigBag parameters) {
+            Object planRaw = parameters.getStringKey(BLUEPRINT_CAMP_PLAN.getName());
+            if (planRaw instanceof String && Strings.isBlank((String)planRaw)) planRaw = null;
+            
+            String url = parameters.get(BLUEPRINT_TYPE);
+            if (url!=null && planRaw!=null)
+                throw new IllegalArgumentException("Cannot supply both plan and url");
+            if (url==null && planRaw==null)
+                throw new IllegalArgumentException("Must supply plan or url");
+            
+            Map<String, Object> config = asMap(parameters, BLUEPRINT_CONFIG);
+            
+            if (planRaw==null) {
+                planRaw = Jsonya.at("services").list().put("serviceType", url).putIfNotNull("brooklyn.config", config).getRootMap();
+            } else { 
+                if (config!=null)
+                    throw new IllegalArgumentException("Cannot supply plan with config");
+            }
+            
+            // planRaw might be a yaml string, or a map; if a map, convert to string
+            if (planRaw instanceof Map)
+                planRaw = Jsonya.of((Map<?,?>)planRaw).toString();
+            if (!(planRaw instanceof String))
+                throw new IllegalArgumentException("Invalid "+JavaClassNames.simpleClassName(planRaw)+" value for CAMP plan: "+planRaw);
+            
+            // now *all* the data is in planRaw; that is what will be submitted
+            return (String)planRaw;
+        }
+        
+        @VisibleForTesting
+        // Integration test for this in BrooklynNodeIntegrationTest in this project doesn't use this method,
+        // but a Unit test for this does, in DeployBlueprintTest -- but in the REST server project (since it runs against local) 
+        public String submitPlan(final String plan) {
+            final MutableMap<String, String> headers = MutableMap.of(com.google.common.net.HttpHeaders.CONTENT_TYPE, "application/yaml");
+            final AtomicReference<byte[]> response = new AtomicReference<byte[]>();
+            Repeater.create()
+                .every(Duration.ONE_SECOND)
+                .backoffTo(Duration.FIVE_SECONDS)
+                .limitTimeTo(Duration.minutes(5))
+                .repeat(Runnables.doNothing())
+                .rethrowExceptionImmediately()
+                .until(new Callable<Boolean>() {
+                    @Override
+                    public Boolean call() {
+                        HttpToolResponse result = ((BrooklynNode)entity()).http()
+                                //will throw on non-{2xx, 403} response
+                                .responseSuccess(Predicates.<Integer>or(ResponseCodePredicates.success(), Predicates.equalTo(HttpStatus.SC_FORBIDDEN)))
+                                .post("/v1/applications", headers, plan.getBytes());
+                        if (result.getResponseCode() == HttpStatus.SC_FORBIDDEN) {
+                            log.debug("Remote is not ready to accept requests, response is " + result.getResponseCode());
+                            return false;
+                        } else {
+                            byte[] content = result.getContent();
+                            response.set(content);
+                            return true;
+                        }
+                    }
+                })
+                .runRequiringTrue();
+            return (String)new Gson().fromJson(new String(response.get()), Map.class).get("entityId");
+        }
+    }
+
+    public static class ShutdownEffectorBody extends EffectorBody<Void> implements ShutdownEffector {
+        public static final Effector<Void> SHUTDOWN = Effectors.effector(BrooklynNode.SHUTDOWN).impl(new ShutdownEffectorBody()).build();
+
+        @Override
+        public Void call(ConfigBag parameters) {
+            MutableMap<String, String> formParams = MutableMap.of();
+            Lifecycle initialState = entity().getAttribute(Attributes.SERVICE_STATE_ACTUAL);
+            ServiceStateLogic.setExpectedState(entity(), Lifecycle.STOPPING);
+            for (ConfigKey<?> k: new ConfigKey<?>[] { STOP_APPS_FIRST, FORCE_SHUTDOWN_ON_ERROR, SHUTDOWN_TIMEOUT, REQUEST_TIMEOUT, DELAY_FOR_HTTP_RETURN })
+                formParams.addIfNotNull(k.getName(), toNullableString(parameters.get(k)));
+            try {
+                log.debug("Shutting down "+entity()+" with "+formParams);
+                HttpToolResponse resp = ((BrooklynNode)entity()).http()
+                    .post("/v1/server/shutdown",
+                        ImmutableMap.of("Brooklyn-Allow-Non-Master-Access", "true"),
+                        formParams);
+                if (resp.getResponseCode() != HttpStatus.SC_NO_CONTENT) {
+                    throw new IllegalStateException("Response code "+resp.getResponseCode());
+                }
+            } catch (Exception e) {
+                Exceptions.propagateIfFatal(e);
+                throw new PropagatedRuntimeException("Error shutting down remote node "+entity()+" (in state "+initialState+"): "+Exceptions.collapseText(e), e);
+            }
+            ServiceNotUpLogic.updateNotUpIndicator(entity(), SHUTDOWN.getName(), "Shutdown of remote node has completed successfuly");
+            return null;
+        }
+
+        private static String toNullableString(Object obj) {
+            if (obj == null) {
+                return null;
+            } else {
+                return obj.toString();
+            }
+        }
+
+    }
+
+    public static class StopNodeButLeaveAppsEffectorBody extends EffectorBody<Void> implements StopNodeButLeaveAppsEffector {
+        public static final Effector<Void> STOP_NODE_BUT_LEAVE_APPS = Effectors.effector(BrooklynNode.STOP_NODE_BUT_LEAVE_APPS).impl(new StopNodeButLeaveAppsEffectorBody()).build();
+
+        @Override
+        public Void call(ConfigBag parameters) {
+            Duration timeout = parameters.get(TIMEOUT);
+
+            ConfigBag stopParameters = ConfigBag.newInstanceCopying(parameters);
+            stopParameters.put(ShutdownEffector.STOP_APPS_FIRST, Boolean.FALSE);
+            stopParameters.putIfAbsent(ShutdownEffector.SHUTDOWN_TIMEOUT, timeout);
+            stopParameters.putIfAbsent(ShutdownEffector.REQUEST_TIMEOUT, timeout);
+            DynamicTasks.queue(Effectors.invocation(entity(), STOP, stopParameters)).asTask().getUnchecked();
+            return null;
+        }
+    }
+
+    public static class StopNodeAndKillAppsEffectorBody extends EffectorBody<Void> implements StopNodeAndKillAppsEffector {
+        public static final Effector<Void> STOP_NODE_AND_KILL_APPS = Effectors.effector(BrooklynNode.STOP_NODE_AND_KILL_APPS).impl(new StopNodeAndKillAppsEffectorBody()).build();
+
+        @Override
+        public Void call(ConfigBag parameters) {
+            Duration timeout = parameters.get(TIMEOUT);
+
+            ConfigBag stopParameters = ConfigBag.newInstanceCopying(parameters);
+            stopParameters.put(ShutdownEffector.STOP_APPS_FIRST, Boolean.TRUE);
+            stopParameters.putIfAbsent(ShutdownEffector.SHUTDOWN_TIMEOUT, timeout);
+            stopParameters.putIfAbsent(ShutdownEffector.REQUEST_TIMEOUT, timeout);
+            DynamicTasks.queue(Effectors.invocation(entity(), STOP, stopParameters)).asTask().getUnchecked();
+            return null;
+        }
+    }
+
+    public List<String> getClasspath() {
+        List<String> classpath = getConfig(CLASSPATH);
+        if (classpath == null || classpath.isEmpty()) {
+            classpath = getManagementContext().getConfig().getConfig(CLASSPATH);
+        }
+        return classpath;
+    }
+    
+    protected List<String> getEnabledHttpProtocols() {
+        return getAttribute(ENABLED_HTTP_PROTOCOLS);
+    }
+    
+    protected boolean isHttpProtocolEnabled(String protocol) {
+        List<String> protocols = getAttribute(ENABLED_HTTP_PROTOCOLS);
+        for (String contender : protocols) {
+            if (protocol.equalsIgnoreCase(contender)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    @Override
+    protected void connectSensors() {
+        super.connectSensors();
+        
+        // TODO what sensors should we poll?
+        ConfigToAttributes.apply(this);
+
+        URI webConsoleUri;
+        if (isHttpProtocolEnabled("http")) {
+            int port = getConfig(PORT_MAPPER).apply(getAttribute(HTTP_PORT));
+            HostAndPort accessible = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, port);
+            webConsoleUri = URI.create(String.format("http://%s:%s", accessible.getHostText(), accessible.getPort()));
+        } else if (isHttpProtocolEnabled("https")) {
+            int port = getConfig(PORT_MAPPER).apply(getAttribute(HTTPS_PORT));
+            HostAndPort accessible = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, port);
+            webConsoleUri = URI.create(String.format("https://%s:%s", accessible.getHostText(), accessible.getPort()));
+        } else {
+            // web-console is not enabled
+            webConsoleUri = null;
+        }
+        setAttribute(WEB_CONSOLE_URI, webConsoleUri);
+
+        if (webConsoleUri != null) {
+            httpFeed = HttpFeed.builder()
+                    .entity(this)
+                    .period(getConfig(POLL_PERIOD))
+                    .baseUri(webConsoleUri)
+                    .credentialsIfNotNull(getConfig(MANAGEMENT_USER), getConfig(MANAGEMENT_PASSWORD))
+                    .poll(new HttpPollConfig<Boolean>(WEB_CONSOLE_ACCESSIBLE)
+                            .suburl("/v1/server/healthy")
+                            .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.cast(Boolean.class)))
+                            //if using an old distribution the path doesn't exist, but at least the instance is responding
+                            .onFailure(HttpValueFunctions.responseCodeEquals(404))
+                            .setOnException(false))
+                    .poll(new HttpPollConfig<ManagementNodeState>(MANAGEMENT_NODE_STATE)
+                            .suburl("/v1/server/ha/state")
+                            .onSuccess(Functionals.chain(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.cast(String.class)), Enums.fromStringFunction(ManagementNodeState.class)))
+                            .setOnFailureOrException(null))
+                    // TODO sensors for load, size, etc
+                    .build();
+
+            if (!Lifecycle.RUNNING.equals(getAttribute(SERVICE_STATE_ACTUAL))) {
+                // TODO when updating the map, if it would change from empty to empty on a successful run (see in nginx)
+                ServiceNotUpLogic.updateNotUpIndicator(this, WEB_CONSOLE_ACCESSIBLE, "No response from the web console yet");
+            }
+            addEnricher(Enrichers.builder().updatingMap(Attributes.SERVICE_NOT_UP_INDICATORS)
+                .from(WEB_CONSOLE_ACCESSIBLE)
+                .computing(Functionals.ifNotEquals(true).value("URL where Brooklyn listens is not answering correctly") )
+                .build());
+        } else {
+            connectServiceUpIsRunning();
+        }
+    }
+    
+    @Override
+    protected void disconnectSensors() {
+        super.disconnectSensors();
+        disconnectServiceUpIsRunning();
+        if (httpFeed != null) httpFeed.stop();
+    }
+
+    @Override
+    public EntityHttpClient http() {
+        return new EntityHttpClientImpl(this, BrooklynNode.WEB_CONSOLE_URI);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java
new file mode 100644
index 0000000..3ba710a
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java
@@ -0,0 +1,394 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static java.lang.String.format;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.InputStream;
+import java.net.InetAddress;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode.ExistingFileBehaviour;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.drivers.downloads.DownloadSubstituters;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.file.ArchiveBuilder;
+import org.apache.brooklyn.util.core.file.ArchiveUtils;
+import org.apache.brooklyn.util.core.internal.ssh.SshTool;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.net.Networking;
+import org.apache.brooklyn.util.net.Urls;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.ssh.BashCommands;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.apache.brooklyn.util.text.Strings;
+
+import com.google.common.base.Objects;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+
+public class BrooklynNodeSshDriver extends JavaSoftwareProcessSshDriver implements BrooklynNodeDriver {
+    
+    public BrooklynNodeSshDriver(BrooklynNodeImpl entity, SshMachineLocation machine) {
+        super(entity, machine);
+    }
+
+    @Override
+    public BrooklynNodeImpl getEntity() {
+        return (BrooklynNodeImpl) super.getEntity();
+    }
+
+    public String getBrooklynHome() {
+        return getRunDir();
+    }
+
+    @Override
+    protected String getLogFileLocation() {
+        return Os.mergePathsUnix(getRunDir(), "console");
+    }
+    
+    protected String getPidFile() {
+        return Os.mergePathsUnix(getRunDir(), "pid_java");
+    }
+    
+    @Override
+    protected String getInstallLabelExtraSalt() {
+        String downloadUrl = entity.getConfig(BrooklynNode.DOWNLOAD_URL);
+        String uploadUrl = entity.getConfig(BrooklynNode.DISTRO_UPLOAD_URL);
+        if (Objects.equal(downloadUrl, BrooklynNode.DOWNLOAD_URL.getConfigKey().getDefaultValue()) &&
+                Objects.equal(uploadUrl, BrooklynNode.DISTRO_UPLOAD_URL.getDefaultValue())) {
+            // if both are at the default value, then no salt
+            return null;
+        }
+        return Identifiers.makeIdFromHash(Objects.hashCode(downloadUrl, uploadUrl));
+    }
+
+    @Override
+    public void preInstall() {
+        resolver = Entities.newDownloader(this);
+        String subpath = entity.getConfig(BrooklynNode.SUBPATH_IN_ARCHIVE);
+        if (subpath==null) {
+            // assume the dir name is `basename-VERSION` where download link is `basename-VERSION-dist.tar.gz`
+            String uploadUrl = entity.getConfig(BrooklynNode.DISTRO_UPLOAD_URL);
+            String origDownloadName = uploadUrl;
+            if (origDownloadName==null) 
+                origDownloadName = entity.getAttribute(BrooklynNode.DOWNLOAD_URL);
+            if (origDownloadName!=null) {
+                // BasicDownloadResolver makes it crazy hard to get the template-evaluated value of DOWNLOAD_URL
+                origDownloadName = DownloadSubstituters.substitute(origDownloadName, DownloadSubstituters.getBasicEntitySubstitutions(this));
+                origDownloadName = Urls.decode(origDownloadName);
+                origDownloadName = Urls.getBasename(origDownloadName);
+                String downloadName = origDownloadName;
+                downloadName = Strings.removeFromEnd(downloadName, ".tar.gz");
+                downloadName = Strings.removeFromEnd(downloadName, ".tgz");
+                downloadName = Strings.removeFromEnd(downloadName, ".zip");
+                if (!downloadName.equals(origDownloadName)) {
+                    downloadName = Strings.removeFromEnd(downloadName, "-dist");
+                    subpath = downloadName;
+                }
+            }
+        }
+        if (subpath==null) subpath = format("brooklyn-dist-%s", getVersion());
+        setExpandedInstallDir(Os.mergePaths(getInstallDir(), resolver.getUnpackedDirectoryName(subpath)));
+    }
+
+    @Override
+    public void clearInstallDir() {
+        super.setInstallDir(null);
+        super.setExpandedInstallDir(null);
+    }
+    
+    @Override
+    public void install() {
+        String uploadUrl = entity.getConfig(BrooklynNode.DISTRO_UPLOAD_URL);
+        
+        // Need to explicitly give file, because for snapshot URLs you don't get a clean filename from the URL.
+        // This filename is used to generate the first URL to try: [BROOKLYN_VERSION_BELOW]
+        // file://$HOME/.brooklyn/repository/BrooklynNode/0.8.0-SNAPSHOT/brooklynnode-0.8.0-snapshot.tar.gz
+        // (DOWNLOAD_URL overrides this and has a default which comes from maven)
+        List<String> urls = resolver.getTargets();
+        String saveAs = resolver.getFilename();
+        
+        newScript("createInstallDir")
+                .body.append("mkdir -p "+getInstallDir())
+                .failOnNonZeroResultCode()
+                .execute();
+
+        List<String> commands = Lists.newArrayList();
+        // TODO use machine.installTo ... but that only works w a single location currently
+        if (uploadUrl != null) {
+            // Only upload if not already installed
+            boolean exists = newScript("checkIfInstalled")
+                    .body.append("cd "+getInstallDir(), "test -f BROOKLYN")
+                    .execute() == 0;
+            if (!exists) {
+                InputStream distroStream = resource.getResourceFromUrl(uploadUrl);
+                getMachine().copyTo(distroStream, getInstallDir()+"/"+saveAs);
+            }
+        } else {
+            commands.addAll(BashCommands.commandsToDownloadUrlsAs(urls, saveAs));
+        }
+        commands.add(BashCommands.INSTALL_TAR);
+        commands.add("tar xzfv " + saveAs);
+        
+        newScript(INSTALLING).
+                failOnNonZeroResultCode().
+                body.append(commands).execute();
+    }
+
+    @Override
+    public void customize() {
+        newScript(CUSTOMIZING)
+                .failOnNonZeroResultCode()
+                .body.append(
+                        // workaround for AMP distribution placing everything in the root of this archive, but
+                        // brooklyn distribution placing everything in a subdirectory: check to see if subdirectory
+                        // with expected name exists; symlink to same directory if it doesn't
+                        // FIXME remove when all downstream usages don't use this
+                        format("[ -d %1$s ] || ln -s . %1$s", getExpandedInstallDir(), getExpandedInstallDir()),
+                        
+                        // previously we only copied bin,conf and set BROOKLYN_HOME to the install dir;
+                        // but that does not play nicely if installing dists other than brooklyn
+                        // (such as what is built by our artifact)  
+                        format("cp -R %s/* .", getExpandedInstallDir()),
+                        "mkdir -p ./lib/")
+                .execute();
+        
+        SshMachineLocation machine = getMachine();
+        BrooklynNode entity = getEntity();
+        
+        String brooklynGlobalPropertiesRemotePath = entity.getConfig(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_REMOTE_PATH);
+        String brooklynGlobalPropertiesContents = entity.getConfig(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_CONTENTS);
+        String brooklynGlobalPropertiesUri = entity.getConfig(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_URI);
+
+        String brooklynLocalPropertiesRemotePath = processTemplateContents(entity.getConfig(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_REMOTE_PATH));
+        String brooklynLocalPropertiesContents = entity.getConfig(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_CONTENTS);
+        String brooklynLocalPropertiesUri = entity.getConfig(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_URI);
+
+        String brooklynCatalogRemotePath = entity.getConfig(BrooklynNode.BROOKLYN_CATALOG_REMOTE_PATH);
+        String brooklynCatalogContents = entity.getConfig(BrooklynNode.BROOKLYN_CATALOG_CONTENTS);
+        String brooklynCatalogUri = entity.getConfig(BrooklynNode.BROOKLYN_CATALOG_URI);
+
+        // Override the ~/.brooklyn/brooklyn.properties if required
+        if (brooklynGlobalPropertiesContents != null || brooklynGlobalPropertiesUri != null) {
+            ExistingFileBehaviour onExisting = entity.getConfig(BrooklynNode.ON_EXISTING_PROPERTIES_FILE);
+            Integer checkExists = DynamicTasks.queue(SshEffectorTasks.ssh("ls \""+brooklynGlobalPropertiesRemotePath+"\"").allowingNonZeroExitCode()).get();
+            boolean doUpload = true;
+            if (checkExists==0) {
+                switch (onExisting) {
+                case USE_EXISTING: doUpload = false; break;
+                case OVERWRITE: break;
+                case DO_NOT_USE: 
+                    throw new IllegalStateException("Properties file "+brooklynGlobalPropertiesContents+" already exists and "+
+                        "even though it is not being used, content for it was supplied");
+                case FAIL: 
+                    throw new IllegalStateException("Properties file "+brooklynGlobalPropertiesContents+" already exists and "+
+                        BrooklynNode.ON_EXISTING_PROPERTIES_FILE+" response is to fail");
+                default:
+                    throw new IllegalStateException("Properties file "+brooklynGlobalPropertiesContents+" already exists and "+
+                        BrooklynNode.ON_EXISTING_PROPERTIES_FILE+" response "+onExisting+" is unknown");
+                }
+            }
+            if (onExisting==ExistingFileBehaviour.DO_NOT_USE) {
+                log.warn("Global properties supplied when told not to use them; no global properties exists, so it will be installed, but it will not be used.");
+            }
+            if (doUpload)
+                uploadFileContents(brooklynGlobalPropertiesContents, brooklynGlobalPropertiesUri, brooklynGlobalPropertiesRemotePath);
+        }
+        
+        // Upload a local-brooklyn.properties if required
+        if (brooklynLocalPropertiesContents != null || brooklynLocalPropertiesUri != null) {
+            uploadFileContents(brooklynLocalPropertiesContents, brooklynLocalPropertiesUri, brooklynLocalPropertiesRemotePath);
+        }
+
+        // Override the ~/.brooklyn/catalog.xml if required
+        if (brooklynCatalogContents != null || brooklynCatalogUri != null) {
+            uploadFileContents(brooklynCatalogContents, brooklynCatalogUri, brooklynCatalogRemotePath);
+        }
+
+        // Copy additional resources to the server
+        for (Map.Entry<String,String> entry : getEntity().getAttribute(BrooklynNode.COPY_TO_RUNDIR).entrySet()) {
+            Map<String, String> substitutions = ImmutableMap.of("RUN", getRunDir());
+            String localResource = entry.getKey();
+            String remotePath = entry.getValue();
+            String resolvedRemotePath = remotePath;
+            for (Map.Entry<String,String> substitution : substitutions.entrySet()) {
+                String key = substitution.getKey();
+                String val = substitution.getValue();
+                resolvedRemotePath = resolvedRemotePath.replace("${"+key+"}", val).replace("$"+key, val);
+            }
+            machine.copyTo(MutableMap.of("permissions", "0600"), resource.getResourceFromUrl(localResource), resolvedRemotePath);
+        }
+
+        for (String entry : getEntity().getClasspath()) {
+            // If a local folder, then create archive from contents first
+            if (Urls.isDirectory(entry)) {
+                File jarFile = ArchiveBuilder.jar().addDirContentsAt(new File(entry), "").create();
+                entry = jarFile.getAbsolutePath();
+            }
+
+            // Determine filename
+            String destFile = entry.contains("?") ? entry.substring(0, entry.indexOf('?')) : entry;
+            destFile = destFile.substring(destFile.lastIndexOf('/') + 1);
+
+            ArchiveUtils.deploy(MutableMap.<String, Object>of(), entry, machine, getRunDir(), Os.mergePaths(getRunDir(), "lib"), destFile);
+        }
+        
+        String cmd = entity.getConfig(BrooklynNode.EXTRA_CUSTOMIZATION_SCRIPT);
+        if (Strings.isNonBlank(cmd)) {
+            DynamicTasks.queueIfPossible( SshEffectorTasks.ssh(cmd).summary("Bespoke BrooklynNode customization script")
+                .requiringExitCodeZero() )
+                .orSubmitAndBlock(getEntity());
+        }
+    }
+
+    @SuppressWarnings("deprecation")
+    @Override
+    public void launch() {
+        String app = getEntity().getAttribute(BrooklynNode.APP);
+        String locations = getEntity().getAttribute(BrooklynNode.LOCATIONS);
+        boolean hasLocalBrooklynProperties = getEntity().getConfig(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_CONTENTS) != null || getEntity().getConfig(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_URI) != null;
+        String localBrooklynPropertiesPath = processTemplateContents(getEntity().getConfig(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_REMOTE_PATH));
+        InetAddress bindAddress = getEntity().getAttribute(BrooklynNode.WEB_CONSOLE_BIND_ADDRESS);
+        InetAddress publicAddress = getEntity().getAttribute(BrooklynNode.WEB_CONSOLE_PUBLIC_ADDRESS);
+
+        String cmd = entity.getConfig(BrooklynNode.LAUNCH_COMMAND);
+        if (Strings.isBlank(cmd)) cmd = "./bin/brooklyn";
+        cmd = "nohup " + cmd + " launch";
+        if (app != null) {
+            cmd += " --app "+app;
+        }
+        if (locations != null) {
+            cmd += " --locations "+locations;
+        }
+        if (entity.getConfig(BrooklynNode.ON_EXISTING_PROPERTIES_FILE)==ExistingFileBehaviour.DO_NOT_USE) {
+            cmd += " --noGlobalBrooklynProperties";
+        }
+        if (hasLocalBrooklynProperties) {
+            cmd += " --localBrooklynProperties "+localBrooklynPropertiesPath;
+        }
+        Integer webPort = null;
+        if (getEntity().isHttpProtocolEnabled("http")) {
+            webPort = getEntity().getAttribute(BrooklynNode.HTTP_PORT);
+            Networking.checkPortsValid(ImmutableMap.of("webPort", webPort));
+        } else if (getEntity().isHttpProtocolEnabled("https")) {
+            webPort = getEntity().getAttribute(BrooklynNode.HTTPS_PORT);
+            Networking.checkPortsValid(ImmutableMap.of("webPort", webPort));
+        }
+        if (webPort!=null) {
+            cmd += " --port "+webPort;
+        } else if (getEntity().getEnabledHttpProtocols().isEmpty()) {
+            // TODO sensors will probably not work in this mode
+            cmd += " --noConsole";
+        } else {
+            throw new IllegalStateException("Unknown web protocol in "+BrooklynNode.ENABLED_HTTP_PROTOCOLS+" "
+                + "("+getEntity().getEnabledHttpProtocols()+"); expecting 'http' or 'https'");
+        }
+        
+        if (bindAddress != null) {
+            cmd += " --bindAddress "+bindAddress.getHostAddress();
+        }
+        if (publicAddress != null) {
+            cmd += " --publicAddress "+publicAddress.getHostName();
+        }
+        if (getEntity().getAttribute(BrooklynNode.NO_WEB_CONSOLE_AUTHENTICATION)) {
+            cmd += " --noConsoleSecurity";
+        }
+        if (Strings.isNonBlank(getEntity().getConfig(BrooklynNode.EXTRA_LAUNCH_PARAMETERS))) {
+            cmd += " "+getEntity().getConfig(BrooklynNode.EXTRA_LAUNCH_PARAMETERS);
+        }
+        cmd += format(" >> %s/console 2>&1 </dev/null &", getRunDir());
+        
+        log.info("Starting brooklyn on {} using command {}", getMachine(), cmd);
+        
+        // relies on brooklyn script creating pid file
+        newScript(ImmutableMap.of("usePidFile", 
+                entity.getConfig(BrooklynNode.LAUNCH_COMMAND_CREATES_PID_FILE) ? false : getPidFile()), 
+            LAUNCHING).
+            body.append(
+                format("export BROOKLYN_CLASSPATH=%s", getRunDir()+"/lib/\"*\""),
+                format("export BROOKLYN_HOME=%s", getBrooklynHome()),
+                format(cmd)
+        ).failOnNonZeroResultCode().execute();
+    }
+
+    @Override
+    public boolean isRunning() {
+        Map<String,String> flags = ImmutableMap.of("usePidFile", getPidFile());
+        int result = newScript(flags, CHECK_RUNNING).execute();
+        return result == 0;
+    }
+
+    @Override
+    public void stop() {
+        Map<String,String> flags = ImmutableMap.of("usePidFile", getPidFile());
+        newScript(flags, STOPPING).execute();
+    }
+
+    @Override
+    public void kill() {
+        Map<String,String> flags = ImmutableMap.of("usePidFile", getPidFile());
+        newScript(flags, KILLING).execute();
+    }
+    
+    @Override
+    public Map<String, String> getShellEnvironment() {
+        Map<String, String> orig = super.getShellEnvironment();
+        String origClasspath = orig.get("CLASSPATH");
+        String newClasspath = (origClasspath == null ? "" : origClasspath+":") + 
+                getRunDir()+"/conf/" + ":" +
+                getRunDir()+"/lib/\"*\"";
+        Map<String,String> results = new LinkedHashMap<String,String>();
+        results.putAll(orig);
+        results.put("BROOKLYN_CLASSPATH", newClasspath);
+        results.put("BROOKLYN_HOME", getBrooklynHome());
+        results.put("RUN", getRunDir());
+        return results;
+    }
+    
+    private void uploadFileContents(String contents, String alternativeUri, String remotePath) {
+        checkNotNull(remotePath, "remotePath");
+        SshMachineLocation machine = getMachine();
+        String tempRemotePath = String.format("%s/upload.tmp", getRunDir());
+
+        if (contents == null && alternativeUri == null) {
+            throw new IllegalStateException("No contents supplied for file " + remotePath);
+        }
+        InputStream stream = contents != null
+                ? new ByteArrayInputStream(contents.getBytes())
+                : resource.getResourceFromUrl(alternativeUri);
+        Map<String, String> flags = MutableMap.of(SshTool.PROP_PERMISSIONS.getName(), "0600");
+        machine.copyTo(flags, stream, tempRemotePath);
+        newScript(CUSTOMIZING)
+                .failOnNonZeroResultCode()
+                .body.append(
+                        format("mkdir -p %s", remotePath.subSequence(0, remotePath.lastIndexOf("/"))),
+                        format("cp -p %s %s", tempRemotePath, remotePath),
+                        format("rm -f %s", tempRemotePath))
+                .execute();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/EntityHttpClient.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/EntityHttpClient.java b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/EntityHttpClient.java
new file mode 100644
index 0000000..dd2db70
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/brooklynnode/EntityHttpClient.java
@@ -0,0 +1,93 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.brooklynnode;
+
+import java.util.Map;
+
+import org.apache.brooklyn.util.core.http.HttpTool;
+import org.apache.brooklyn.util.core.http.HttpToolResponse;
+
+import com.google.common.base.Predicate;
+import com.google.common.base.Predicates;
+import com.google.common.collect.Range;
+
+/**
+ * Helpful methods for making HTTP requests to {@link BrooklynNode} entities.
+ */
+public interface EntityHttpClient {
+    public static class ResponseCodePredicates {
+        private static class ResponseCodeHealthyPredicate implements Predicate<Integer> {
+            @Override
+            public boolean apply(Integer input) {
+                return HttpTool.isStatusCodeHealthy(input);
+            }
+        }
+        public static Predicate<Integer> informational() {return Range.closed(100, 199);}
+        public static Predicate<Integer> success() {return new ResponseCodeHealthyPredicate();}
+        public static Predicate<Integer> redirect() {return Range.closed(300, 399);}
+        public static Predicate<Integer> clientError() {return Range.closed(400, 499);}
+        public static Predicate<Integer> serverError() {return Range.closed(500, 599);}
+        public static Predicate<Integer> invalid() {return Predicates.or(Range.atMost(99), Range.atLeast(600));}
+    }
+
+    /**
+     * @return An HTTP client builder configured to access the {@link
+     *         BrooklynNode#WEB_CONSOLE_URI web console URI} at the
+     *         given entity, or null if the entity has no URI.
+     */
+    public HttpTool.HttpClientBuilder getHttpClientForBrooklynNode();
+
+    /**
+     * Configure which response codes are treated as successful
+     * @param successPredicate A predicate which returns true is the response code is acceptable
+     * @return this
+     */
+    public EntityHttpClient responseSuccess(Predicate<Integer> responseSuccess);
+
+    /**
+     * Makes an HTTP GET to a Brooklyn node entity.
+     * @param path Relative path to resource on server, e.g v1/catalog
+     * @return The server's response
+     */
+    public HttpToolResponse get(String path);
+
+    /**
+     * Makes an HTTP POST to a Brooklyn node entity.
+     * @param path Relative path to resource on server, e.g v1/catalog
+     * @param body byte array of serialized JSON to attach to the request
+     * @return The server's response
+     */
+    public HttpToolResponse post(String path, Map<String, String> headers, byte[] body);
+
+    /**
+     * Makes an HTTP POST to a Brooklyn node entity.
+     * @param path Relative path to resource on server, e.g v1/catalog
+     * @param formParams The parameters to send in a x-www-form-urlencoded format
+     * @return The server's response
+     */
+    public HttpToolResponse post(String path, Map<String, String> headers, Map<String, String> formParams);
+
+    /**
+     * Makes an HTTP DELETE to a Brooklyn node entity.
+     * @param path Relative path to resource on server, e.g v1/catalog
+     * @return The server's response
+     */
+    public HttpToolResponse delete(String path, Map<String, String> headers);
+
+}


[07/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessAndChildrenIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessAndChildrenIntegrationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessAndChildrenIntegrationTest.java
new file mode 100644
index 0000000..3298a2f
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/VanillaSoftwareProcessAndChildrenIntegrationTest.java
@@ -0,0 +1,197 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import java.util.Collections;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.ChildStartableMode;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.core.ResourceUtils;
+import org.apache.brooklyn.util.javalang.JavaClassNames;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Stopwatch;
+
+public class VanillaSoftwareProcessAndChildrenIntegrationTest {
+
+    // TODO Why are these tests so slow? Even when the sleep time was 3 seconds instead of 10, they would still take about 10 seconds.
+    
+    // Note that tests run by jenkins can be extremely time-sensitive.
+    // e.g. http://brooklyn.builds.cloudsoftcorp.com/job/Brooklyn-Master-Integration/io.brooklyn$brooklyn-software-base/217/testReport/junit/brooklyn.entity.basic/VanillaSoftwareProcessAndChildrenIntegrationTest/testModeBackground/
+    //      shows a 5 second difference when in background mode, whereas the test originally asserted a difference of <= 1.
+    // Therefore increasing time that tests will take, but decreasing the sensitivity so we don't get such false-negatives.
+    
+    private static final Logger log = LoggerFactory.getLogger(VanillaSoftwareProcessAndChildrenIntegrationTest.class);
+
+    private static final int PARENT_TASK_SLEEP_LENGTH_SECS = 10;
+    private static final int CHILD_TASK_SLEEP_LENGTH_SECS = 10;
+    private static final int CONCURRENT_MAX_ACCEPTABLE_DIFF_SECS = PARENT_TASK_SLEEP_LENGTH_SECS - 1;
+    private static final int SEQUENTIAL_MIN_ACCEPTABLE_DIFF_SECS = PARENT_TASK_SLEEP_LENGTH_SECS - 1;
+    private static final int EARLY_RETURN_GRACE_MS = 20;
+    
+    private TestApplication app;
+    private Location localhost;
+
+    private VanillaSoftwareProcess p1;
+    private VanillaSoftwareProcess p2;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setup() {
+        app = TestApplication.Factory.newManagedInstanceForTests();
+        localhost = app.getManagementContext().getLocationRegistry().resolve("localhost");
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void shutdown() {
+        if (app != null) Entities.destroyAll(app.getManagementContext());
+    }
+
+    @Test(groups = "Integration")
+    public void testModeNone() {
+        prep(ChildStartableMode.NONE);
+        long startTime = startApp();
+
+        Assert.assertNotNull(p1.getAttribute(SoftwareProcess.RUN_DIR));
+        Assert.assertNull(p2.getAttribute(SoftwareProcess.RUN_DIR));
+        Assert.assertTrue(startTime >= PARENT_TASK_SLEEP_LENGTH_SECS*1000 - EARLY_RETURN_GRACE_MS, "startTime="+Time.makeTimeStringRounded(startTime));
+    }
+
+    @Test(groups = "Integration")
+    public void testModeForeground() {
+        prep(ChildStartableMode.FOREGROUND);        
+        long startTime = startApp();
+
+        long timediff = timediff();
+        Assert.assertTrue( Math.abs(timediff) <= CONCURRENT_MAX_ACCEPTABLE_DIFF_SECS, "should have started concurrently, not with time difference "+timediff+" ("+p1+", "+p2+")" );
+        Assert.assertTrue(startTime >= PARENT_TASK_SLEEP_LENGTH_SECS*1000 - EARLY_RETURN_GRACE_MS, "startTime="+Time.makeTimeStringRounded(startTime));
+    }
+
+    @Test(groups = "Integration")
+    public void testModeForegroundLate() {
+        prep(ChildStartableMode.FOREGROUND_LATE);        
+        long startTime = startApp();
+
+        long timediff = timediff();
+        Assert.assertTrue( timediff >= SEQUENTIAL_MIN_ACCEPTABLE_DIFF_SECS, "should have started later, not with time difference "+timediff+" ("+p1+", "+p2+")" );
+        Assert.assertTrue(startTime >= 2*PARENT_TASK_SLEEP_LENGTH_SECS*1000 - EARLY_RETURN_GRACE_MS, "startTime="+Time.makeTimeStringRounded(startTime));
+    }
+
+    @Test(groups = "Integration")
+    public void testModeBackground() {
+        prep(ChildStartableMode.BACKGROUND);
+        long startTime = startApp();
+
+        checkChildComesUpSoon();
+        
+        long timediff = timediff();
+        Assert.assertTrue( Math.abs(timediff) <= CONCURRENT_MAX_ACCEPTABLE_DIFF_SECS, "should have started concurrently, not with time difference "+timediff+" ("+p1+", "+p2+")" );
+        Assert.assertTrue(startTime >= PARENT_TASK_SLEEP_LENGTH_SECS*1000 - EARLY_RETURN_GRACE_MS, "startTime="+Time.makeTimeStringRounded(startTime));
+    }
+
+    @Test(groups = "Integration")
+    public void testModeBackgroundLate() {
+        prep(ChildStartableMode.BACKGROUND_LATE);
+        long startTime = startApp();
+
+        checkChildNotUpYet();
+        checkChildComesUpSoon();
+        
+        long timediff = timediff();
+        Assert.assertTrue( Math.abs(timediff) >= SEQUENTIAL_MIN_ACCEPTABLE_DIFF_SECS, "should have started later, not with time difference "+timediff+" ("+p1+", "+p2+")" );
+        Assert.assertTrue(startTime >= PARENT_TASK_SLEEP_LENGTH_SECS*1000 - EARLY_RETURN_GRACE_MS, "startTime="+Time.makeTimeStringRounded(startTime));
+        
+        // just to prevent warnings
+        waitForBackgroundedTasks(CHILD_TASK_SLEEP_LENGTH_SECS+1);
+        app.stop();
+        app = null;
+    }
+    
+    private long startApp() {
+        Stopwatch stopwatch = Stopwatch.createStarted();
+        app.start(Collections.singleton(localhost));
+        long result = stopwatch.elapsed(TimeUnit.MILLISECONDS);
+        log.info("Took "+Time.makeTimeStringRounded(result)+" for app.start to complete");
+        return result;
+    }
+
+    private void waitForBackgroundedTasks(int secs) {
+        // child task is backgrounded; quick and dirty way to make sure it finishes (after setting service_up)
+        Time.sleep(Duration.seconds(secs));
+    }
+
+    private void checkChildNotUpYet() {
+        Assert.assertFalse(p2.getAttribute(SoftwareProcess.SERVICE_UP));
+    }
+
+    private void checkChildComesUpSoon() {
+        Stopwatch stopwatch = Stopwatch.createStarted();
+        EntityTestUtils.assertAttributeEqualsEventually(p2, Attributes.SERVICE_UP, true);
+        log.info("Took "+Time.makeTimeStringRounded(stopwatch)+" for child-process to be service-up");
+    }
+
+    private long timediff() {
+        Long d1 = getRunTimeUtc(p1);
+        Long d2 = getRunTimeUtc(p2);
+
+        log.info("timestamps for "+JavaClassNames.callerNiceClassAndMethod(1)+" have difference "+(d2-d1));
+
+        return d2 - d1;
+    }
+
+    private Long getRunTimeUtc(VanillaSoftwareProcess p) {
+        Assert.assertNotNull(p.getAttribute(SoftwareProcess.RUN_DIR));
+        return Long.parseLong( Strings.getFirstWordAfter(new ResourceUtils(this).getResourceAsString(Os.mergePaths(p.getAttribute(SoftwareProcess.RUN_DIR), "DATE")), "utc") );
+    }
+    
+    private void prep(ChildStartableMode mode) {
+        String parentCmd = "echo utc `date +%s` > DATE ; echo human `date` >> DATE ; "
+            + "{ nohup sleep 60 & } ; echo $! > $PID_FILE ; sleep "+PARENT_TASK_SLEEP_LENGTH_SECS;
+        
+        String childCmd = "echo utc `date +%s` > DATE ; echo human `date` >> DATE ; "
+                + "{ nohup sleep 60 & } ; echo $! > $PID_FILE ; sleep "+CHILD_TASK_SLEEP_LENGTH_SECS;
+        
+        p1 = app.createAndManageChild(EntitySpec.create(VanillaSoftwareProcess.class)
+            .configure(VanillaSoftwareProcess.LAUNCH_COMMAND, parentCmd)
+            .configure(VanillaSoftwareProcess.CHILDREN_STARTABLE_MODE, mode)
+            );
+        p2 = p1.addChild(EntitySpec.create(VanillaSoftwareProcess.class)
+            .configure(VanillaSoftwareProcess.LAUNCH_COMMAND, childCmd));
+        Entities.manage(p2);
+        
+        log.info("testing "+JavaClassNames.callerNiceClassAndMethod(1)+", using "+p1+" and "+p2);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntity.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntity.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntity.java
new file mode 100644
index 0000000..aacbe9f
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntity.java
@@ -0,0 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.lifecycle;
+
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+
+@ImplementedBy(MyEntityImpl.class)
+public interface MyEntity extends SoftwareProcess {
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntityApp.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntityApp.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntityApp.java
new file mode 100644
index 0000000..461c676
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntityApp.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.lifecycle;
+
+public class MyEntityApp {
+    public static void main(String[] args) throws InterruptedException {
+        System.out.println("Properties: "+System.getProperties());
+        Thread.sleep(60*60*1000);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntityImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntityImpl.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntityImpl.java
new file mode 100644
index 0000000..15dd95b
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MyEntityImpl.java
@@ -0,0 +1,125 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.lifecycle;
+
+import java.util.List;
+
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.ResourceUtils;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+import org.apache.brooklyn.util.text.Identifiers;
+
+public class MyEntityImpl extends SoftwareProcessImpl implements MyEntity {
+    @Override
+    public Class<?> getDriverInterface() {
+        return MyEntityDriver.class;
+    }
+
+    @Override
+    protected void connectSensors() {
+        super.connectSensors();
+        connectServiceUpIsRunning();
+    }
+    
+    @Override
+    protected void disconnectSensors() {
+        super.disconnectSensors();
+        disconnectServiceUpIsRunning();
+    }
+    
+    public interface MyEntityDriver extends SoftwareProcessDriver {}
+
+    public static class MyEntitySshDriver extends JavaSoftwareProcessSshDriver implements MyEntityDriver {
+
+        @SetFromFlag("version")
+        public static final ConfigKey<String> SUGGESTED_VERSION = ConfigKeys.newConfigKeyWithDefault(SoftwareProcess.SUGGESTED_VERSION, "0.1");
+
+        public MyEntitySshDriver(MyEntityImpl entity, SshMachineLocation machine) {
+            super(entity, machine);
+        }
+
+        @Override
+        protected String getLogFileLocation() {
+            return getRunDir()+"/nohup.out";
+        }
+        
+        @Override
+        public void install() {
+            String resourceName = "/"+MyEntityApp.class.getName().replace(".", "/")+".class";
+            ResourceUtils r = ResourceUtils.create(this);
+            if (r.getResourceFromUrl(resourceName) == null) 
+                throw new IllegalStateException("Cannot find resource "+resourceName);
+            String tmpFile = "/tmp/brooklyn-test-MyEntityApp-"+Identifiers.makeRandomId(6)+".class";
+            int result = getMachine().installTo(resourceName, tmpFile);
+            if (result!=0) throw new IllegalStateException("Cannot install "+resourceName+" to "+tmpFile);
+            String saveAs = "classes/"+MyEntityApp.class.getPackage().getName().replace(".", "/")+"/"+MyEntityApp.class.getSimpleName()+".class";
+            newScript(INSTALLING).
+                failOnNonZeroResultCode().
+                body.append(
+                    "curl -L \"file://"+tmpFile+"\" --create-dirs -o "+saveAs+" || exit 9"
+                ).execute();
+        }
+
+        @Override
+        public void customize() {
+            newScript(CUSTOMIZING)
+                .execute();
+        }
+        
+        @Override
+        public void launch() {
+            newScript(MutableMap.of("usePidFile", true), LAUNCHING)
+                .body.append(
+                    String.format("nohup java -classpath %s/classes $JAVA_OPTS %s &", getInstallDir(), MyEntityApp.class.getName())
+                ).execute();
+        }
+        
+        @Override
+        public boolean isRunning() {
+            //TODO use PID instead
+            return newScript(MutableMap.of("usePidFile", true), CHECK_RUNNING)
+                .execute() == 0;
+        }
+        
+        @Override
+        public void stop() {
+            newScript(MutableMap.of("usePidFile", true), STOPPING)
+                .execute();
+        }
+
+        @Override
+        public void kill() {
+            newScript(MutableMap.of("usePidFile", true), KILLING)
+                .execute();
+        }
+
+        @Override
+        protected List<String> getCustomJavaConfigOptions() {
+            return MutableList.<String>builder().addAll(super.getCustomJavaConfigOptions()).add("-Dabc=def").build();
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/NaiveScriptRunnerTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/NaiveScriptRunnerTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/NaiveScriptRunnerTest.java
new file mode 100644
index 0000000..59103f1
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/NaiveScriptRunnerTest.java
@@ -0,0 +1,254 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.lifecycle;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags.WrappedStream;
+import org.apache.brooklyn.entity.software.base.lifecycle.NaiveScriptRunner;
+import org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.task.BasicExecutionContext;
+import org.apache.brooklyn.util.core.task.BasicExecutionManager;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.repeat.Repeater;
+import org.apache.brooklyn.util.time.Duration;
+
+import com.google.common.base.Throwables;
+
+@Test
+public class NaiveScriptRunnerTest {
+    
+    private static final Logger log = LoggerFactory.getLogger(NaiveScriptRunnerTest.class);
+    
+    List<String> commands = new ArrayList<String>();
+    
+    @BeforeMethod
+    private void setup() { commands.clear(); }
+    
+    @SuppressWarnings("rawtypes")
+    private NaiveScriptRunner newMockRunner(final int result) {
+        return new NaiveScriptRunner() {
+            @Override
+            public int execute(List<String> script, String summaryForLogging) {
+                return execute(new MutableMap(), script, summaryForLogging);
+            }
+            @Override
+            public int execute(Map flags, List<String> script, String summaryForLogging) {
+                commands.addAll(script);
+                return result;                
+            }
+        };
+    }
+
+    @SuppressWarnings("rawtypes")
+    public static NaiveScriptRunner newLocalhostRunner() {
+        return new NaiveScriptRunner() {
+            LocalhostMachineProvisioningLocation location = new LocalhostMachineProvisioningLocation();
+            @Override
+            public int execute(List<String> script, String summaryForLogging) {
+                return execute(new MutableMap(), script, summaryForLogging);
+            }
+            @SuppressWarnings("unchecked")
+            @Override
+            public int execute(Map flags, List<String> script, String summaryForLogging) {
+                try {
+                    Map flags2 = MutableMap.of("logPrefix", "test");
+                    flags2.putAll(flags);
+                    return location.obtain().execScript(flags2, summaryForLogging, script);
+                } catch (NoMachinesAvailableException e) {
+                    throw Throwables.propagate(e);
+                }
+            }
+        };
+    };
+
+    public void testHeadBodyFootAndResult() {
+        ScriptHelper h = new ScriptHelper(newMockRunner(101), "mock");
+        int result = h.header.
+                append("h1", "h2").body.append("b1", "b2").footer.append("f1", "f2").
+                execute();
+        Assert.assertEquals(result, 101);
+        Assert.assertEquals(commands, Arrays.asList("h1", "h2", "b1", "b2", "f1", "f2"), "List wrong: "+commands);
+    }
+
+    public void testFailOnNonZero() {
+        ScriptHelper h = new ScriptHelper(newMockRunner(106), "mock");
+        boolean succeededWhenShouldntHave = false;
+        try {
+            h.body.append("ignored").
+                failOnNonZeroResultCode().   // will happen
+                execute();            
+            succeededWhenShouldntHave = true;
+        } catch (Exception e) {
+            log.info("ScriptHelper non-zero causes return code: "+e);
+        }
+        if (succeededWhenShouldntHave) Assert.fail("succeeded when shouldn't have");
+    }
+
+    public void testFailOnNonZeroDontFailIfZero() {
+        int result = new ScriptHelper(newMockRunner(0), "mock").body.append("ignored").
+                failOnNonZeroResultCode().   // will happen
+                execute();
+        Assert.assertEquals(result, 0);
+    }
+
+
+    @Test(groups = "Integration")
+    public void testFailingCommandFailsEarly() {
+        ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock").
+                body.append("curl road://to/nowhere", "exit 11").
+                gatherOutput();
+        int result = script.execute();
+        // should get _1_ from curl failing, not 11 from us
+        // TODO not sure why though!
+        Assert.assertEquals(1, result);
+    }
+
+    // TODO a good way to indicate when downloads fail, as that is quite a common case
+    // but i think we need quite a bit of scaffolding to detect that problem (without inspecting logs) ...
+
+    @Test(groups = "Integration")
+    public void testGatherOutputStdout() {
+        ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock").
+                body.append("echo `echo foo``echo bar`", "exit 8").
+                gatherOutput();
+        int result = script.execute();
+        Assert.assertEquals(8, result);
+        if (!script.getResultStdout().contains("foobar"))
+            Assert.fail("STDOUT does not contain expected text 'foobar'.\n"+script.getResultStdout()+
+                    "\nSTDERR:\n"+script.getResultStderr());
+    }
+
+    @Test(groups = "Integration")
+    public void testGatherOutputStderr() {
+        ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock").
+                body.append("set -x", "curl road://to/nowhere || exit 11").
+                gatherOutput();
+        int result = script.execute();
+        Assert.assertEquals(11, result);
+        if (!script.getResultStderr().contains("road"))
+            Assert.fail("STDERR does not contain expected text 'road'.\n"+script.getResultStderr()+
+                    "\nSTDOUT:\n"+script.getResultStdout());
+    }
+
+    @Test(groups = "Integration")
+    public void testGatherOutuputNotEnabled() {
+        ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock").
+                body.append("echo foo", "exit 11");
+        int result = script.execute();
+        Assert.assertEquals(11, result);
+        boolean succeededWhenShouldNotHave = false;
+        try {
+            script.getResultStdout();
+            succeededWhenShouldNotHave = true;
+        } catch (Exception e) { /* expected */ }
+        if (succeededWhenShouldNotHave) Assert.fail("Should have failed");
+    }
+
+    @Test(groups = "Integration")
+    public void testStreamsInTask() {
+        final ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock").
+                body.append("echo `echo foo``echo bar`", "grep absent-text badfile_which_does_not_exist_blaahblahasdewq").
+                gatherOutput();
+        Assert.assertNull(script.peekTask());
+        Task<Integer> task = script.newTask();
+        Assert.assertTrue(BrooklynTaskTags.streams(task).size() >= 3, "Expected at least 3 streams: "+BrooklynTaskTags.streams(task));
+        Assert.assertFalse(Tasks.isQueuedOrSubmitted(task));
+        WrappedStream in = BrooklynTaskTags.stream(task, BrooklynTaskTags.STREAM_STDIN);
+        Assert.assertNotNull(in);
+        Assert.assertTrue(in.streamContents.get().contains("echo foo"), "Expected 'echo foo' but had: "+in.streamContents.get());
+        Assert.assertTrue(in.streamSize.get() > 0);
+        Assert.assertNotNull(script.peekTask());
+    }
+
+    @Test(groups = "Integration")
+    public void testAutoQueueAndRuntimeStreamsInTask() {
+        final ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock").
+                body.append("echo `echo foo``echo bar`", "grep absent-text badfile_which_does_not_exist_blaahblahasdewq").
+                gatherOutput();
+        Task<Integer> submitter = Tasks.<Integer>builder().body(new Callable<Integer>() {
+            public Integer call() {
+                int result = script.execute();
+                return result;
+            } 
+        }).build();
+        BasicExecutionManager em = new BasicExecutionManager("tests");
+        BasicExecutionContext ec = new BasicExecutionContext(em);
+        try {
+            Assert.assertNull(script.peekTask());
+            ec.submit(submitter);
+            // soon there should be a task which is submitted
+            Assert.assertTrue(Repeater.create("get script").every(Duration.millis(10)).limitTimeTo(Duration.FIVE_SECONDS).until(new Callable<Boolean>() {
+                public Boolean call() { 
+                    return (script.peekTask() != null) && Tasks.isQueuedOrSubmitted(script.peekTask());
+                }
+            }).run());
+            Task<Integer> task = script.peekTask();
+            Assert.assertTrue(BrooklynTaskTags.streams(task).size() >= 3, "Expected at least 3 streams: "+BrooklynTaskTags.streams(task));
+            // stdin should be populated
+            WrappedStream in = BrooklynTaskTags.stream(task, BrooklynTaskTags.STREAM_STDIN);
+            Assert.assertNotNull(in);
+            Assert.assertTrue(in.streamContents.get().contains("echo foo"), "Expected 'echo foo' but had: "+in.streamContents.get());
+            Assert.assertTrue(in.streamSize.get() > 0);
+            
+            // out and err should exist
+            WrappedStream out = BrooklynTaskTags.stream(task, BrooklynTaskTags.STREAM_STDOUT);
+            WrappedStream err = BrooklynTaskTags.stream(task, BrooklynTaskTags.STREAM_STDERR);
+            Assert.assertNotNull(out);
+            Assert.assertNotNull(err);
+            
+            // it should soon finish, with exit code
+            Integer result = task.getUnchecked(Duration.TEN_SECONDS);
+            Assert.assertNotNull(result);
+            Assert.assertTrue(result > 0, "Expected non-zero exit code: "+result);
+            // and should contain foobar in stdout
+            if (!script.getResultStdout().contains("foobar"))
+                Assert.fail("Script STDOUT does not contain expected text 'foobar'.\n"+script.getResultStdout()+
+                        "\nSTDERR:\n"+script.getResultStderr());
+            if (!out.streamContents.get().contains("foobar"))
+                Assert.fail("Task STDOUT does not contain expected text 'foobar'.\n"+out.streamContents.get()+
+                        "\nSTDERR:\n"+script.getResultStderr());
+            // and "No such file or directory" in stderr
+            if (!script.getResultStderr().contains("No such file or directory"))
+                Assert.fail("Script STDERR does not contain expected text 'No such ...'.\n"+script.getResultStdout()+
+                        "\nSTDERR:\n"+script.getResultStderr());
+            if (!err.streamContents.get().contains("No such file or directory"))
+                Assert.fail("Task STDERR does not contain expected text 'No such...'.\n"+out.streamContents.get()+
+                        "\nSTDERR:\n"+script.getResultStderr());
+        } finally {
+            em.shutdownNow();
+        }
+    }
+
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelperTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelperTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelperTest.java
new file mode 100644
index 0000000..479c24f
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelperTest.java
@@ -0,0 +1,157 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.lifecycle;
+
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessEntityTest;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessEntityTest.MyService;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessEntityTest.MyServiceImpl;
+import org.apache.brooklyn.entity.trait.Startable;
+import org.apache.brooklyn.sensor.feed.function.FunctionFeed;
+import org.apache.brooklyn.sensor.feed.function.FunctionPollConfig;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.TestException;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+import com.google.common.base.Functions;
+import com.google.common.collect.ImmutableList;
+
+public class ScriptHelperTest extends BrooklynAppUnitTestSupport {
+    
+    private static final Logger log = LoggerFactory.getLogger(ScriptHelperTest.class);
+    
+    private SshMachineLocation machine;
+    private FixedListMachineProvisioningLocation<SshMachineLocation> loc;
+    boolean shouldFail = false;
+    int failCount = 0;
+    
+    @BeforeMethod(alwaysRun=true)
+    @SuppressWarnings("unchecked")
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        loc = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class));
+        machine = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure("address", "localhost"));
+        loc.addMachine(machine);
+    }
+
+    @Test
+    public void testCheckRunningForcesInessential() {
+        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class, MyServiceInessentialDriverImpl.class));
+        
+        entity.start(ImmutableList.of(loc));
+        SimulatedInessentialIsRunningDriver driver = (SimulatedInessentialIsRunningDriver) entity.getDriver();
+        Assert.assertTrue(driver.isRunning());
+        
+        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, true);
+        EntityTestUtils.assertAttributeEqualsEventually(entity, Startable.SERVICE_UP, true);
+        
+        log.debug("up, now cause failure");
+        
+        driver.setFailExecution(true);
+        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, false);
+        
+        log.debug("caught failure, now clear");
+        driver.setFailExecution(false);
+        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, true);
+    }
+    
+    public static class MyServiceInessentialDriverImpl extends MyServiceImpl {
+
+        @Override public Class<?> getDriverInterface() {
+            return SimulatedInessentialIsRunningDriver.class;
+        }
+
+        @Override
+        protected void connectSensors() {
+            super.connectSensors();
+            connectServiceUpIsRunning();
+        }
+        
+        @Override
+        public void connectServiceUpIsRunning() {
+//            super.connectServiceUpIsRunning();
+            // run more often
+            FunctionFeed.builder()
+                .entity(this)
+                .period(Duration.millis(10))
+                .poll(new FunctionPollConfig<Boolean, Boolean>(SERVICE_PROCESS_IS_RUNNING)
+                    .onException(Functions.constant(Boolean.FALSE))
+                    .callable(new Callable<Boolean>() {
+                        public Boolean call() {
+                            return getDriver().isRunning();
+                        }
+                    }))
+                .build();
+        }
+    }
+    
+    public static class SimulatedInessentialIsRunningDriver extends SoftwareProcessEntityTest.SimulatedDriver {
+        private boolean failExecution = false;
+
+        public SimulatedInessentialIsRunningDriver(EntityLocal entity, SshMachineLocation machine) {
+            super(entity, machine);
+        }
+        
+        @Override
+        public boolean isRunning() {
+            return newScript(CHECK_RUNNING)
+                .execute() == 0;
+        }
+        
+        @Override
+        public int execute(List<String> script, String summaryForLogging) {
+            if (failExecution) {
+                throw new TestException("Simulated driver exception");
+            }
+            return 0;
+        }
+        
+        @SuppressWarnings("rawtypes")
+        @Override
+        public int execute(Map flags2, List<String> script, String summaryForLogging) {
+            if (failExecution) {
+                throw new TestException("Simulated driver exception");
+            }
+            return 0;
+        }
+        
+        public void setFailExecution(boolean failExecution) {
+            this.failExecution = failExecution;
+        }
+        
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/StartStopSshDriverTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/StartStopSshDriverTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/StartStopSshDriverTest.java
new file mode 100644
index 0000000..1bf3bbe
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/StartStopSshDriverTest.java
@@ -0,0 +1,168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.lifecycle;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.io.ByteArrayOutputStream;
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadInfo;
+import java.lang.management.ThreadMXBean;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.core.test.entity.TestApplicationImpl;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.core.test.entity.TestEntityImpl;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.collections.MutableSet;
+import org.apache.brooklyn.util.core.internal.ssh.SshTool;
+import org.apache.brooklyn.util.core.internal.ssh.cli.SshCliTool;
+import org.apache.brooklyn.util.core.internal.ssh.sshj.SshjTool;
+import org.apache.brooklyn.util.stream.StreamGobbler;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+import com.google.common.base.Function;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+
+public class StartStopSshDriverTest {
+
+    public class BasicStartStopSshDriver extends AbstractSoftwareProcessSshDriver {
+        public BasicStartStopSshDriver(EntityLocal entity, SshMachineLocation machine) {
+            super(entity, machine);
+        }
+        public boolean isRunning() { return true; }
+        public void stop() {}
+        public void kill() {}
+        public void install() {}
+        public void customize() {}
+        public void launch() {}
+    }
+
+    private static class ThreadIdTransformer implements Function<ThreadInfo, Long> {
+        @Override
+        public Long apply(ThreadInfo t) {
+            return t.getThreadId();
+        }
+    }
+
+    private TestApplication app;
+    private TestEntity entity;
+    private SshMachineLocationWithSshTool sshMachineLocation;
+    private AbstractSoftwareProcessSshDriver driver;
+
+    @SuppressWarnings("rawtypes")
+    protected static class SshMachineLocationWithSshTool extends SshMachineLocation {
+        private static final long serialVersionUID = 1L;
+
+        SshTool lastTool;
+        public SshMachineLocationWithSshTool(Map flags) { super(flags); }
+        public SshTool connectSsh(Map args) {
+            SshTool result = super.connectSsh(args);
+            lastTool = result;
+            return result;
+        }
+    }
+    
+    @BeforeMethod(alwaysRun = true)
+    public void setUp() {
+        app = new TestApplicationImpl();
+        entity = new TestEntityImpl(app);
+        Entities.startManagement(app);
+        sshMachineLocation = new SshMachineLocationWithSshTool(ImmutableMap.of("address", "localhost"));
+        driver = new BasicStartStopSshDriver(entity, sshMachineLocation);
+    }
+    
+    @Test(groups="Integration")
+    public void testExecuteDoesNotLeaveRunningStreamGobblerThread() {
+        List<ThreadInfo> existingThreads = getThreadsCalling(StreamGobbler.class);
+        final List<Long> existingThreadIds = getThreadId(existingThreads);
+        
+        List<String> script = Arrays.asList("echo hello");
+        driver.execute(script, "mytest");
+        
+        Asserts.succeedsEventually(ImmutableMap.of("timeout", 10*1000), new Runnable() {
+            @Override
+            public void run() {
+              List<ThreadInfo> currentThreads = getThreadsCalling(StreamGobbler.class);
+              Set<Long> currentThreadIds = MutableSet.copyOf(getThreadId(currentThreads));
+
+              currentThreadIds.removeAll(existingThreadIds);
+              assertEquals(currentThreadIds, ImmutableSet.<Long>of());
+            }
+        });
+    }
+
+    @Test(groups="Integration")
+    public void testSshScriptHeaderUsedWhenSpecified() {
+        entity.setConfig(BrooklynConfigKeys.SSH_CONFIG_SCRIPT_HEADER, "#!/bin/bash -e\necho hello world");
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        driver.execute(ImmutableMap.of("out", out), Arrays.asList("echo goodbye"), "test");
+        String s = out.toString();
+        assertTrue(s.contains("goodbye"), "should have said goodbye: "+s);
+        assertTrue(s.contains("hello world"), "should have said hello: "+s);
+        assertTrue(sshMachineLocation.lastTool instanceof SshjTool, "expect sshj tool, got "+
+            (sshMachineLocation.lastTool!=null ? ""+sshMachineLocation.lastTool.getClass()+":" : "") + sshMachineLocation.lastTool);
+    }
+
+    @Test(groups="Integration")
+    public void testSshCliPickedUpWhenSpecified() {
+        entity.setConfig(BrooklynConfigKeys.SSH_TOOL_CLASS, SshCliTool.class.getName());
+        driver.execute(Arrays.asList("echo hi"), "test");
+        assertTrue(sshMachineLocation.lastTool instanceof SshCliTool, "expect CLI tool, got "+
+                        (sshMachineLocation.lastTool!=null ? ""+sshMachineLocation.lastTool.getClass()+":" : "") + sshMachineLocation.lastTool);
+    }
+    
+    private List<ThreadInfo> getThreadsCalling(Class<?> clazz) {
+        String clazzName = clazz.getCanonicalName();
+        List<ThreadInfo> result = MutableList.of();
+        ThreadMXBean threadMxbean = ManagementFactory.getThreadMXBean();
+        ThreadInfo[] threads = threadMxbean.dumpAllThreads(false, false);
+        
+        for (ThreadInfo thread : threads) {
+            StackTraceElement[] stackTrace = thread.getStackTrace();
+            for (StackTraceElement stackTraceElement : stackTrace) {
+                if (clazzName == stackTraceElement.getClassName()) {
+                    result.add(thread);
+                    break;
+                }
+            }
+        }
+        return result;
+    }
+
+    private ImmutableList<Long> getThreadId(List<ThreadInfo> existingThreads) {
+        return FluentIterable.from(existingThreads).transform(new ThreadIdTransformer()).toList();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/ApplicationUsageTrackingTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/ApplicationUsageTrackingTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/ApplicationUsageTrackingTest.java
new file mode 100644
index 0000000..11fba70
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/ApplicationUsageTrackingTest.java
@@ -0,0 +1,224 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.core.mgmt.usage;
+
+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.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.brooklyn.api.entity.Application;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.mgmt.internal.UsageListener.ApplicationMetadata;
+import org.apache.brooklyn.core.mgmt.usage.ApplicationUsage;
+import org.apache.brooklyn.core.mgmt.usage.ApplicationUsage.ApplicationEvent;
+import org.apache.brooklyn.core.objs.proxy.EntityProxy;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.time.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Predicates;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+
+public class ApplicationUsageTrackingTest {
+
+    private static final Logger LOG = LoggerFactory.getLogger(ApplicationUsageTrackingTest.class);
+
+    protected TestApplication app;
+    protected ManagementContextInternal mgmt;
+
+    protected boolean shouldSkipOnBoxBaseDirResolution() {
+        return true;
+    }
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        mgmt = LocalManagementContextForTests.newInstance();
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        try {
+            if (mgmt != null) Entities.destroyAll(mgmt);
+        } catch (Throwable t) {
+            LOG.error("Caught exception in tearDown method", t);
+        } finally {
+            mgmt = null;
+        }
+    }
+
+    @Test
+    public void testUsageInitiallyEmpty() {
+        Set<ApplicationUsage> usage = mgmt.getUsageManager().getApplicationUsage(Predicates.alwaysTrue());
+        assertEquals(usage, ImmutableSet.of());
+    }
+
+    @Test
+    @SuppressWarnings("deprecation")
+    public void testAddAndRemoveLegacyUsageListener() throws Exception {
+        final RecordingLegacyUsageListener listener = new RecordingLegacyUsageListener();
+        mgmt.getUsageManager().addUsageListener(listener);
+        
+        app = TestApplication.Factory.newManagedInstanceForTests(mgmt);
+        app.setCatalogItemId("testCatalogItem");
+        app.start(ImmutableList.<Location>of());
+
+        Asserts.succeedsEventually(new Runnable() {
+            @Override public void run() {
+                List<List<?>> events = listener.getApplicationEvents();
+                assertEquals(events.size(), 2, "events="+events); // expect STARTING and RUNNING
+                
+                String appId = (String) events.get(0).get(1);
+                String appName = (String) events.get(0).get(2);
+                String entityType = (String) events.get(0).get(3);
+                String catalogItemId = (String) events.get(0).get(4);
+                Map<?,?> metadata = (Map<?, ?>) events.get(0).get(5);
+                ApplicationEvent appEvent = (ApplicationEvent) events.get(0).get(6);
+                
+                assertEquals(appId, app.getId(), "events="+events);
+                assertNotNull(appName, "events="+events);
+                assertEquals(catalogItemId, app.getCatalogItemId(), "events="+events);
+                assertNotNull(entityType, "events="+events);
+                assertNotNull(metadata, "events="+events);
+                assertEquals(appEvent.getState(), Lifecycle.STARTING, "events="+events);
+            }});
+
+
+        // Remove the listener; will get no more notifications
+        listener.clearEvents();
+        mgmt.getUsageManager().removeUsageListener(listener);
+        
+        app.start(ImmutableList.<Location>of());
+        Asserts.succeedsContinually(new Runnable() {
+            @Override public void run() {
+                List<List<?>> events = listener.getLocationEvents();
+                assertEquals(events.size(), 0, "events="+events);
+            }});
+    }
+
+    @Test
+    public void testAddAndRemoveUsageListener() throws Exception {
+        final RecordingUsageListener listener = new RecordingUsageListener();
+        mgmt.getUsageManager().addUsageListener(listener);
+        
+        app = TestApplication.Factory.newManagedInstanceForTests(mgmt);
+        app.setCatalogItemId("testCatalogItem");
+        app.start(ImmutableList.<Location>of());
+
+        Asserts.succeedsEventually(new Runnable() {
+            @Override public void run() {
+                List<List<?>> events = listener.getApplicationEvents();
+                assertEquals(events.size(), 2, "events="+events); // expect STARTING and RUNNING
+                ApplicationMetadata appMetadata = (ApplicationMetadata) events.get(0).get(1);
+                ApplicationEvent appEvent = (ApplicationEvent) events.get(0).get(2);
+                
+                assertEquals(appMetadata.getApplication(), app, "events="+events);
+                assertTrue(appMetadata.getApplication() instanceof EntityProxy, "events="+events);
+                assertEquals(appMetadata.getApplicationId(), app.getId(), "events="+events);
+                assertNotNull(appMetadata.getApplicationName(), "events="+events);
+                assertEquals(appMetadata.getCatalogItemId(), app.getCatalogItemId(), "events="+events);
+                assertNotNull(appMetadata.getEntityType(), "events="+events);
+                assertNotNull(appMetadata.getMetadata(), "events="+events);
+                assertEquals(appEvent.getState(), Lifecycle.STARTING, "events="+events);
+            }});
+
+
+        // Remove the listener; will get no more notifications
+        listener.clearEvents();
+        mgmt.getUsageManager().removeUsageListener(listener);
+        
+        app.start(ImmutableList.<Location>of());
+        Asserts.succeedsContinually(new Runnable() {
+            @Override public void run() {
+                List<List<?>> events = listener.getLocationEvents();
+                assertEquals(events.size(), 0, "events="+events);
+            }});
+    }
+    
+    @Test
+    public void testUsageIncludesStartAndStopEvents() {
+        // Start event
+        long preStart = System.currentTimeMillis();
+        app = TestApplication.Factory.newManagedInstanceForTests(mgmt);
+        app.start(ImmutableList.<Location>of());
+        long postStart = System.currentTimeMillis();
+
+        Set<ApplicationUsage> usages1 = mgmt.getUsageManager().getApplicationUsage(Predicates.alwaysTrue());
+        ApplicationUsage usage1 = Iterables.getOnlyElement(usages1);
+        assertApplicationUsage(usage1, app);
+        assertApplicationEvent(usage1.getEvents().get(0), Lifecycle.STARTING, preStart, postStart);
+        assertApplicationEvent(usage1.getEvents().get(1), Lifecycle.RUNNING, preStart, postStart);
+
+        // Stop events
+        long preStop = System.currentTimeMillis();
+        app.stop();
+        long postStop = System.currentTimeMillis();
+
+        Set<ApplicationUsage> usages2 = mgmt.getUsageManager().getApplicationUsage(Predicates.alwaysTrue());
+        ApplicationUsage usage2 = Iterables.getOnlyElement(usages2);
+        assertApplicationUsage(usage2, app);
+        assertApplicationEvent(usage2.getEvents().get(2), Lifecycle.STOPPING, preStop, postStop);
+        assertApplicationEvent(usage2.getEvents().get(3), Lifecycle.STOPPED, preStop, postStop);
+        //Apps unmanage themselves on stop
+        assertApplicationEvent(usage2.getEvents().get(4), Lifecycle.DESTROYED, preStop, postStop);
+        
+        assertFalse(mgmt.getEntityManager().isManaged(app), "App should already be unmanaged");
+        
+        Set<ApplicationUsage> usages3 = mgmt.getUsageManager().getApplicationUsage(Predicates.alwaysTrue());
+        ApplicationUsage usage3 = Iterables.getOnlyElement(usages3);
+        assertApplicationUsage(usage3, app);
+        
+        assertEquals(usage3.getEvents().size(), 5, "usage="+usage3);
+    }
+    
+    private void assertApplicationUsage(ApplicationUsage usage, Application expectedApp) {
+        assertEquals(usage.getApplicationId(), expectedApp.getId());
+        assertEquals(usage.getApplicationName(), expectedApp.getDisplayName());
+        assertEquals(usage.getEntityType(), expectedApp.getEntityType().getName());
+    }
+    
+    private void assertApplicationEvent(ApplicationEvent event, Lifecycle expectedState, long preEvent, long postEvent) {
+        // Saw times differ by 1ms - perhaps different threads calling currentTimeMillis() can get out-of-order times?!
+        final int TIMING_GRACE = 5;
+        
+        assertEquals(event.getState(), expectedState);
+        long eventTime = event.getDate().getTime();
+        if (eventTime < (preEvent - TIMING_GRACE) || eventTime > (postEvent + TIMING_GRACE)) {
+            fail("for "+expectedState+": event=" + Time.makeDateString(eventTime) + "("+eventTime + "); "
+                    + "pre=" + Time.makeDateString(preEvent) + " ("+preEvent+ "); "
+                    + "post=" + Time.makeDateString(postEvent) + " ("+postEvent + ")");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/LocationUsageTrackingTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/LocationUsageTrackingTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/LocationUsageTrackingTest.java
new file mode 100644
index 0000000..44760ac
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/LocationUsageTrackingTest.java
@@ -0,0 +1,210 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.core.mgmt.usage;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.fail;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.core.mgmt.internal.UsageListener.LocationMetadata;
+import org.apache.brooklyn.core.mgmt.usage.LocationUsage;
+import org.apache.brooklyn.core.mgmt.usage.LocationUsage.LocationEvent;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessEntityTest;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.time.Time;
+
+import com.google.common.base.Predicates;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+
+public class LocationUsageTrackingTest extends BrooklynAppUnitTestSupport {
+
+    private DynamicLocalhostMachineProvisioningLocation loc;
+
+    @BeforeMethod(alwaysRun = true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        loc = mgmt.getLocationManager().createLocation(LocationSpec.create(DynamicLocalhostMachineProvisioningLocation.class));
+    }
+
+    @Test
+    public void testUsageInitiallyEmpty() {
+        Set<LocationUsage> usage = mgmt.getUsageManager().getLocationUsage(Predicates.alwaysTrue());
+        assertEquals(usage, ImmutableSet.of());
+    }
+
+    @Test
+    @SuppressWarnings("deprecation")
+    public void testAddAndRemoveLegacyUsageListener() throws Exception {
+        final RecordingLegacyUsageListener listener = new RecordingLegacyUsageListener();
+        mgmt.getUsageManager().addUsageListener(listener);
+        
+        app.createAndManageChild(EntitySpec.create(SoftwareProcessEntityTest.MyService.class));
+        app.start(ImmutableList.of(loc));
+        final SshMachineLocation machine = Iterables.getOnlyElement(loc.getAllMachines());
+        
+        Asserts.succeedsEventually(new Runnable() {
+            @Override public void run() {
+                List<List<?>> events = listener.getLocationEvents();
+                String locId = (String) events.get(0).get(1);
+                LocationEvent locEvent = (LocationEvent) events.get(0).get(3);
+                Map<?,?> metadata = (Map<?, ?>) events.get(0).get(2);
+                
+                assertEquals(events.size(), 1, "events="+events);
+                assertEquals(locId, machine.getId(), "events="+events);
+                assertNotNull(metadata, "events="+events);
+                assertEquals(locEvent.getApplicationId(), app.getId(), "events="+events);
+                assertEquals(locEvent.getState(), Lifecycle.CREATED, "events="+events);
+            }});
+
+        // Remove the listener; will get no more notifications
+        listener.clearEvents();
+        mgmt.getUsageManager().removeUsageListener(listener);
+        
+        app.stop();
+        Asserts.succeedsContinually(new Runnable() {
+            @Override public void run() {
+                List<List<?>> events = listener.getLocationEvents();
+                assertEquals(events.size(), 0, "events="+events);
+            }});
+    }
+
+    @Test
+    public void testAddAndRemoveUsageListener() throws Exception {
+        final RecordingUsageListener listener = new RecordingUsageListener();
+        mgmt.getUsageManager().addUsageListener(listener);
+        
+        app.createAndManageChild(EntitySpec.create(SoftwareProcessEntityTest.MyService.class));
+        app.start(ImmutableList.of(loc));
+        final SshMachineLocation machine = Iterables.getOnlyElement(loc.getAllMachines());
+        
+        Asserts.succeedsEventually(new Runnable() {
+            @Override public void run() {
+                List<List<?>> events = listener.getLocationEvents();
+                LocationMetadata locMetadata = (LocationMetadata) events.get(0).get(1);
+                LocationEvent locEvent = (LocationEvent) events.get(0).get(2);
+                
+                assertEquals(events.size(), 1, "events="+events);
+                assertEquals(locMetadata.getLocation(), machine, "events="+events);
+                assertEquals(locMetadata.getLocationId(), machine.getId(), "events="+events);
+                assertNotNull(locMetadata.getMetadata(), "events="+events);
+                assertEquals(locEvent.getApplicationId(), app.getId(), "events="+events);
+                assertEquals(locEvent.getState(), Lifecycle.CREATED, "events="+events);
+            }});
+
+        // Remove the listener; will get no more notifications
+        listener.clearEvents();
+        mgmt.getUsageManager().removeUsageListener(listener);
+        
+        app.stop();
+        Asserts.succeedsContinually(new Runnable() {
+            @Override public void run() {
+                List<List<?>> events = listener.getLocationEvents();
+                assertEquals(events.size(), 0, "events="+events);
+            }});
+    }
+
+    @Test
+    public void testUsageIncludesStartAndStopEvents() {
+        SoftwareProcessEntityTest.MyService entity = app.createAndManageChild(EntitySpec.create(SoftwareProcessEntityTest.MyService.class));
+
+        // Start the app; expect record of location in use
+        long preStart = System.currentTimeMillis();
+        app.start(ImmutableList.of(loc));
+        long postStart = System.currentTimeMillis();
+        SshMachineLocation machine = Iterables.getOnlyElement(loc.getAllMachines());
+
+        Set<LocationUsage> usages1 = mgmt.getUsageManager().getLocationUsage(Predicates.alwaysTrue());
+        LocationUsage usage1 = Iterables.getOnlyElement(usages1);
+        assertLocationUsage(usage1, machine);
+        assertLocationEvent(usage1.getEvents().get(0), entity, Lifecycle.CREATED, preStart, postStart);
+
+        // Stop the app; expect record of location no longer in use
+        long preStop = System.currentTimeMillis();
+        app.stop();
+        long postStop = System.currentTimeMillis();
+
+        Set<LocationUsage> usages2 = mgmt.getUsageManager().getLocationUsage(Predicates.alwaysTrue());
+        LocationUsage usage2 = Iterables.getOnlyElement(usages2);
+        assertLocationUsage(usage2, machine);
+        assertLocationEvent(usage2.getEvents().get(1), app.getApplicationId(), entity.getId(), entity.getEntityType().getName(), Lifecycle.DESTROYED, preStop, postStop);
+        
+        assertEquals(usage2.getEvents().size(), 2, "usage="+usage2);
+    }
+
+    public static class DynamicLocalhostMachineProvisioningLocation extends LocalhostMachineProvisioningLocation {
+        private static final long serialVersionUID = 4822009936654077946L;
+
+        @Override
+        public SshMachineLocation obtain(Map<?, ?> flags) throws NoMachinesAvailableException {
+            System.out.println("called DynamicLocalhostMachineProvisioningLocation.obtain");
+            return super.obtain(flags);
+        }
+
+        @Override
+        public void release(SshMachineLocation machine) {
+            System.out.println("called DynamicLocalhostMachineProvisioningLocation.release");
+            super.release(machine);
+            super.machines.remove(machine);
+            super.removeChild(machine);
+        }
+    }
+    
+    private void assertLocationUsage(LocationUsage usage, Location expectedLoc) {
+        assertEquals(usage.getLocationId(), expectedLoc.getId(), "usage="+usage);
+        assertNotNull(usage.getMetadata(), "usage="+usage);
+    }
+
+    private void assertLocationEvent(LocationEvent event, Entity expectedEntity, Lifecycle expectedState, long preEvent, long postEvent) {
+        assertLocationEvent(event, expectedEntity.getApplicationId(), expectedEntity.getId(), expectedEntity.getEntityType().getName(), expectedState, preEvent, postEvent);
+    }
+    
+    private void assertLocationEvent(LocationEvent event, String expectedAppId, String expectedEntityId, String expectedEntityType, Lifecycle expectedState, long preEvent, long postEvent) {
+        // Saw times differ by 1ms - perhaps different threads calling currentTimeMillis() can get out-of-order times?!
+        final int TIMING_GRACE = 5;
+        
+        assertEquals(event.getApplicationId(), expectedAppId);
+        assertEquals(event.getEntityId(), expectedEntityId);
+        assertEquals(event.getEntityType(), expectedEntityType);
+        assertEquals(event.getState(), expectedState);
+        long eventTime = event.getDate().getTime();
+        if (eventTime < (preEvent - TIMING_GRACE) || eventTime > (postEvent + TIMING_GRACE)) {
+            fail("for "+expectedState+": event=" + Time.makeDateString(eventTime) + "("+eventTime + "); "
+                    + "pre=" + Time.makeDateString(preEvent) + " ("+preEvent+ "); "
+                    + "post=" + Time.makeDateString(postEvent) + " ("+postEvent + ")");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/RecordingLegacyUsageListener.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/RecordingLegacyUsageListener.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/RecordingLegacyUsageListener.java
new file mode 100644
index 0000000..8e2e489
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/RecordingLegacyUsageListener.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.core.mgmt.usage;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.core.mgmt.usage.ApplicationUsage.ApplicationEvent;
+import org.apache.brooklyn.core.mgmt.usage.LocationUsage.LocationEvent;
+import org.apache.brooklyn.util.collections.MutableList;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+@Deprecated
+public class RecordingLegacyUsageListener implements org.apache.brooklyn.core.mgmt.internal.UsageManager.UsageListener {
+
+    private final List<List<?>> events = Lists.newCopyOnWriteArrayList();
+    
+    @Override
+    public void onApplicationEvent(String applicationId, String applicationName, String entityType, 
+            String catalogItemId, Map<String, String> metadata, ApplicationEvent event) {
+        events.add(MutableList.of("application", applicationId, applicationName, entityType, catalogItemId, metadata, event));
+    }
+
+    @Override
+    public void onLocationEvent(String locationId, Map<String, String> metadata, LocationEvent event) {
+        events.add(MutableList.of("location", locationId, metadata, event));
+    }
+    
+    public void clearEvents() {
+        events.clear();
+    }
+    
+    public List<List<?>> getEvents() {
+        return ImmutableList.copyOf(events);
+    }
+    
+    public List<List<?>> getLocationEvents() {
+        List<List<?>> result = Lists.newArrayList();
+        for (List<?> event : events) {
+            if (event.get(0).equals("location")) result.add(event);
+        }
+        return ImmutableList.copyOf(result);
+    }
+    
+    public List<List<?>> getApplicationEvents() {
+        List<List<?>> result = Lists.newArrayList();
+        for (List<?> event : events) {
+            if (event.get(0).equals("application")) result.add(event);
+        }
+        return ImmutableList.copyOf(result);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/RecordingUsageListener.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/RecordingUsageListener.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/RecordingUsageListener.java
new file mode 100644
index 0000000..399b575
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/RecordingUsageListener.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.core.mgmt.usage;
+
+import java.util.List;
+
+import org.apache.brooklyn.core.mgmt.usage.ApplicationUsage.ApplicationEvent;
+import org.apache.brooklyn.core.mgmt.usage.LocationUsage.LocationEvent;
+import org.apache.brooklyn.util.collections.MutableList;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+public class RecordingUsageListener implements org.apache.brooklyn.core.mgmt.internal.UsageListener {
+
+    private final List<List<?>> events = Lists.newCopyOnWriteArrayList();
+    
+    @Override
+    public void onApplicationEvent(ApplicationMetadata app, ApplicationEvent event) {
+        events.add(MutableList.of("application", app, event));
+    }
+
+    @Override
+    public void onLocationEvent(LocationMetadata loc, LocationEvent event) {
+        events.add(MutableList.of("location", loc, event));
+    }
+    
+    public void clearEvents() {
+        events.clear();
+    }
+    
+    public List<List<?>> getEvents() {
+        return ImmutableList.copyOf(events);
+    }
+    
+    public List<List<?>> getLocationEvents() {
+        List<List<?>> result = Lists.newArrayList();
+        for (List<?> event : events) {
+            if (event.get(0).equals("location")) result.add(event);
+        }
+        return ImmutableList.copyOf(result);
+    }
+    
+    public List<List<?>> getApplicationEvents() {
+        List<List<?>> result = Lists.newArrayList();
+        for (List<?> event : events) {
+            if (event.get(0).equals("application")) result.add(event);
+        }
+        return ImmutableList.copyOf(result);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/UsageListenerTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/UsageListenerTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/UsageListenerTest.java
new file mode 100644
index 0000000..518f975
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/core/mgmt/usage/UsageListenerTest.java
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.core.mgmt.usage;
+
+import static org.testng.Assert.assertTrue;
+
+import java.util.List;
+
+import org.apache.brooklyn.test.Asserts;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.mgmt.internal.UsageManager;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Entities;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+
+public class UsageListenerTest {
+
+    // Also see {Application|Location}UsageTrackingTest for listener functionality
+    
+    private static final Logger LOG = LoggerFactory.getLogger(ApplicationUsageTrackingTest.class);
+
+    protected TestApplication app;
+    protected ManagementContextInternal mgmt;
+
+    protected boolean shouldSkipOnBoxBaseDirResolution() {
+        return true;
+    }
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        RecordingStaticLegacyUsageListener.clearInstances();
+        RecordingStaticUsageListener.clearInstances();
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        try {
+            if (mgmt != null) Entities.destroyAll(mgmt);
+        } catch (Throwable t) {
+            LOG.error("Caught exception in tearDown method", t);
+        } finally {
+            mgmt = null;
+            RecordingStaticLegacyUsageListener.clearInstances();
+            RecordingStaticUsageListener.clearInstances();
+        }
+    }
+
+    @Test
+    public void testAddLegacyUsageListenerViaProperties() throws Exception {
+        BrooklynProperties brooklynProperties = BrooklynProperties.Factory.newEmpty();
+        brooklynProperties.put(UsageManager.USAGE_LISTENERS, RecordingStaticLegacyUsageListener.class.getName());
+        mgmt = LocalManagementContextForTests.newInstance(brooklynProperties);
+        
+        app = TestApplication.Factory.newManagedInstanceForTests(mgmt);
+        app.start(ImmutableList.<Location>of());
+
+        Asserts.succeedsEventually(new Runnable() {
+            @Override public void run() {
+                List<List<?>> events = RecordingStaticLegacyUsageListener.getInstance().getApplicationEvents();
+                assertTrue(events.size() > 0, "events="+events); // expect some events
+            }});
+    }
+    
+    @Test
+    public void testAddUsageListenerViaProperties() throws Exception {
+        BrooklynProperties brooklynProperties = BrooklynProperties.Factory.newEmpty();
+        brooklynProperties.put(UsageManager.USAGE_LISTENERS, RecordingStaticUsageListener.class.getName());
+        mgmt = LocalManagementContextForTests.newInstance(brooklynProperties);
+        
+        app = TestApplication.Factory.newManagedInstanceForTests(mgmt);
+        app.start(ImmutableList.<Location>of());
+
+        Asserts.succeedsEventually(new Runnable() {
+            @Override public void run() {
+                List<List<?>> events = RecordingStaticUsageListener.getInstance().getApplicationEvents();
+                assertTrue(events.size() > 0, "events="+events); // expect some events
+            }});
+    }
+    
+    public static class RecordingStaticLegacyUsageListener extends RecordingLegacyUsageListener implements org.apache.brooklyn.core.mgmt.internal.UsageManager.UsageListener {
+        private static final List<RecordingStaticLegacyUsageListener> STATIC_INSTANCES = Lists.newCopyOnWriteArrayList();
+        
+        public static RecordingStaticLegacyUsageListener getInstance() {
+            return Iterables.getOnlyElement(STATIC_INSTANCES);
+        }
+
+        public static void clearInstances() {
+            STATIC_INSTANCES.clear();
+        }
+        
+        public RecordingStaticLegacyUsageListener() {
+            // Bad to leak a ref to this before constructor finished, but we'll live with it because
+            // it's just test code!
+            STATIC_INSTANCES.add(this);
+        }
+    }
+    
+    public static class RecordingStaticUsageListener extends RecordingUsageListener implements org.apache.brooklyn.core.mgmt.internal.UsageListener {
+        private static final List<RecordingStaticUsageListener> STATIC_INSTANCES = Lists.newCopyOnWriteArrayList();
+        
+        public static RecordingStaticUsageListener getInstance() {
+            return Iterables.getOnlyElement(STATIC_INSTANCES);
+        }
+
+        public static void clearInstances() {
+            STATIC_INSTANCES.clear();
+        }
+        
+        public RecordingStaticUsageListener() {
+            // Bad to leak a ref to this before constructor finished, but we'll live with it because
+            // it's just test code!
+            STATIC_INSTANCES.add(this);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/driver/MockSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/driver/MockSshDriver.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/driver/MockSshDriver.java
new file mode 100644
index 0000000..9c92b5b
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/driver/MockSshDriver.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.driver;
+
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+public class MockSshDriver implements SoftwareProcessDriver {
+
+    public int numCallsToRunApp = 0;
+    private final EntityLocal entity;
+    private final SshMachineLocation machine;
+
+    public MockSshDriver(EntityLocal entity, SshMachineLocation machine) {
+        this.entity = entity;
+        this.machine = machine;
+    }
+    
+    @Override
+    public void start() {
+        numCallsToRunApp++;
+    }
+
+    @Override
+    public boolean isRunning() {
+        return numCallsToRunApp>0;
+    }
+
+    @Override
+    public EntityLocal getEntity() {
+        return entity;
+    }
+
+    @Override
+    public Location getLocation() {
+        return machine;
+    }
+
+    @Override
+    public void rebind() {
+    }
+
+    @Override
+    public void stop() {
+    }
+
+    @Override
+    public void restart() {
+    }
+    
+    @Override
+    public void kill() {
+    }
+}


[34/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNodeImpl.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNodeImpl.java
deleted file mode 100644
index e09eab5..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNodeImpl.java
+++ /dev/null
@@ -1,524 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import java.net.URI;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.atomic.AtomicReference;
-
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.api.mgmt.TaskAdaptable;
-import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.render.RendererHints;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.effector.core.EffectorBody;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic.ServiceNotUpLogic;
-import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.http.HttpStatus;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcess.StopSoftwareParameters.StopMode;
-import brooklyn.entity.basic.SoftwareProcessImpl;
-import brooklyn.entity.brooklynnode.EntityHttpClient.ResponseCodePredicates;
-import brooklyn.entity.brooklynnode.effector.BrooklynNodeUpgradeEffectorBody;
-import brooklyn.entity.brooklynnode.effector.SetHighAvailabilityModeEffectorBody;
-import brooklyn.entity.brooklynnode.effector.SetHighAvailabilityPriorityEffectorBody;
-import brooklyn.entity.software.MachineLifecycleEffectorTasks;
-
-import org.apache.brooklyn.location.access.BrooklynAccessUtils;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.sensor.enricher.Enrichers;
-import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
-import org.apache.brooklyn.sensor.feed.http.HttpFeed;
-import org.apache.brooklyn.sensor.feed.http.HttpPollConfig;
-import org.apache.brooklyn.sensor.feed.http.HttpValueFunctions;
-import org.apache.brooklyn.sensor.feed.http.JsonFunctions;
-import org.apache.brooklyn.util.collections.Jsonya;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.http.HttpToolResponse;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.TaskTags;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.exceptions.PropagatedRuntimeException;
-import org.apache.brooklyn.util.guava.Functionals;
-import org.apache.brooklyn.util.javalang.Enums;
-import org.apache.brooklyn.util.javalang.JavaClassNames;
-import org.apache.brooklyn.util.repeat.Repeater;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicates;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.net.HostAndPort;
-import com.google.common.util.concurrent.Runnables;
-import com.google.gson.Gson;
-
-public class BrooklynNodeImpl extends SoftwareProcessImpl implements BrooklynNode {
-
-    private static final Logger log = LoggerFactory.getLogger(BrooklynNodeImpl.class);
-
-    static {
-        RendererHints.register(WEB_CONSOLE_URI, RendererHints.namedActionWithUrl());
-    }
-
-    private static class UnmanageTask implements Runnable {
-        private Task<?> latchTask;
-        private Entity unmanageEntity;
-
-        public UnmanageTask(@Nullable Task<?> latchTask, Entity unmanageEntity) {
-            this.latchTask = latchTask;
-            this.unmanageEntity = unmanageEntity;
-        }
-
-        public void run() {
-            if (latchTask != null) {
-                latchTask.blockUntilEnded();
-            } else {
-                log.debug("No latch task provided for UnmanageTask, falling back to fixed wait");
-                Time.sleep(Duration.FIVE_SECONDS);
-            }
-            synchronized (this) {
-                Entities.unmanage(unmanageEntity);
-            }
-        }
-    }
-
-    private HttpFeed httpFeed;
-    
-    public BrooklynNodeImpl() {
-        super();
-    }
-
-    public BrooklynNodeImpl(Entity parent) {
-        super(parent);
-    }
-    
-    @Override
-    public Class<?> getDriverInterface() {
-        return BrooklynNodeDriver.class;
-    }
-
-    @Override
-    public void init() {
-        super.init();
-        getMutableEntityType().addEffector(DeployBlueprintEffectorBody.DEPLOY_BLUEPRINT);
-        getMutableEntityType().addEffector(ShutdownEffectorBody.SHUTDOWN);
-        getMutableEntityType().addEffector(StopNodeButLeaveAppsEffectorBody.STOP_NODE_BUT_LEAVE_APPS);
-        getMutableEntityType().addEffector(StopNodeAndKillAppsEffectorBody.STOP_NODE_AND_KILL_APPS);
-        getMutableEntityType().addEffector(SetHighAvailabilityPriorityEffectorBody.SET_HIGH_AVAILABILITY_PRIORITY);
-        getMutableEntityType().addEffector(SetHighAvailabilityModeEffectorBody.SET_HIGH_AVAILABILITY_MODE);
-        getMutableEntityType().addEffector(BrooklynNodeUpgradeEffectorBody.UPGRADE);
-    }
-
-    @Override
-    protected void preStart() {
-        ServiceNotUpLogic.clearNotUpIndicator(this, SHUTDOWN.getName());
-    }
-
-    @Override
-    protected void preStopConfirmCustom() {
-        super.preStopConfirmCustom();
-        ConfigBag stopParameters = BrooklynTaskTags.getCurrentEffectorParameters();
-        if (Boolean.TRUE.equals(getAttribute(BrooklynNode.WEB_CONSOLE_ACCESSIBLE)) &&
-                stopParameters != null && !stopParameters.containsKey(ShutdownEffector.STOP_APPS_FIRST)) {
-            Preconditions.checkState(getChildren().isEmpty(), "Can't stop instance with running applications.");
-        }
-    }
-
-    @Override
-    protected void preStop() {
-        super.preStop();
-        if (MachineLifecycleEffectorTasks.canStop(getStopProcessModeParam(), this)) {
-            shutdownGracefully();
-        }
-    }
-
-    private StopMode getStopProcessModeParam() {
-        ConfigBag parameters = BrooklynTaskTags.getCurrentEffectorParameters();
-        if (parameters != null) {
-            return parameters.get(StopSoftwareParameters.STOP_PROCESS_MODE);
-        } else {
-            return StopSoftwareParameters.STOP_PROCESS_MODE.getDefaultValue();
-        }
-    }
-
-    @Override
-    protected void preRestart() {
-        super.preRestart();
-        //restart will kill the process, try to shut down before that
-        shutdownGracefully();
-        DynamicTasks.queue("pre-restart", new Runnable() { public void run() {
-            //set by shutdown - clear it so the entity starts cleanly. Does the indicator bring any value at all?
-            ServiceNotUpLogic.clearNotUpIndicator(BrooklynNodeImpl.this, SHUTDOWN.getName());
-        }});
-    }
-
-    private void shutdownGracefully() {
-        // Shutdown only if accessible: any of stop_* could have already been called.
-        // Don't check serviceUp=true because stop() will already have set serviceUp=false && expectedState=stopping
-        if (Boolean.TRUE.equals(getAttribute(BrooklynNode.WEB_CONSOLE_ACCESSIBLE))) {
-            queueShutdownTask();
-            queueWaitExitTask();
-        } else {
-            log.info("Skipping graceful shutdown call, because web-console not up for {}", this);
-        }
-    }
-
-    private void queueWaitExitTask() {
-        //give time to the process to die gracefully after closing the shutdown call
-        DynamicTasks.queue(Tasks.builder().name("wait for graceful stop").body(new Runnable() {
-            @Override
-            public void run() {
-                DynamicTasks.markInessential();
-                boolean cleanExit = Repeater.create()
-                    .until(new Callable<Boolean>() {
-                        @Override
-                        public Boolean call() throws Exception {
-                            return !getDriver().isRunning();
-                        }
-                    })
-                    .backoffTo(Duration.ONE_SECOND)
-                    .limitTimeTo(Duration.ONE_MINUTE)
-                    .run();
-                if (!cleanExit) {
-                    log.warn("Tenant " + this + " didn't stop cleanly after shutdown. Timeout waiting for process exit.");
-                }
-            }
-        }).build());
-    }
-
-    @Override
-    protected void postStop() {
-        super.postStop();
-        if (isMachineStopped()) {
-            // Don't unmanage in entity's task context as it will self-cancel the task. Wait for the stop effector to complete (and all parent entity tasks).
-            // If this is not enough (still getting Caused by: java.util.concurrent.CancellationException: null) then
-            // we could wait for BrooklynTaskTags.getTasksInEntityContext(ExecutionManager, this).isEmpty();
-            Task<?> stopEffectorTask = BrooklynTaskTags.getClosestEffectorTask(Tasks.current(), Startable.STOP);
-            Task<?> topEntityTask = getTopEntityTask(stopEffectorTask);
-            getManagementContext().getExecutionManager().submit(new UnmanageTask(topEntityTask, this));
-        }
-    }
-
-    private Task<?> getTopEntityTask(Task<?> stopEffectorTask) {
-        Entity context = BrooklynTaskTags.getContextEntity(stopEffectorTask);
-        Task<?> topTask = stopEffectorTask;
-        while (true) {
-            Task<?> parentTask = topTask.getSubmittedByTask();
-            Entity parentContext = BrooklynTaskTags.getContextEntity(parentTask);
-            if (parentTask == null || parentContext != context) {
-                return topTask;
-            } else {
-                topTask = parentTask;
-            }
-        }
-    }
-
-    private boolean isMachineStopped() {
-        // Don't rely on effector parameters, check if there is still a machine running.
-        // If the entity was previously stopped with STOP_MACHINE_MODE=StopMode.NEVER
-        // and a second time with STOP_MACHINE_MODE=StopMode.IF_NOT_STOPPED, then the
-        // machine is still running, but there is no deterministic way to infer this from
-        // the parameters alone.
-        return Locations.findUniqueSshMachineLocation(this.getLocations()).isAbsent();
-    }
-
-    private void queueShutdownTask() {
-        ConfigBag stopParameters = BrooklynTaskTags.getCurrentEffectorParameters();
-        ConfigBag shutdownParameters;
-        if (stopParameters != null) {
-            shutdownParameters = ConfigBag.newInstanceCopying(stopParameters);
-        } else {
-            shutdownParameters = ConfigBag.newInstance();
-        }
-        shutdownParameters.putIfAbsent(ShutdownEffector.REQUEST_TIMEOUT, Duration.ONE_MINUTE);
-        shutdownParameters.putIfAbsent(ShutdownEffector.FORCE_SHUTDOWN_ON_ERROR, Boolean.TRUE);
-        TaskAdaptable<Void> shutdownTask = Effectors.invocation(this, SHUTDOWN, shutdownParameters);
-        //Mark inessential so that even if it fails the process stop task will run afterwards to clean up.
-        TaskTags.markInessential(shutdownTask);
-        DynamicTasks.queue(shutdownTask);
-    }
-
-    public static class DeployBlueprintEffectorBody extends EffectorBody<String> implements DeployBlueprintEffector {
-        public static final Effector<String> DEPLOY_BLUEPRINT = Effectors.effector(BrooklynNode.DEPLOY_BLUEPRINT).impl(new DeployBlueprintEffectorBody()).build();
-        
-        // TODO support YAML parsing
-        // TODO define a new type YamlMap for the config key which supports coercing from string and from map
-        @SuppressWarnings("unchecked")
-        public static Map<String,Object> asMap(ConfigBag parameters, ConfigKey<?> key) {
-            Object v = parameters.getStringKey(key.getName());
-            if (v==null || (v instanceof String && Strings.isBlank((String)v)))
-                return null;
-            if (v instanceof Map) 
-                return (Map<String, Object>) v;
-            
-            if (v instanceof String) {
-                // TODO ideally, parse YAML 
-                return new Gson().fromJson((String)v, Map.class);
-            }
-            throw new IllegalArgumentException("Invalid "+JavaClassNames.simpleClassName(v)+" value for "+key+": "+v);
-        }
-        
-        @Override
-        public String call(ConfigBag parameters) {
-            if (log.isDebugEnabled())
-                log.debug("Deploying blueprint to "+entity()+": "+parameters);
-            String plan = extractPlanYamlString(parameters);
-            return submitPlan(plan);
-        }
-
-        protected String extractPlanYamlString(ConfigBag parameters) {
-            Object planRaw = parameters.getStringKey(BLUEPRINT_CAMP_PLAN.getName());
-            if (planRaw instanceof String && Strings.isBlank((String)planRaw)) planRaw = null;
-            
-            String url = parameters.get(BLUEPRINT_TYPE);
-            if (url!=null && planRaw!=null)
-                throw new IllegalArgumentException("Cannot supply both plan and url");
-            if (url==null && planRaw==null)
-                throw new IllegalArgumentException("Must supply plan or url");
-            
-            Map<String, Object> config = asMap(parameters, BLUEPRINT_CONFIG);
-            
-            if (planRaw==null) {
-                planRaw = Jsonya.at("services").list().put("serviceType", url).putIfNotNull("brooklyn.config", config).getRootMap();
-            } else { 
-                if (config!=null)
-                    throw new IllegalArgumentException("Cannot supply plan with config");
-            }
-            
-            // planRaw might be a yaml string, or a map; if a map, convert to string
-            if (planRaw instanceof Map)
-                planRaw = Jsonya.of((Map<?,?>)planRaw).toString();
-            if (!(planRaw instanceof String))
-                throw new IllegalArgumentException("Invalid "+JavaClassNames.simpleClassName(planRaw)+" value for CAMP plan: "+planRaw);
-            
-            // now *all* the data is in planRaw; that is what will be submitted
-            return (String)planRaw;
-        }
-        
-        @VisibleForTesting
-        // Integration test for this in BrooklynNodeIntegrationTest in this project doesn't use this method,
-        // but a Unit test for this does, in DeployBlueprintTest -- but in the REST server project (since it runs against local) 
-        public String submitPlan(final String plan) {
-            final MutableMap<String, String> headers = MutableMap.of(com.google.common.net.HttpHeaders.CONTENT_TYPE, "application/yaml");
-            final AtomicReference<byte[]> response = new AtomicReference<byte[]>();
-            Repeater.create()
-                .every(Duration.ONE_SECOND)
-                .backoffTo(Duration.FIVE_SECONDS)
-                .limitTimeTo(Duration.minutes(5))
-                .repeat(Runnables.doNothing())
-                .rethrowExceptionImmediately()
-                .until(new Callable<Boolean>() {
-                    @Override
-                    public Boolean call() {
-                        HttpToolResponse result = ((BrooklynNode)entity()).http()
-                                //will throw on non-{2xx, 403} response
-                                .responseSuccess(Predicates.<Integer>or(ResponseCodePredicates.success(), Predicates.equalTo(HttpStatus.SC_FORBIDDEN)))
-                                .post("/v1/applications", headers, plan.getBytes());
-                        if (result.getResponseCode() == HttpStatus.SC_FORBIDDEN) {
-                            log.debug("Remote is not ready to accept requests, response is " + result.getResponseCode());
-                            return false;
-                        } else {
-                            byte[] content = result.getContent();
-                            response.set(content);
-                            return true;
-                        }
-                    }
-                })
-                .runRequiringTrue();
-            return (String)new Gson().fromJson(new String(response.get()), Map.class).get("entityId");
-        }
-    }
-
-    public static class ShutdownEffectorBody extends EffectorBody<Void> implements ShutdownEffector {
-        public static final Effector<Void> SHUTDOWN = Effectors.effector(BrooklynNode.SHUTDOWN).impl(new ShutdownEffectorBody()).build();
-
-        @Override
-        public Void call(ConfigBag parameters) {
-            MutableMap<String, String> formParams = MutableMap.of();
-            Lifecycle initialState = entity().getAttribute(Attributes.SERVICE_STATE_ACTUAL);
-            ServiceStateLogic.setExpectedState(entity(), Lifecycle.STOPPING);
-            for (ConfigKey<?> k: new ConfigKey<?>[] { STOP_APPS_FIRST, FORCE_SHUTDOWN_ON_ERROR, SHUTDOWN_TIMEOUT, REQUEST_TIMEOUT, DELAY_FOR_HTTP_RETURN })
-                formParams.addIfNotNull(k.getName(), toNullableString(parameters.get(k)));
-            try {
-                log.debug("Shutting down "+entity()+" with "+formParams);
-                HttpToolResponse resp = ((BrooklynNode)entity()).http()
-                    .post("/v1/server/shutdown",
-                        ImmutableMap.of("Brooklyn-Allow-Non-Master-Access", "true"),
-                        formParams);
-                if (resp.getResponseCode() != HttpStatus.SC_NO_CONTENT) {
-                    throw new IllegalStateException("Response code "+resp.getResponseCode());
-                }
-            } catch (Exception e) {
-                Exceptions.propagateIfFatal(e);
-                throw new PropagatedRuntimeException("Error shutting down remote node "+entity()+" (in state "+initialState+"): "+Exceptions.collapseText(e), e);
-            }
-            ServiceNotUpLogic.updateNotUpIndicator(entity(), SHUTDOWN.getName(), "Shutdown of remote node has completed successfuly");
-            return null;
-        }
-
-        private static String toNullableString(Object obj) {
-            if (obj == null) {
-                return null;
-            } else {
-                return obj.toString();
-            }
-        }
-
-    }
-
-    public static class StopNodeButLeaveAppsEffectorBody extends EffectorBody<Void> implements StopNodeButLeaveAppsEffector {
-        public static final Effector<Void> STOP_NODE_BUT_LEAVE_APPS = Effectors.effector(BrooklynNode.STOP_NODE_BUT_LEAVE_APPS).impl(new StopNodeButLeaveAppsEffectorBody()).build();
-
-        @Override
-        public Void call(ConfigBag parameters) {
-            Duration timeout = parameters.get(TIMEOUT);
-
-            ConfigBag stopParameters = ConfigBag.newInstanceCopying(parameters);
-            stopParameters.put(ShutdownEffector.STOP_APPS_FIRST, Boolean.FALSE);
-            stopParameters.putIfAbsent(ShutdownEffector.SHUTDOWN_TIMEOUT, timeout);
-            stopParameters.putIfAbsent(ShutdownEffector.REQUEST_TIMEOUT, timeout);
-            DynamicTasks.queue(Effectors.invocation(entity(), STOP, stopParameters)).asTask().getUnchecked();
-            return null;
-        }
-    }
-
-    public static class StopNodeAndKillAppsEffectorBody extends EffectorBody<Void> implements StopNodeAndKillAppsEffector {
-        public static final Effector<Void> STOP_NODE_AND_KILL_APPS = Effectors.effector(BrooklynNode.STOP_NODE_AND_KILL_APPS).impl(new StopNodeAndKillAppsEffectorBody()).build();
-
-        @Override
-        public Void call(ConfigBag parameters) {
-            Duration timeout = parameters.get(TIMEOUT);
-
-            ConfigBag stopParameters = ConfigBag.newInstanceCopying(parameters);
-            stopParameters.put(ShutdownEffector.STOP_APPS_FIRST, Boolean.TRUE);
-            stopParameters.putIfAbsent(ShutdownEffector.SHUTDOWN_TIMEOUT, timeout);
-            stopParameters.putIfAbsent(ShutdownEffector.REQUEST_TIMEOUT, timeout);
-            DynamicTasks.queue(Effectors.invocation(entity(), STOP, stopParameters)).asTask().getUnchecked();
-            return null;
-        }
-    }
-
-    public List<String> getClasspath() {
-        List<String> classpath = getConfig(CLASSPATH);
-        if (classpath == null || classpath.isEmpty()) {
-            classpath = getManagementContext().getConfig().getConfig(CLASSPATH);
-        }
-        return classpath;
-    }
-    
-    protected List<String> getEnabledHttpProtocols() {
-        return getAttribute(ENABLED_HTTP_PROTOCOLS);
-    }
-    
-    protected boolean isHttpProtocolEnabled(String protocol) {
-        List<String> protocols = getAttribute(ENABLED_HTTP_PROTOCOLS);
-        for (String contender : protocols) {
-            if (protocol.equalsIgnoreCase(contender)) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    @Override
-    protected void connectSensors() {
-        super.connectSensors();
-        
-        // TODO what sensors should we poll?
-        ConfigToAttributes.apply(this);
-
-        URI webConsoleUri;
-        if (isHttpProtocolEnabled("http")) {
-            int port = getConfig(PORT_MAPPER).apply(getAttribute(HTTP_PORT));
-            HostAndPort accessible = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, port);
-            webConsoleUri = URI.create(String.format("http://%s:%s", accessible.getHostText(), accessible.getPort()));
-        } else if (isHttpProtocolEnabled("https")) {
-            int port = getConfig(PORT_MAPPER).apply(getAttribute(HTTPS_PORT));
-            HostAndPort accessible = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, port);
-            webConsoleUri = URI.create(String.format("https://%s:%s", accessible.getHostText(), accessible.getPort()));
-        } else {
-            // web-console is not enabled
-            webConsoleUri = null;
-        }
-        setAttribute(WEB_CONSOLE_URI, webConsoleUri);
-
-        if (webConsoleUri != null) {
-            httpFeed = HttpFeed.builder()
-                    .entity(this)
-                    .period(getConfig(POLL_PERIOD))
-                    .baseUri(webConsoleUri)
-                    .credentialsIfNotNull(getConfig(MANAGEMENT_USER), getConfig(MANAGEMENT_PASSWORD))
-                    .poll(new HttpPollConfig<Boolean>(WEB_CONSOLE_ACCESSIBLE)
-                            .suburl("/v1/server/healthy")
-                            .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.cast(Boolean.class)))
-                            //if using an old distribution the path doesn't exist, but at least the instance is responding
-                            .onFailure(HttpValueFunctions.responseCodeEquals(404))
-                            .setOnException(false))
-                    .poll(new HttpPollConfig<ManagementNodeState>(MANAGEMENT_NODE_STATE)
-                            .suburl("/v1/server/ha/state")
-                            .onSuccess(Functionals.chain(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.cast(String.class)), Enums.fromStringFunction(ManagementNodeState.class)))
-                            .setOnFailureOrException(null))
-                    // TODO sensors for load, size, etc
-                    .build();
-
-            if (!Lifecycle.RUNNING.equals(getAttribute(SERVICE_STATE_ACTUAL))) {
-                // TODO when updating the map, if it would change from empty to empty on a successful run (see in nginx)
-                ServiceNotUpLogic.updateNotUpIndicator(this, WEB_CONSOLE_ACCESSIBLE, "No response from the web console yet");
-            }
-            addEnricher(Enrichers.builder().updatingMap(Attributes.SERVICE_NOT_UP_INDICATORS)
-                .from(WEB_CONSOLE_ACCESSIBLE)
-                .computing(Functionals.ifNotEquals(true).value("URL where Brooklyn listens is not answering correctly") )
-                .build());
-        } else {
-            connectServiceUpIsRunning();
-        }
-    }
-    
-    @Override
-    protected void disconnectSensors() {
-        super.disconnectSensors();
-        disconnectServiceUpIsRunning();
-        if (httpFeed != null) httpFeed.stop();
-    }
-
-    @Override
-    public EntityHttpClient http() {
-        return new EntityHttpClientImpl(this, BrooklynNode.WEB_CONSOLE_URI);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java
deleted file mode 100644
index 13a099e..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNodeSshDriver.java
+++ /dev/null
@@ -1,395 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import static java.lang.String.format;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.InputStream;
-import java.net.InetAddress;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-import brooklyn.entity.brooklynnode.BrooklynNode.ExistingFileBehaviour;
-import brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-import brooklyn.entity.software.SshEffectorTasks;
-
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.drivers.downloads.DownloadSubstituters;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.file.ArchiveBuilder;
-import org.apache.brooklyn.util.core.file.ArchiveUtils;
-import org.apache.brooklyn.util.core.internal.ssh.SshTool;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.net.Networking;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.ssh.BashCommands;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.apache.brooklyn.util.text.Strings;
-
-import com.google.common.base.Objects;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
-
-public class BrooklynNodeSshDriver extends JavaSoftwareProcessSshDriver implements BrooklynNodeDriver {
-    
-    public BrooklynNodeSshDriver(BrooklynNodeImpl entity, SshMachineLocation machine) {
-        super(entity, machine);
-    }
-
-    @Override
-    public BrooklynNodeImpl getEntity() {
-        return (BrooklynNodeImpl) super.getEntity();
-    }
-
-    public String getBrooklynHome() {
-        return getRunDir();
-    }
-
-    @Override
-    protected String getLogFileLocation() {
-        return Os.mergePathsUnix(getRunDir(), "console");
-    }
-    
-    protected String getPidFile() {
-        return Os.mergePathsUnix(getRunDir(), "pid_java");
-    }
-    
-    @Override
-    protected String getInstallLabelExtraSalt() {
-        String downloadUrl = entity.getConfig(BrooklynNode.DOWNLOAD_URL);
-        String uploadUrl = entity.getConfig(BrooklynNode.DISTRO_UPLOAD_URL);
-        if (Objects.equal(downloadUrl, BrooklynNode.DOWNLOAD_URL.getConfigKey().getDefaultValue()) &&
-                Objects.equal(uploadUrl, BrooklynNode.DISTRO_UPLOAD_URL.getDefaultValue())) {
-            // if both are at the default value, then no salt
-            return null;
-        }
-        return Identifiers.makeIdFromHash(Objects.hashCode(downloadUrl, uploadUrl));
-    }
-
-    @Override
-    public void preInstall() {
-        resolver = Entities.newDownloader(this);
-        String subpath = entity.getConfig(BrooklynNode.SUBPATH_IN_ARCHIVE);
-        if (subpath==null) {
-            // assume the dir name is `basename-VERSION` where download link is `basename-VERSION-dist.tar.gz`
-            String uploadUrl = entity.getConfig(BrooklynNode.DISTRO_UPLOAD_URL);
-            String origDownloadName = uploadUrl;
-            if (origDownloadName==null) 
-                origDownloadName = entity.getAttribute(BrooklynNode.DOWNLOAD_URL);
-            if (origDownloadName!=null) {
-                // BasicDownloadResolver makes it crazy hard to get the template-evaluated value of DOWNLOAD_URL
-                origDownloadName = DownloadSubstituters.substitute(origDownloadName, DownloadSubstituters.getBasicEntitySubstitutions(this));
-                origDownloadName = Urls.decode(origDownloadName);
-                origDownloadName = Urls.getBasename(origDownloadName);
-                String downloadName = origDownloadName;
-                downloadName = Strings.removeFromEnd(downloadName, ".tar.gz");
-                downloadName = Strings.removeFromEnd(downloadName, ".tgz");
-                downloadName = Strings.removeFromEnd(downloadName, ".zip");
-                if (!downloadName.equals(origDownloadName)) {
-                    downloadName = Strings.removeFromEnd(downloadName, "-dist");
-                    subpath = downloadName;
-                }
-            }
-        }
-        if (subpath==null) subpath = format("brooklyn-dist-%s", getVersion());
-        setExpandedInstallDir(Os.mergePaths(getInstallDir(), resolver.getUnpackedDirectoryName(subpath)));
-    }
-
-    @Override
-    public void clearInstallDir() {
-        super.setInstallDir(null);
-        super.setExpandedInstallDir(null);
-    }
-    
-    @Override
-    public void install() {
-        String uploadUrl = entity.getConfig(BrooklynNode.DISTRO_UPLOAD_URL);
-        
-        // Need to explicitly give file, because for snapshot URLs you don't get a clean filename from the URL.
-        // This filename is used to generate the first URL to try: [BROOKLYN_VERSION_BELOW]
-        // file://$HOME/.brooklyn/repository/BrooklynNode/0.8.0-SNAPSHOT/brooklynnode-0.8.0-snapshot.tar.gz
-        // (DOWNLOAD_URL overrides this and has a default which comes from maven)
-        List<String> urls = resolver.getTargets();
-        String saveAs = resolver.getFilename();
-        
-        newScript("createInstallDir")
-                .body.append("mkdir -p "+getInstallDir())
-                .failOnNonZeroResultCode()
-                .execute();
-
-        List<String> commands = Lists.newArrayList();
-        // TODO use machine.installTo ... but that only works w a single location currently
-        if (uploadUrl != null) {
-            // Only upload if not already installed
-            boolean exists = newScript("checkIfInstalled")
-                    .body.append("cd "+getInstallDir(), "test -f BROOKLYN")
-                    .execute() == 0;
-            if (!exists) {
-                InputStream distroStream = resource.getResourceFromUrl(uploadUrl);
-                getMachine().copyTo(distroStream, getInstallDir()+"/"+saveAs);
-            }
-        } else {
-            commands.addAll(BashCommands.commandsToDownloadUrlsAs(urls, saveAs));
-        }
-        commands.add(BashCommands.INSTALL_TAR);
-        commands.add("tar xzfv " + saveAs);
-        
-        newScript(INSTALLING).
-                failOnNonZeroResultCode().
-                body.append(commands).execute();
-    }
-
-    @Override
-    public void customize() {
-        newScript(CUSTOMIZING)
-                .failOnNonZeroResultCode()
-                .body.append(
-                        // workaround for AMP distribution placing everything in the root of this archive, but
-                        // brooklyn distribution placing everything in a subdirectory: check to see if subdirectory
-                        // with expected name exists; symlink to same directory if it doesn't
-                        // FIXME remove when all downstream usages don't use this
-                        format("[ -d %1$s ] || ln -s . %1$s", getExpandedInstallDir(), getExpandedInstallDir()),
-                        
-                        // previously we only copied bin,conf and set BROOKLYN_HOME to the install dir;
-                        // but that does not play nicely if installing dists other than brooklyn
-                        // (such as what is built by our artifact)  
-                        format("cp -R %s/* .", getExpandedInstallDir()),
-                        "mkdir -p ./lib/")
-                .execute();
-        
-        SshMachineLocation machine = getMachine();
-        BrooklynNode entity = getEntity();
-        
-        String brooklynGlobalPropertiesRemotePath = entity.getConfig(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_REMOTE_PATH);
-        String brooklynGlobalPropertiesContents = entity.getConfig(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_CONTENTS);
-        String brooklynGlobalPropertiesUri = entity.getConfig(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_URI);
-
-        String brooklynLocalPropertiesRemotePath = processTemplateContents(entity.getConfig(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_REMOTE_PATH));
-        String brooklynLocalPropertiesContents = entity.getConfig(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_CONTENTS);
-        String brooklynLocalPropertiesUri = entity.getConfig(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_URI);
-
-        String brooklynCatalogRemotePath = entity.getConfig(BrooklynNode.BROOKLYN_CATALOG_REMOTE_PATH);
-        String brooklynCatalogContents = entity.getConfig(BrooklynNode.BROOKLYN_CATALOG_CONTENTS);
-        String brooklynCatalogUri = entity.getConfig(BrooklynNode.BROOKLYN_CATALOG_URI);
-
-        // Override the ~/.brooklyn/brooklyn.properties if required
-        if (brooklynGlobalPropertiesContents != null || brooklynGlobalPropertiesUri != null) {
-            ExistingFileBehaviour onExisting = entity.getConfig(BrooklynNode.ON_EXISTING_PROPERTIES_FILE);
-            Integer checkExists = DynamicTasks.queue(SshEffectorTasks.ssh("ls \""+brooklynGlobalPropertiesRemotePath+"\"").allowingNonZeroExitCode()).get();
-            boolean doUpload = true;
-            if (checkExists==0) {
-                switch (onExisting) {
-                case USE_EXISTING: doUpload = false; break;
-                case OVERWRITE: break;
-                case DO_NOT_USE: 
-                    throw new IllegalStateException("Properties file "+brooklynGlobalPropertiesContents+" already exists and "+
-                        "even though it is not being used, content for it was supplied");
-                case FAIL: 
-                    throw new IllegalStateException("Properties file "+brooklynGlobalPropertiesContents+" already exists and "+
-                        BrooklynNode.ON_EXISTING_PROPERTIES_FILE+" response is to fail");
-                default:
-                    throw new IllegalStateException("Properties file "+brooklynGlobalPropertiesContents+" already exists and "+
-                        BrooklynNode.ON_EXISTING_PROPERTIES_FILE+" response "+onExisting+" is unknown");
-                }
-            }
-            if (onExisting==ExistingFileBehaviour.DO_NOT_USE) {
-                log.warn("Global properties supplied when told not to use them; no global properties exists, so it will be installed, but it will not be used.");
-            }
-            if (doUpload)
-                uploadFileContents(brooklynGlobalPropertiesContents, brooklynGlobalPropertiesUri, brooklynGlobalPropertiesRemotePath);
-        }
-        
-        // Upload a local-brooklyn.properties if required
-        if (brooklynLocalPropertiesContents != null || brooklynLocalPropertiesUri != null) {
-            uploadFileContents(brooklynLocalPropertiesContents, brooklynLocalPropertiesUri, brooklynLocalPropertiesRemotePath);
-        }
-
-        // Override the ~/.brooklyn/catalog.xml if required
-        if (brooklynCatalogContents != null || brooklynCatalogUri != null) {
-            uploadFileContents(brooklynCatalogContents, brooklynCatalogUri, brooklynCatalogRemotePath);
-        }
-
-        // Copy additional resources to the server
-        for (Map.Entry<String,String> entry : getEntity().getAttribute(BrooklynNode.COPY_TO_RUNDIR).entrySet()) {
-            Map<String, String> substitutions = ImmutableMap.of("RUN", getRunDir());
-            String localResource = entry.getKey();
-            String remotePath = entry.getValue();
-            String resolvedRemotePath = remotePath;
-            for (Map.Entry<String,String> substitution : substitutions.entrySet()) {
-                String key = substitution.getKey();
-                String val = substitution.getValue();
-                resolvedRemotePath = resolvedRemotePath.replace("${"+key+"}", val).replace("$"+key, val);
-            }
-            machine.copyTo(MutableMap.of("permissions", "0600"), resource.getResourceFromUrl(localResource), resolvedRemotePath);
-        }
-
-        for (String entry : getEntity().getClasspath()) {
-            // If a local folder, then create archive from contents first
-            if (Urls.isDirectory(entry)) {
-                File jarFile = ArchiveBuilder.jar().addDirContentsAt(new File(entry), "").create();
-                entry = jarFile.getAbsolutePath();
-            }
-
-            // Determine filename
-            String destFile = entry.contains("?") ? entry.substring(0, entry.indexOf('?')) : entry;
-            destFile = destFile.substring(destFile.lastIndexOf('/') + 1);
-
-            ArchiveUtils.deploy(MutableMap.<String, Object>of(), entry, machine, getRunDir(), Os.mergePaths(getRunDir(), "lib"), destFile);
-        }
-        
-        String cmd = entity.getConfig(BrooklynNode.EXTRA_CUSTOMIZATION_SCRIPT);
-        if (Strings.isNonBlank(cmd)) {
-            DynamicTasks.queueIfPossible( SshEffectorTasks.ssh(cmd).summary("Bespoke BrooklynNode customization script")
-                .requiringExitCodeZero() )
-                .orSubmitAndBlock(getEntity());
-        }
-    }
-
-    @SuppressWarnings("deprecation")
-    @Override
-    public void launch() {
-        String app = getEntity().getAttribute(BrooklynNode.APP);
-        String locations = getEntity().getAttribute(BrooklynNode.LOCATIONS);
-        boolean hasLocalBrooklynProperties = getEntity().getConfig(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_CONTENTS) != null || getEntity().getConfig(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_URI) != null;
-        String localBrooklynPropertiesPath = processTemplateContents(getEntity().getConfig(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_REMOTE_PATH));
-        InetAddress bindAddress = getEntity().getAttribute(BrooklynNode.WEB_CONSOLE_BIND_ADDRESS);
-        InetAddress publicAddress = getEntity().getAttribute(BrooklynNode.WEB_CONSOLE_PUBLIC_ADDRESS);
-
-        String cmd = entity.getConfig(BrooklynNode.LAUNCH_COMMAND);
-        if (Strings.isBlank(cmd)) cmd = "./bin/brooklyn";
-        cmd = "nohup " + cmd + " launch";
-        if (app != null) {
-            cmd += " --app "+app;
-        }
-        if (locations != null) {
-            cmd += " --locations "+locations;
-        }
-        if (entity.getConfig(BrooklynNode.ON_EXISTING_PROPERTIES_FILE)==ExistingFileBehaviour.DO_NOT_USE) {
-            cmd += " --noGlobalBrooklynProperties";
-        }
-        if (hasLocalBrooklynProperties) {
-            cmd += " --localBrooklynProperties "+localBrooklynPropertiesPath;
-        }
-        Integer webPort = null;
-        if (getEntity().isHttpProtocolEnabled("http")) {
-            webPort = getEntity().getAttribute(BrooklynNode.HTTP_PORT);
-            Networking.checkPortsValid(ImmutableMap.of("webPort", webPort));
-        } else if (getEntity().isHttpProtocolEnabled("https")) {
-            webPort = getEntity().getAttribute(BrooklynNode.HTTPS_PORT);
-            Networking.checkPortsValid(ImmutableMap.of("webPort", webPort));
-        }
-        if (webPort!=null) {
-            cmd += " --port "+webPort;
-        } else if (getEntity().getEnabledHttpProtocols().isEmpty()) {
-            // TODO sensors will probably not work in this mode
-            cmd += " --noConsole";
-        } else {
-            throw new IllegalStateException("Unknown web protocol in "+BrooklynNode.ENABLED_HTTP_PROTOCOLS+" "
-                + "("+getEntity().getEnabledHttpProtocols()+"); expecting 'http' or 'https'");
-        }
-        
-        if (bindAddress != null) {
-            cmd += " --bindAddress "+bindAddress.getHostAddress();
-        }
-        if (publicAddress != null) {
-            cmd += " --publicAddress "+publicAddress.getHostName();
-        }
-        if (getEntity().getAttribute(BrooklynNode.NO_WEB_CONSOLE_AUTHENTICATION)) {
-            cmd += " --noConsoleSecurity";
-        }
-        if (Strings.isNonBlank(getEntity().getConfig(BrooklynNode.EXTRA_LAUNCH_PARAMETERS))) {
-            cmd += " "+getEntity().getConfig(BrooklynNode.EXTRA_LAUNCH_PARAMETERS);
-        }
-        cmd += format(" >> %s/console 2>&1 </dev/null &", getRunDir());
-        
-        log.info("Starting brooklyn on {} using command {}", getMachine(), cmd);
-        
-        // relies on brooklyn script creating pid file
-        newScript(ImmutableMap.of("usePidFile", 
-                entity.getConfig(BrooklynNode.LAUNCH_COMMAND_CREATES_PID_FILE) ? false : getPidFile()), 
-            LAUNCHING).
-            body.append(
-                format("export BROOKLYN_CLASSPATH=%s", getRunDir()+"/lib/\"*\""),
-                format("export BROOKLYN_HOME=%s", getBrooklynHome()),
-                format(cmd)
-        ).failOnNonZeroResultCode().execute();
-    }
-
-    @Override
-    public boolean isRunning() {
-        Map<String,String> flags = ImmutableMap.of("usePidFile", getPidFile());
-        int result = newScript(flags, CHECK_RUNNING).execute();
-        return result == 0;
-    }
-
-    @Override
-    public void stop() {
-        Map<String,String> flags = ImmutableMap.of("usePidFile", getPidFile());
-        newScript(flags, STOPPING).execute();
-    }
-
-    @Override
-    public void kill() {
-        Map<String,String> flags = ImmutableMap.of("usePidFile", getPidFile());
-        newScript(flags, KILLING).execute();
-    }
-    
-    @Override
-    public Map<String, String> getShellEnvironment() {
-        Map<String, String> orig = super.getShellEnvironment();
-        String origClasspath = orig.get("CLASSPATH");
-        String newClasspath = (origClasspath == null ? "" : origClasspath+":") + 
-                getRunDir()+"/conf/" + ":" +
-                getRunDir()+"/lib/\"*\"";
-        Map<String,String> results = new LinkedHashMap<String,String>();
-        results.putAll(orig);
-        results.put("BROOKLYN_CLASSPATH", newClasspath);
-        results.put("BROOKLYN_HOME", getBrooklynHome());
-        results.put("RUN", getRunDir());
-        return results;
-    }
-    
-    private void uploadFileContents(String contents, String alternativeUri, String remotePath) {
-        checkNotNull(remotePath, "remotePath");
-        SshMachineLocation machine = getMachine();
-        String tempRemotePath = String.format("%s/upload.tmp", getRunDir());
-
-        if (contents == null && alternativeUri == null) {
-            throw new IllegalStateException("No contents supplied for file " + remotePath);
-        }
-        InputStream stream = contents != null
-                ? new ByteArrayInputStream(contents.getBytes())
-                : resource.getResourceFromUrl(alternativeUri);
-        Map<String, String> flags = MutableMap.of(SshTool.PROP_PERMISSIONS.getName(), "0600");
-        machine.copyTo(flags, stream, tempRemotePath);
-        newScript(CUSTOMIZING)
-                .failOnNonZeroResultCode()
-                .body.append(
-                        format("mkdir -p %s", remotePath.subSequence(0, remotePath.lastIndexOf("/"))),
-                        format("cp -p %s %s", tempRemotePath, remotePath),
-                        format("rm -f %s", tempRemotePath))
-                .execute();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/EntityHttpClient.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/EntityHttpClient.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/EntityHttpClient.java
deleted file mode 100644
index deed605..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/EntityHttpClient.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import java.util.Map;
-
-import org.apache.brooklyn.util.core.http.HttpTool;
-import org.apache.brooklyn.util.core.http.HttpToolResponse;
-
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-import com.google.common.collect.Range;
-
-/**
- * Helpful methods for making HTTP requests to {@link BrooklynNode} entities.
- */
-public interface EntityHttpClient {
-    public static class ResponseCodePredicates {
-        private static class ResponseCodeHealthyPredicate implements Predicate<Integer> {
-            @Override
-            public boolean apply(Integer input) {
-                return HttpTool.isStatusCodeHealthy(input);
-            }
-        }
-        public static Predicate<Integer> informational() {return Range.closed(100, 199);}
-        public static Predicate<Integer> success() {return new ResponseCodeHealthyPredicate();}
-        public static Predicate<Integer> redirect() {return Range.closed(300, 399);}
-        public static Predicate<Integer> clientError() {return Range.closed(400, 499);}
-        public static Predicate<Integer> serverError() {return Range.closed(500, 599);}
-        public static Predicate<Integer> invalid() {return Predicates.or(Range.atMost(99), Range.atLeast(600));}
-    }
-
-    /**
-     * @return An HTTP client builder configured to access the {@link
-     *         BrooklynNode#WEB_CONSOLE_URI web console URI} at the
-     *         given entity, or null if the entity has no URI.
-     */
-    public HttpTool.HttpClientBuilder getHttpClientForBrooklynNode();
-
-    /**
-     * Configure which response codes are treated as successful
-     * @param successPredicate A predicate which returns true is the response code is acceptable
-     * @return this
-     */
-    public EntityHttpClient responseSuccess(Predicate<Integer> responseSuccess);
-
-    /**
-     * Makes an HTTP GET to a Brooklyn node entity.
-     * @param path Relative path to resource on server, e.g v1/catalog
-     * @return The server's response
-     */
-    public HttpToolResponse get(String path);
-
-    /**
-     * Makes an HTTP POST to a Brooklyn node entity.
-     * @param path Relative path to resource on server, e.g v1/catalog
-     * @param body byte array of serialized JSON to attach to the request
-     * @return The server's response
-     */
-    public HttpToolResponse post(String path, Map<String, String> headers, byte[] body);
-
-    /**
-     * Makes an HTTP POST to a Brooklyn node entity.
-     * @param path Relative path to resource on server, e.g v1/catalog
-     * @param formParams The parameters to send in a x-www-form-urlencoded format
-     * @return The server's response
-     */
-    public HttpToolResponse post(String path, Map<String, String> headers, Map<String, String> formParams);
-
-    /**
-     * Makes an HTTP DELETE to a Brooklyn node entity.
-     * @param path Relative path to resource on server, e.g v1/catalog
-     * @return The server's response
-     */
-    public HttpToolResponse delete(String path, Map<String, String> headers);
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/EntityHttpClientImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/EntityHttpClientImpl.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/EntityHttpClientImpl.java
deleted file mode 100644
index f34ac15..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/EntityHttpClientImpl.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.net.URI;
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.http.HttpTool;
-import org.apache.brooklyn.util.core.http.HttpToolResponse;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.brooklyn.util.stream.Streams;
-import org.apache.http.auth.UsernamePasswordCredentials;
-import org.apache.http.client.HttpClient;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
-
-public class EntityHttpClientImpl implements EntityHttpClient {
-    private static final Logger LOG = LoggerFactory.getLogger(EntityHttpClientImpl.class);
-
-    protected static interface HttpCall {
-        public HttpToolResponse call(HttpClient client, URI uri);
-    }
-
-    protected Entity entity;
-    protected AttributeSensor<?> urlSensor;
-    protected ConfigKey<?> urlConfig;
-    protected Predicate<Integer> responseSuccess = ResponseCodePredicates.success();
-
-    protected EntityHttpClientImpl(Entity entity, AttributeSensor<?> urlSensor) {
-        this.entity = entity;
-        this.urlSensor = urlSensor;
-    }
-
-    protected EntityHttpClientImpl(Entity entity, ConfigKey<?> urlConfig) {
-        this.entity = entity;
-        this.urlConfig = urlConfig;
-    }
-
-    @Override
-    public HttpTool.HttpClientBuilder getHttpClientForBrooklynNode() {
-        String baseUrl = getEntityUrl();
-        HttpTool.HttpClientBuilder builder = HttpTool.httpClientBuilder()
-                .trustAll()
-                .laxRedirect(true)
-                .uri(baseUrl);
-        if (entity.getConfig(BrooklynNode.MANAGEMENT_USER) != null) {
-            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
-                    entity.getConfig(BrooklynNode.MANAGEMENT_USER),
-                    entity.getConfig(BrooklynNode.MANAGEMENT_PASSWORD));
-            builder.credentials(credentials);
-        }
-        return builder;
-    }
-
-    @Override
-    public EntityHttpClient responseSuccess(Predicate<Integer> responseSuccess) {
-        this.responseSuccess = checkNotNull(responseSuccess, "responseSuccess");
-        return this;
-    }
-
-    protected HttpToolResponse exec(String path, HttpCall httpCall) {
-        HttpClient client = Preconditions.checkNotNull(getHttpClientForBrooklynNode(), "No address info for "+entity)
-                .build();
-        String baseUri = getEntityUrl();
-        URI uri = URI.create(Urls.mergePaths(baseUri, path));
-
-        HttpToolResponse result;
-        try {
-            result = httpCall.call(client, uri);
-        } catch (Exception e) {
-            Exceptions.propagateIfFatal(e);
-            throw new IllegalStateException("Invalid response invoking " + uri + ": " + e, e);
-        }
-        Tasks.addTagDynamically(BrooklynTaskTags.tagForStream("http_response", Streams.byteArray(result.getContent())));
-        if (!responseSuccess.apply(result.getResponseCode())) {
-            LOG.warn("Invalid response invoking {}: response code {}\n{}: {}",
-                    new Object[]{uri, result.getResponseCode(), result, new String(result.getContent())});
-            throw new IllegalStateException("Invalid response invoking " + uri + ": response code " + result.getResponseCode());
-        }
-        return result;
-    }
-
-    @Override
-    public HttpToolResponse get(String path) {
-        return exec(path, new HttpCall() {
-            @Override
-            public HttpToolResponse call(HttpClient client, URI uri) {
-                return HttpTool.httpGet(client, uri, MutableMap.<String, String>of());
-            }
-        });
-    }
-
-    @Override
-    public HttpToolResponse post(String path, final Map<String, String> headers, final byte[] body) {
-        return exec(path, new HttpCall() {
-            @Override
-            public HttpToolResponse call(HttpClient client, URI uri) {
-                return HttpTool.httpPost(client, uri, headers, body);
-            }
-        });
-    }
-
-    @Override
-    public HttpToolResponse post(String path, final Map<String, String> headers, final Map<String, String> formParams) {
-        return exec(path, new HttpCall() {
-            @Override
-            public HttpToolResponse call(HttpClient client, URI uri) {
-                return HttpTool.httpPost(client, uri, headers, formParams);
-            }
-        });
-    }
-
-    protected String getEntityUrl() {
-        Preconditions.checkState(urlSensor == null ^ urlConfig == null, "Exactly one of urlSensor and urlConfig should be non-null for entity " + entity);
-        Object url = null;
-        if (urlSensor != null) {
-            url = entity.getAttribute(urlSensor);
-        } else if (urlConfig != null) {
-            url = entity.getConfig(urlConfig);
-        }
-        Preconditions.checkNotNull(url, "URL sensor " + urlSensor + " for entity " + entity + " is empty");
-        return url.toString();
-    }
-
-    @Override
-    public HttpToolResponse delete(String path, final Map<String, String> headers) {
-        return exec(path, new HttpCall() {
-            @Override
-            public HttpToolResponse call(HttpClient client, URI uri) {
-                return HttpTool.httpDelete(client, uri, headers);
-            }
-        });
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/LocalBrooklynNode.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/LocalBrooklynNode.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/LocalBrooklynNode.java
deleted file mode 100644
index 41714de..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/LocalBrooklynNode.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import org.apache.brooklyn.api.entity.ImplementedBy;
-
-/**
- * A {@link BrooklynNode} entity that represents the local Brooklyn service.
- * <p>
- * Management username and password can be specified in the {@code brooklyn.properties} file, as
- * either specific username and password (useful when the credentials are set with SHA-256 hashes
- * or via LDAP) or a username with separately configured webconsole plaintext password.
- * <pre>
- * brooklyn.entity.brooklynnode.local.user=admin
- * brooklyn.entity.brooklynnode.local.password=password
- * brooklyn.webconsole.security.user.admin.password=password
- * </pre>
- */
-@ImplementedBy(LocalBrooklynNodeImpl.class)
-public interface LocalBrooklynNode extends BrooklynNode {
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/LocalBrooklynNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/LocalBrooklynNodeImpl.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/LocalBrooklynNodeImpl.java
deleted file mode 100644
index 1096ea5..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/LocalBrooklynNodeImpl.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.util.text.Strings;
-
-public class LocalBrooklynNodeImpl extends BrooklynNodeImpl implements LocalBrooklynNode {
-
-    private static final String LOCAL_BROOKLYN_NODE_KEY = "brooklyn.entity.brooklynnode.local.%s";
-    private static final String BROOKLYN_WEBCONSOLE_PASSWORD_KEY = "brooklyn.webconsole.security.user.%s.password";
-
-    @Override
-    protected void connectSensors() {
-        // Override management username and password from brooklyn.properties
-        BrooklynProperties properties = (BrooklynProperties) getManagementContext().getConfig();
-        String user = (String) properties.get(String.format(LOCAL_BROOKLYN_NODE_KEY, "user"));
-        String password = (String) properties.get(String.format(LOCAL_BROOKLYN_NODE_KEY, "password"));
-        if (Strings.isBlank(password)) {
-            if (Strings.isBlank(user)) user = "admin";
-            password = (String) properties.get(String.format(BROOKLYN_WEBCONSOLE_PASSWORD_KEY, user));
-        }
-        if (Strings.isNonBlank(user) && Strings.isNonBlank(password)) {
-            setConfig(MANAGEMENT_USER, user);
-            setConfig(MANAGEMENT_PASSWORD, password);
-        }
-        super.connectSensors();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/RemoteEffectorBuilder.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/RemoteEffectorBuilder.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/RemoteEffectorBuilder.java
deleted file mode 100644
index fedeff9..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/RemoteEffectorBuilder.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Map;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.effector.core.Effectors.EffectorBuilder;
-import org.apache.brooklyn.util.core.http.HttpToolResponse;
-
-import brooklyn.entity.brooklynnode.BrooklynEntityMirrorImpl.RemoteEffector;
-
-import com.google.common.base.Function;
-
-public class RemoteEffectorBuilder {
-    private static class ResultParser implements Function<HttpToolResponse, String> {
-        @Override
-        public String apply(HttpToolResponse input) {
-            return input.getContentAsString();
-        }
-    }
-    
-
-    public static Collection<Effector<String>> of(Collection<?> cfgEffectors) {
-        Collection<Effector<String>> effectors = new ArrayList<Effector<String>>();
-        for (Object objEff : cfgEffectors) {
-            Map<?, ?> cfgEff = (Map<?, ?>)objEff;
-            String effName = (String)cfgEff.get("name");
-            String description = (String)cfgEff.get("description");
-
-            EffectorBuilder<String> eff = Effectors.effector(String.class, effName);
-            Collection<?> params = (Collection<?>)cfgEff.get("parameters");
-
-            /* The *return type* should NOT be included in the signature here.
-             * It might be a type known only at the mirrored brooklyn node
-             * (in which case loading it here would fail); or possibly it could
-             * be a different version of the type here, in which case the signature
-             * would look valid here, but deserializing it would fail.
-             * 
-             * Best to just pass the json representation back to the caller.
-             * (They won't be able to tell the difference between that and deserialize-then-serialize!)
-             */
-            
-            if (description != null) {
-                eff.description(description);
-            }
-
-            for (Object objParam : params) {
-                buildParam(eff, (Map<?, ?>)objParam);
-            }
-
-            eff.impl(new RemoteEffector<String>(effName, new ResultParser()));
-            effectors.add(eff.build());
-        }
-        return effectors;
-    }
-
-    private static void buildParam(EffectorBuilder<String> eff, Map<?, ?> cfgParam) {
-        String name = (String)cfgParam.get("name");
-        String description = (String)cfgParam.get("description");
-        String defaultValue = (String)cfgParam.get("defaultValue");
-
-        eff.parameter(Object.class, name, description, defaultValue /*TypeCoercions.coerce(defaultValue, paramType)*/);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/BrooklynClusterUpgradeEffectorBody.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/BrooklynClusterUpgradeEffectorBody.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/BrooklynClusterUpgradeEffectorBody.java
deleted file mode 100644
index 26ecaca..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/BrooklynClusterUpgradeEffectorBody.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode.effector;
-
-import java.io.File;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.concurrent.Callable;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.entity.Group;
-import org.apache.brooklyn.api.mgmt.TaskAdaptable;
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
-import org.apache.brooklyn.effector.core.EffectorBody;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.EntityPredicates;
-import org.apache.brooklyn.entity.core.EntityTasks;
-import org.apache.brooklyn.entity.group.DynamicCluster;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.brooklyn.util.time.Duration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.brooklynnode.BrooklynCluster;
-import brooklyn.entity.brooklynnode.BrooklynCluster.SelectMasterEffector;
-import brooklyn.entity.brooklynnode.BrooklynCluster.UpgradeClusterEffector;
-import brooklyn.entity.brooklynnode.BrooklynNode;
-import brooklyn.entity.brooklynnode.BrooklynNode.SetHighAvailabilityModeEffector;
-
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicates;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.Iterables;
-
-public class BrooklynClusterUpgradeEffectorBody extends EffectorBody<Void> implements UpgradeClusterEffector {
-    
-    private static final Logger log = LoggerFactory.getLogger(BrooklynClusterUpgradeEffectorBody.class);
-    
-    public static final Effector<Void> UPGRADE_CLUSTER = Effectors.effector(UpgradeClusterEffector.UPGRADE_CLUSTER)
-        .impl(new BrooklynClusterUpgradeEffectorBody()).build();
-
-    private final AtomicBoolean upgradeInProgress = new AtomicBoolean();
-
-    @Override
-    public Void call(ConfigBag parameters) {
-        if (!upgradeInProgress.compareAndSet(false, true)) {
-            throw new IllegalStateException("An upgrade is already in progress.");
-        }
-
-        EntitySpec<?> origMemberSpec = entity().getConfig(BrooklynCluster.MEMBER_SPEC);
-        Preconditions.checkNotNull(origMemberSpec, BrooklynCluster.MEMBER_SPEC.getName() + " is required for " + UpgradeClusterEffector.class.getName());
-
-        log.debug("Upgrading "+entity()+", changing "+BrooklynCluster.MEMBER_SPEC+" from "+origMemberSpec+" / "+origMemberSpec.getConfig());
-
-        boolean success = false;
-        try {
-            String newDownloadUrl = parameters.get(DOWNLOAD_URL);
-            
-            EntitySpec<?> newMemberSpec = EntitySpec.create(origMemberSpec);
-            
-            ConfigBag newConfig = ConfigBag.newInstance();
-            newConfig.putIfNotNull(DOWNLOAD_URL, newDownloadUrl);
-            newConfig.put(BrooklynNode.DISTRO_UPLOAD_URL, inferUploadUrl(newDownloadUrl));
-            newConfig.putAll(ConfigBag.newInstance(parameters.get(EXTRA_CONFIG)).getAllConfigAsConfigKeyMap());
-            newMemberSpec.configure(newConfig.getAllConfigAsConfigKeyMap());
-            
-            entity().setConfig(BrooklynCluster.MEMBER_SPEC, newMemberSpec);
-            
-            log.debug("Upgrading "+entity()+", new "+BrooklynCluster.MEMBER_SPEC+": "+newMemberSpec+" / "+newMemberSpec.getConfig()+" (adding: "+newConfig+")");
-            
-            upgrade(parameters);
-
-            success = true;
-        } finally {
-            if (!success) {
-                log.debug("Upgrading "+entity()+" failed, will rethrow after restoring "+BrooklynCluster.MEMBER_SPEC+" to: "+origMemberSpec);
-                entity().setConfig(BrooklynCluster.MEMBER_SPEC, origMemberSpec);
-            }
-            
-            upgradeInProgress.set(false);
-        }
-        return null;
-    }
-
-    private String inferUploadUrl(String newDownloadUrl) {
-        if (newDownloadUrl==null) return null;
-        boolean isLocal = "file".equals(Urls.getProtocol(newDownloadUrl)) || new File(newDownloadUrl).exists();
-        if (isLocal) {
-            return newDownloadUrl;
-        } else {
-            return null;
-        }
-    }
-
-    protected void upgrade(ConfigBag parameters) {
-        //TODO currently this will fight with auto-scaler policies; they must be turned off for upgrade to work
-
-        Group cluster = (Group)entity();
-        Collection<Entity> initialMembers = cluster.getMembers();
-        int initialClusterSize = initialMembers.size();
-        
-        if (!BrooklynNodeUpgradeEffectorBody.isPersistenceModeEnabled(cluster)) {
-            // would could try a `forcePersistNow`, but that's sloppy; 
-            // for now, require HA/persistence for upgrading 
-            DynamicTasks.queue( Tasks.warning("Check persistence", 
-                new IllegalStateException("Persistence does not appear to be enabled at this cluster. "
-                + "Cluster upgrade will not succeed unless a custom launch script enables it.")) );
-        }
-       
-        //TODO we'd like to disable these nodes as standby targets, ie in some 'hot standby but not available for failover' mode
-        //currently if failover happens to a new node, assumptions below may fail and the cluster may require manual repair
-
-        //1. Initially create a single node to check if it will launch successfully
-        TaskAdaptable<Collection<Entity>> initialNodeTask = DynamicTasks.queue(newCreateNodesTask(1, "Creating first upgraded version node"));
-
-        //2. If everything is OK with the first node launch the rest as well
-        @SuppressWarnings("unused")
-        TaskAdaptable<Collection<Entity>> remainingNodesTask = DynamicTasks.queue(newCreateNodesTask(initialClusterSize - 1, "Creating remaining upgraded version nodes ("+(initialClusterSize - 1)+")"));
-
-        //3. Once we have all nodes running without errors switch master
-        DynamicTasks.queue(Effectors.invocation(cluster, BrooklynCluster.SELECT_MASTER, MutableMap.of(SelectMasterEffector.NEW_MASTER_ID, 
-            Iterables.getOnlyElement(initialNodeTask.asTask().getUnchecked()).getId()))).asTask().getUnchecked();
-
-        //4. Stop the nodes which were running at the start of the upgrade call, but keep them around.
-        //   Should we create a quarantine-like zone for old stopped version?
-        //   For members that were created meanwhile - they will be using the new version already. If the new version
-        //   isn't good then they will fail to start as well, forcing the policies to retry (and succeed once the
-        //   URL is reverted).
-        
-        //any other nodes created via other means should also be using the new spec, so initialMembers will be all the old version nodes
-        DynamicTasks.queue(Effectors.invocation(BrooklynNode.STOP_NODE_BUT_LEAVE_APPS, Collections.emptyMap(), initialMembers)).asTask().getUnchecked();
-    }
-
-    private TaskAdaptable<Collection<Entity>> newCreateNodesTask(int size, String name) {
-        return Tasks.<Collection<Entity>>builder().name(name).body(new CreateNodesCallable(size)).build();
-    }
-
-    protected class CreateNodesCallable implements Callable<Collection<Entity>> {
-        private final int size;
-        public CreateNodesCallable(int size) {
-            this.size = size;
-        }
-        @Override
-        public Collection<Entity> call() throws Exception {
-            return createNodes(size);
-        }
-    }
-
-    protected Collection<Entity> createNodes(int nodeCnt) {
-        DynamicCluster cluster = (DynamicCluster)entity();
-
-        //1. Create the nodes
-        Collection<Entity> newNodes = cluster.resizeByDelta(nodeCnt);
-
-        //2. Wait for them to be RUNNING (or at least STARTING to have completed)
-        // (should already be the case, because above is synchronous and, we think, it will fail if start does not succeed)
-        DynamicTasks.queue(EntityTasks.requiringAttributeEventually(newNodes, Attributes.SERVICE_STATE_ACTUAL, 
-                Predicates.not(Predicates.equalTo(Lifecycle.STARTING)), Duration.minutes(30)));
-
-        //3. Set HOT_STANDBY in case it is not enabled on the command line ...
-        // TODO support via EntitySpec
-        DynamicTasks.queue(Effectors.invocation(
-                BrooklynNode.SET_HIGH_AVAILABILITY_MODE,
-                MutableMap.of(SetHighAvailabilityModeEffector.MODE, HighAvailabilityMode.HOT_STANDBY), 
-                newNodes)).asTask().getUnchecked();
-        //... and wait until all of the nodes change state
-        // TODO fail quicker if state changes to FAILED
-        DynamicTasks.queue(EntityTasks.requiringAttributeEventually(newNodes, BrooklynNode.MANAGEMENT_NODE_STATE, 
-                Predicates.equalTo(ManagementNodeState.HOT_STANDBY), Duration.FIVE_MINUTES));
-
-        // TODO also check that the nodes created all report the original master, in case persistence changes it
-        
-        //5. Just in case check if all of the nodes are SERVICE_UP (which would rule out ON_FIRE as well)
-        Collection<Entity> failedNodes = Collections2.filter(newNodes, EntityPredicates.attributeEqualTo(BrooklynNode.SERVICE_UP, Boolean.FALSE));
-        if (!failedNodes.isEmpty()) {
-            throw new IllegalStateException("Nodes " + failedNodes + " are not " + BrooklynNode.SERVICE_UP + " though successfully in " + ManagementNodeState.HOT_STANDBY);
-        }
-        return newNodes;
-    }
-
-}


[40/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormSshDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormSshDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormSshDriver.java
index 3df87fb..296ae16 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormSshDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormSshDriver.java
@@ -32,8 +32,8 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.zookeeper.ZooKeeperEnsemble;
-import org.apache.brooklyn.location.basic.Machines;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.Machines;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperSshDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperSshDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperSshDriver.java
index af55acc..9efd5bc 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperSshDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperSshDriver.java
@@ -27,7 +27,7 @@ import java.util.concurrent.ExecutionException;
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;
 import org.apache.brooklyn.util.os.Os;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/kafka/KafkaIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/kafka/KafkaIntegrationTest.java b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/kafka/KafkaIntegrationTest.java
index 0f4ef30..30a48da 100644
--- a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/kafka/KafkaIntegrationTest.java
+++ b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/kafka/KafkaIntegrationTest.java
@@ -39,7 +39,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.factory.ApplicationBuilder;
 import org.apache.brooklyn.entity.messaging.activemq.ActiveMQBroker;
 import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitIntegrationTest.java b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitIntegrationTest.java
index ce4228c..6c965c9 100644
--- a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitIntegrationTest.java
+++ b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitIntegrationTest.java
@@ -37,7 +37,7 @@ import org.apache.brooklyn.entity.factory.ApplicationBuilder;
 import org.apache.brooklyn.entity.messaging.MessageBroker;
 import org.apache.brooklyn.entity.messaging.amqp.AmqpExchange;
 import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Charsets;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitNodeImpl.java b/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitNodeImpl.java
index e23981f..8b5914c 100644
--- a/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitNodeImpl.java
+++ b/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitNodeImpl.java
@@ -23,7 +23,7 @@ import java.util.Map;
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.ssh.SshFeed;
 import org.apache.brooklyn.sensor.feed.ssh.SshPollConfig;
 import org.apache.brooklyn.sensor.feed.ssh.SshPollValue;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitSshDriver.java
----------------------------------------------------------------------
diff --git a/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitSshDriver.java b/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitSshDriver.java
index 511b3b0..c2c5c7a 100644
--- a/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitSshDriver.java
+++ b/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitSshDriver.java
@@ -27,7 +27,7 @@ import org.apache.brooklyn.api.location.OsDetails;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelper;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.os.Os;
 import org.apache.brooklyn.util.ssh.BashCommands;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/monitoring/src/test/java/org/apache/brooklyn/entity/monitoring/monit/MonitIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/monitoring/src/test/java/org/apache/brooklyn/entity/monitoring/monit/MonitIntegrationTest.java b/software/monitoring/src/test/java/org/apache/brooklyn/entity/monitoring/monit/MonitIntegrationTest.java
index 41eb9d2..418157d 100644
--- a/software/monitoring/src/test/java/org/apache/brooklyn/entity/monitoring/monit/MonitIntegrationTest.java
+++ b/software/monitoring/src/test/java/org/apache/brooklyn/entity/monitoring/monit/MonitIntegrationTest.java
@@ -34,7 +34,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.database.mysql.MySqlNode;
 import org.apache.brooklyn.entity.software.base.SameServerEntity;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.EntityTestUtils;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServer.java
----------------------------------------------------------------------
diff --git a/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServer.java b/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServer.java
index b848555..a9eada4 100644
--- a/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServer.java
+++ b/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServer.java
@@ -34,7 +34,7 @@ import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.entity.annotation.Effector;
 import org.apache.brooklyn.entity.group.DynamicGroup;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.Sensors;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerImpl.java
----------------------------------------------------------------------
diff --git a/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerImpl.java b/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerImpl.java
index 6d263b3..28a4e85 100644
--- a/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerImpl.java
+++ b/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerImpl.java
@@ -57,8 +57,8 @@ import com.google.common.collect.Multimap;
 import com.google.common.collect.MultimapBuilder;
 import com.google.common.collect.Multimaps;
 
-import org.apache.brooklyn.location.basic.Machines;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.Machines;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.guava.Maybe;
 import org.apache.brooklyn.util.net.Cidr;
 import org.apache.brooklyn.util.ssh.BashCommands;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerSshDriver.java
----------------------------------------------------------------------
diff --git a/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerSshDriver.java b/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerSshDriver.java
index e60955d..b9991c8 100644
--- a/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerSshDriver.java
+++ b/software/network/src/main/java/org/apache/brooklyn/entity/network/bind/BindDnsServerSshDriver.java
@@ -29,7 +29,7 @@ import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
 
 import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;
 import org.apache.brooklyn.util.net.Protocol;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/DoNothingSoftwareProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/DoNothingSoftwareProcessDriver.java b/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/DoNothingSoftwareProcessDriver.java
index d12269f..c78a6ca 100644
--- a/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/DoNothingSoftwareProcessDriver.java
+++ b/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/DoNothingSoftwareProcessDriver.java
@@ -20,7 +20,7 @@ package org.apache.brooklyn.entity.network.bind;
 
 import org.apache.brooklyn.api.internal.EntityLocal;
 import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 /**
  * Implements methods in {@link org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver}.

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/TestBindDnsServerImpl.java
----------------------------------------------------------------------
diff --git a/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/TestBindDnsServerImpl.java b/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/TestBindDnsServerImpl.java
index 988d92b..c103fe4 100644
--- a/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/TestBindDnsServerImpl.java
+++ b/software/network/src/test/java/org/apache/brooklyn/entity/network/bind/TestBindDnsServerImpl.java
@@ -22,7 +22,7 @@ import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.internal.EntityLocal;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 public class TestBindDnsServerImpl extends BindDnsServerImpl {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterImpl.java
index 136d9a2..d50e197 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterImpl.java
@@ -46,7 +46,7 @@ import org.apache.brooklyn.entity.lifecycle.Lifecycle;
 import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic.ServiceNotUpLogic;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.Machines;
+import org.apache.brooklyn.location.core.Machines;
 import org.apache.brooklyn.sensor.enricher.Enrichers;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNode.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNode.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNode.java
index 0919476..699ca57 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNode.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNode.java
@@ -34,7 +34,7 @@ import org.apache.brooklyn.entity.database.DatastoreMixins;
 import org.apache.brooklyn.entity.java.UsesJavaMXBeans;
 import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.Sensors;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeImpl.java
index fd24985..df501dd 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeImpl.java
@@ -43,8 +43,8 @@ import org.apache.brooklyn.entity.java.JavaAppUtils;
 import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.Machines;
 import org.apache.brooklyn.location.cloud.CloudLocationConfig;
+import org.apache.brooklyn.location.core.Machines;
 import org.apache.brooklyn.policy.enricher.RollingTimeWindowMeanEnricher;
 import org.apache.brooklyn.policy.enricher.TimeWeightedDeltaEnricher;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeSshDriver.java
index 7ee2b95..67a44f1 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraNodeSshDriver.java
@@ -44,8 +44,8 @@ import org.apache.brooklyn.entity.database.DatastoreMixins;
 import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
 import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
-import org.apache.brooklyn.location.basic.Machines;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.Machines;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
 import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.MutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeSshDriver.java
index b637210..dc5b02b 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseNodeSshDriver.java
@@ -41,7 +41,7 @@ import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
 import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.apache.http.auth.UsernamePasswordCredentials;
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
 import org.apache.brooklyn.sensor.feed.http.HttpValueFunctions;
 import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewaySshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewaySshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewaySshDriver.java
index 7f15f35..5e8257b 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewaySshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseSyncGatewaySshDriver.java
@@ -33,7 +33,7 @@ import org.apache.brooklyn.api.location.OsDetails;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.core.EntityPredicates;
 import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.ssh.BashCommands;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeSshDriver.java
index 3ef5c16..359254f 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/couchdb/CouchDBNodeSshDriver.java
@@ -29,7 +29,7 @@ import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;
 import org.apache.brooklyn.util.os.Os;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNode.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNode.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNode.java
index 8bc238a..5f230b0 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNode.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNode.java
@@ -26,7 +26,7 @@ import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.WebAppServiceConstants;
 import org.apache.brooklyn.entity.database.DatastoreMixins;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.Sensors;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeSshDriver.java
index 61f9e01..e989756 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeSshDriver.java
@@ -28,7 +28,7 @@ import org.apache.brooklyn.api.internal.EntityLocal;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Urls;
 import org.apache.brooklyn.util.os.Os;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/AbstractMongoDBSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/AbstractMongoDBSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/AbstractMongoDBSshDriver.java
index 3b5ddc6..ee390cb 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/AbstractMongoDBSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/AbstractMongoDBSshDriver.java
@@ -29,7 +29,7 @@ import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver
 import org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.apache.brooklyn.util.net.Networking;
 import org.apache.brooklyn.util.os.Os;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBClientSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBClientSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBClientSshDriver.java
index 0a938e0..53ecfa7 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBClientSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBClientSshDriver.java
@@ -28,7 +28,7 @@ import org.apache.brooklyn.entity.nosql.mongodb.sharding.MongoDBRouter;
 import org.apache.brooklyn.entity.nosql.mongodb.sharding.MongoDBRouterCluster;
 import org.apache.brooklyn.entity.nosql.mongodb.sharding.MongoDBShardedDeployment;
 import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.apache.brooklyn.util.math.MathPredicates;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBSshDriver.java
index fb10378..89f8112 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBSshDriver.java
@@ -19,7 +19,8 @@
 package org.apache.brooklyn.entity.nosql.mongodb;
 
 import static com.google.common.base.Preconditions.checkState;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Strings;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerSshDriver.java
index d5d5127..3eada3b 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerSshDriver.java
@@ -20,8 +20,7 @@ package org.apache.brooklyn.entity.nosql.mongodb.sharding;
 
 import org.apache.brooklyn.entity.nosql.mongodb.AbstractMongoDBSshDriver;
 import org.apache.brooklyn.entity.nosql.mongodb.MongoDBDriver;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 public class MongoDBConfigServerSshDriver extends AbstractMongoDBSshDriver implements MongoDBDriver {
     

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBRouterSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBRouterSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBRouterSshDriver.java
index 2d2a352..816906d 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBRouterSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBRouterSshDriver.java
@@ -21,8 +21,7 @@ package org.apache.brooklyn.entity.nosql.mongodb.sharding;
 import org.apache.brooklyn.entity.nosql.mongodb.AbstractMongoDBSshDriver;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Joiner;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreImpl.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreImpl.java
index c92f678..857c048 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreImpl.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreImpl.java
@@ -27,7 +27,7 @@ import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.api.location.MachineLocation;
 import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.ssh.SshFeed;
 import org.apache.brooklyn.sensor.feed.ssh.SshPollConfig;
 import org.apache.brooklyn.sensor.feed.ssh.SshPollValue;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreSshDriver.java
index 4c10689..5424130 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/redis/RedisStoreSshDriver.java
@@ -27,7 +27,7 @@ import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.os.Os;
 import org.apache.brooklyn.util.ssh.BashCommands;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeSshDriver.java
index d3953dc..cc85a14 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeSshDriver.java
@@ -43,7 +43,7 @@ import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
 import org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelper;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.task.DynamicTasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServer.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServer.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServer.java
index 1b89e07..daed1c5 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServer.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServer.java
@@ -29,7 +29,7 @@ import org.apache.brooklyn.entity.java.UsesJava;
 import org.apache.brooklyn.entity.java.UsesJavaMXBeans;
 import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerSshDriver.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerSshDriver.java b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerSshDriver.java
index 3c41f95..698cf48 100644
--- a/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerSshDriver.java
+++ b/software/nosql/src/main/java/org/apache/brooklyn/entity/nosql/solr/SolrServerSshDriver.java
@@ -30,7 +30,7 @@ import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
 import org.apache.brooklyn.entity.java.UsesJmx;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.file.ArchiveUtils;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterRebindIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterRebindIntegrationTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterRebindIntegrationTest.java
index d7a8e60..8f63050 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterRebindIntegrationTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterRebindIntegrationTest.java
@@ -34,7 +34,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterTest.java
index 4a3676d..83f2c1f 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraDatacenterTest.java
@@ -42,7 +42,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraFabricTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraFabricTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraFabricTest.java
index 24ff8ba..89128da 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraFabricTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/cassandra/CassandraFabricTest.java
@@ -43,7 +43,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseOfflineTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseOfflineTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseOfflineTest.java
index 2949411..6abe32f 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseOfflineTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchbase/CouchbaseOfflineTest.java
@@ -25,8 +25,8 @@ import org.testng.annotations.Test;
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
 import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.location.basic.BasicOsDetails;
-import org.apache.brooklyn.location.basic.BasicOsDetails.OsArchs;
+import org.apache.brooklyn.location.core.BasicOsDetails;
+import org.apache.brooklyn.location.core.BasicOsDetails.OsArchs;
 
 public class CouchbaseOfflineTest {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchdb/AbstractCouchDBNodeTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchdb/AbstractCouchDBNodeTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchdb/AbstractCouchDBNodeTest.java
index 7132cf0..f74dd95 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchdb/AbstractCouchDBNodeTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/couchdb/AbstractCouchDBNodeTest.java
@@ -27,7 +27,7 @@ import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 /**
  * CouchDB test framework for integration and live tests.

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeIntegrationTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeIntegrationTest.java
index 070ff6e..42c955d 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeIntegrationTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/elasticsearch/ElasticSearchNodeIntegrationTest.java
@@ -39,7 +39,7 @@ import org.bouncycastle.util.Strings;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBIntegrationTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBIntegrationTest.java
index 4a58f4c..65e7f69 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBIntegrationTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBIntegrationTest.java
@@ -30,7 +30,7 @@ import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.mongodb.DBObject;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBRebindIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBRebindIntegrationTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBRebindIntegrationTest.java
index 65ed25e..6fc2013 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBRebindIntegrationTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBRebindIntegrationTest.java
@@ -23,7 +23,7 @@ import org.apache.brooklyn.core.mgmt.rebind.RebindTestFixtureWithApp;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBReplicaSetIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBReplicaSetIntegrationTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBReplicaSetIntegrationTest.java
index 3c84d9c..df649f3 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBReplicaSetIntegrationTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/MongoDBReplicaSetIntegrationTest.java
@@ -35,7 +35,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.util.time.Duration;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerIntegrationTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerIntegrationTest.java
index 3d87857..c833fa5 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerIntegrationTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBConfigServerIntegrationTest.java
@@ -32,7 +32,7 @@ import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBShardedDeploymentIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBShardedDeploymentIntegrationTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBShardedDeploymentIntegrationTest.java
index 2ccb2eb..e1ad5fb 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBShardedDeploymentIntegrationTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/mongodb/sharding/MongoDBShardedDeploymentIntegrationTest.java
@@ -30,7 +30,7 @@ import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.Assert;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/redis/RedisClusterIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/redis/RedisClusterIntegrationTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/redis/RedisClusterIntegrationTest.java
index 0fef850..801871e 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/redis/RedisClusterIntegrationTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/redis/RedisClusterIntegrationTest.java
@@ -36,7 +36,7 @@ import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/redis/RedisIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/redis/RedisIntegrationTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/redis/RedisIntegrationTest.java
index 4cf387e..095307a 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/redis/RedisIntegrationTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/redis/RedisIntegrationTest.java
@@ -30,7 +30,7 @@ import org.apache.brooklyn.util.time.Duration;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 
 import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeIntegrationTest.java b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeIntegrationTest.java
index be871ac..b50ab1c 100644
--- a/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeIntegrationTest.java
+++ b/software/nosql/src/test/java/org/apache/brooklyn/entity/nosql/riak/RiakNodeIntegrationTest.java
@@ -31,7 +31,7 @@ import org.testng.annotations.Test;
 
 import com.google.common.collect.ImmutableList;
 
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 public class RiakNodeIntegrationTest {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafSshDriver.java
----------------------------------------------------------------------
diff --git a/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafSshDriver.java b/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafSshDriver.java
index bb60895..ee5176e 100644
--- a/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafSshDriver.java
+++ b/software/osgi/src/main/java/org/apache/brooklyn/entity/osgi/karaf/KarafSshDriver.java
@@ -26,7 +26,7 @@ import java.util.Map;
 
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/osgi/src/test/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerTest.java
----------------------------------------------------------------------
diff --git a/software/osgi/src/test/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerTest.java b/software/osgi/src/test/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerTest.java
index b3188eb..6a984c5 100644
--- a/software/osgi/src/test/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerTest.java
+++ b/software/osgi/src/test/java/org/apache/brooklyn/entity/osgi/karaf/KarafContainerTest.java
@@ -38,7 +38,7 @@ import org.apache.brooklyn.util.text.Identifiers;
 import org.testng.Assert;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/AbstractControllerImpl.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/AbstractControllerImpl.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/AbstractControllerImpl.java
index 2449184..9739744 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/AbstractControllerImpl.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/AbstractControllerImpl.java
@@ -44,7 +44,7 @@ import org.apache.brooklyn.entity.trait.Startable;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.location.access.BrooklynAccessUtils;
-import org.apache.brooklyn.location.basic.Machines;
+import org.apache.brooklyn.location.core.Machines;
 import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.task.Tasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxSshDriver.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxSshDriver.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxSshDriver.java
index 685c593..77c1eaf 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxSshDriver.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/proxy/nginx/NginxSshDriver.java
@@ -36,7 +36,7 @@ import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver
 import org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.task.DynamicTasks;
 import org.apache.brooklyn.util.core.task.Tasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSshDriver.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSshDriver.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSshDriver.java
index d045305..075bfee 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSshDriver.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/JavaWebAppSshDriver.java
@@ -26,7 +26,7 @@ import java.util.Set;
 
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.task.DynamicTasks;
 import org.apache.brooklyn.util.core.task.Tasks;
 import org.apache.brooklyn.util.core.task.ssh.SshTasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6SshDriver.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6SshDriver.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6SshDriver.java
index 35bc26b..09fdf27 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6SshDriver.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss6SshDriver.java
@@ -32,7 +32,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.entity.java.UsesJmx.JmxAgentModes;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7SshDriver.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7SshDriver.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7SshDriver.java
index 0acaa95..81fc449 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7SshDriver.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jboss/JBoss7SshDriver.java
@@ -30,7 +30,7 @@ import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSshDriver;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jetty/Jetty6SshDriver.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jetty/Jetty6SshDriver.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jetty/Jetty6SshDriver.java
index 939a7d9..29fe084 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jetty/Jetty6SshDriver.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/jetty/Jetty6SshDriver.java
@@ -26,7 +26,7 @@ import java.util.Map;
 
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppService.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppService.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppService.java
index 25ae613..2a96f34 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppService.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppService.java
@@ -28,7 +28,7 @@ import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.WebAppService;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSshDriver.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSshDriver.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSshDriver.java
index db3233f..3e31a90 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSshDriver.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/nodejs/NodeJsWebAppSshDriver.java
@@ -29,7 +29,7 @@ import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.WebAppService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.file.ArchiveUtils;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat7SshDriver.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat7SshDriver.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat7SshDriver.java
index 203096f..f4ea225 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat7SshDriver.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/Tomcat7SshDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.webapp.tomcat;
 
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 @Deprecated
 public class Tomcat7SshDriver extends TomcatSshDriver implements Tomcat7Driver {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServer.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServer.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServer.java
index 2f0ee58..2837432 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServer.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatServer.java
@@ -27,7 +27,7 @@ import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcess;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatSshDriver.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatSshDriver.java b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatSshDriver.java
index 49bae86..02dad68 100644
--- a/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatSshDriver.java
+++ b/software/webapp/src/main/java/org/apache/brooklyn/entity/webapp/tomcat/TomcatSshDriver.java
@@ -27,7 +27,7 @@ import java.util.Map;
 
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.webapp.JavaWebAppSshDriver;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/dns/AbstractGeoDnsServiceTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/dns/AbstractGeoDnsServiceTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/dns/AbstractGeoDnsServiceTest.java
index 7db193c..549bda1 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/dns/AbstractGeoDnsServiceTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/dns/AbstractGeoDnsServiceTest.java
@@ -56,13 +56,13 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.BasicLocationRegistry;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.location.basic.Machines;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.BasicLocationRegistry;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.apache.brooklyn.location.core.Locations;
+import org.apache.brooklyn.location.core.Machines;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 import org.apache.brooklyn.location.geo.HostGeoInfo;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/dns/geoscaling/GeoscalingIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/dns/geoscaling/GeoscalingIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/dns/geoscaling/GeoscalingIntegrationTest.java
index cfc76a0..cb963ec 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/dns/geoscaling/GeoscalingIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/dns/geoscaling/GeoscalingIntegrationTest.java
@@ -43,11 +43,11 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.location.geo.HostGeoInfo;
 import org.apache.brooklyn.location.geo.HostGeoLookup;
 import org.apache.brooklyn.location.geo.MaxMind2HostGeoLookup;
 import org.apache.brooklyn.location.geo.UtraceHostGeoLookup;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/AbstractControllerTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/AbstractControllerTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/AbstractControllerTest.java
index 9d4913e..4114749 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/AbstractControllerTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/AbstractControllerTest.java
@@ -56,8 +56,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/UrlMappingTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/UrlMappingTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/UrlMappingTest.java
index bc2d995..b8cadb2 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/UrlMappingTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/UrlMappingTest.java
@@ -48,7 +48,7 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Function;
 import com.google.common.base.Predicates;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxClusterIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxClusterIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxClusterIntegrationTest.java
index 1bd60e0..590faf6 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxClusterIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxClusterIntegrationTest.java
@@ -45,7 +45,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxHttpsSslIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxHttpsSslIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxHttpsSslIntegrationTest.java
index 1b5826f..08bc17b 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxHttpsSslIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxHttpsSslIntegrationTest.java
@@ -45,7 +45,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxLightIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxLightIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxLightIntegrationTest.java
index 7dab483..d4f0e49 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxLightIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxLightIntegrationTest.java
@@ -31,7 +31,7 @@ import org.apache.brooklyn.entity.factory.EntityFactory;
 import org.apache.brooklyn.entity.group.DynamicCluster;
 import org.apache.brooklyn.entity.proxy.StubAppServer;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.test.Asserts;
 
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxRebindIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxRebindIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxRebindIntegrationTest.java
index 02fde07..5a75506 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxRebindIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxRebindIntegrationTest.java
@@ -54,7 +54,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxRebindWithHaIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxRebindWithHaIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxRebindWithHaIntegrationTest.java
index 92ebbae..f54e491 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxRebindWithHaIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxRebindWithHaIntegrationTest.java
@@ -56,8 +56,8 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocationReuseIntegrationTest.RecordingSshjTool;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocationReuseIntegrationTest.RecordingSshjTool;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxUrlMappingIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxUrlMappingIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxUrlMappingIntegrationTest.java
index 9da1e2d..3c8c48c 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxUrlMappingIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxUrlMappingIntegrationTest.java
@@ -53,7 +53,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxWebClusterEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxWebClusterEc2LiveTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxWebClusterEc2LiveTest.java
index 5bca559..93a6faf 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxWebClusterEc2LiveTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/proxy/nginx/NginxWebClusterEc2LiveTest.java
@@ -43,7 +43,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.Machines;
+import org.apache.brooklyn.location.core.Machines;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/AbstractWebAppFixtureIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/AbstractWebAppFixtureIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/AbstractWebAppFixtureIntegrationTest.java
index c00b514..169a532 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/AbstractWebAppFixtureIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/AbstractWebAppFixtureIntegrationTest.java
@@ -44,7 +44,7 @@ import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.api.entity.Application;
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.entity.drivers.DriverDependentEntity;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ControlledDynamicWebAppClusterIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ControlledDynamicWebAppClusterIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ControlledDynamicWebAppClusterIntegrationTest.java
index 3a50f6c..e6aefec 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ControlledDynamicWebAppClusterIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ControlledDynamicWebAppClusterIntegrationTest.java
@@ -45,7 +45,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Suppliers;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ControlledDynamicWebAppClusterTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ControlledDynamicWebAppClusterTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ControlledDynamicWebAppClusterTest.java
index 261b0fd..b4715dd 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ControlledDynamicWebAppClusterTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ControlledDynamicWebAppClusterTest.java
@@ -42,7 +42,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/DynamicWebAppClusterTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/DynamicWebAppClusterTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/DynamicWebAppClusterTest.java
index 9956875..39cf94f 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/DynamicWebAppClusterTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/DynamicWebAppClusterTest.java
@@ -33,7 +33,7 @@ import org.apache.brooklyn.util.collections.MutableMap;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/DynamicWebAppFabricTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/DynamicWebAppFabricTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/DynamicWebAppFabricTest.java
index b8fff86..8d36ecb 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/DynamicWebAppFabricTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/DynamicWebAppFabricTest.java
@@ -36,7 +36,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ElasticCustomLocationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ElasticCustomLocationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ElasticCustomLocationTest.java
index 20d5f0d..0cfd963 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ElasticCustomLocationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ElasticCustomLocationTest.java
@@ -33,7 +33,7 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ElasticJavaWebAppServiceIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ElasticJavaWebAppServiceIntegrationTest.java b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ElasticJavaWebAppServiceIntegrationTest.java
index 2013a0d..5d177dc 100644
--- a/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ElasticJavaWebAppServiceIntegrationTest.java
+++ b/software/webapp/src/test/java/org/apache/brooklyn/entity/webapp/ElasticJavaWebAppServiceIntegrationTest.java
@@ -27,7 +27,7 @@ import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.collect.ImmutableList;
 



[53/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/InMemoryObjectStore.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/InMemoryObjectStore.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/InMemoryObjectStore.java
new file mode 100644
index 0000000..c842fd1
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/InMemoryObjectStore.java
@@ -0,0 +1,170 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.StoreObjectAccessorLocking;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Objects;
+
+public class InMemoryObjectStore implements PersistenceObjectStore {
+
+    private static final Logger log = LoggerFactory.getLogger(InMemoryObjectStore.class);
+
+    final Map<String,String> filesByName;
+    final Map<String, Date> fileModTimesByName;
+    boolean prepared = false;
+    
+    public InMemoryObjectStore() {
+        this(MutableMap.<String,String>of(), MutableMap.<String,Date>of());
+    }
+    
+    public InMemoryObjectStore(Map<String,String> map, Map<String, Date> fileModTimesByName) {
+        filesByName = map;
+        this.fileModTimesByName = fileModTimesByName;
+        log.debug("Using memory-based objectStore");
+    }
+    
+    @Override
+    public String getSummaryName() {
+        return "in-memory (test) persistence store";
+    }
+    
+    @Override
+    public void prepareForMasterUse() {
+    }
+
+    @Override
+    public void createSubPath(String subPath) {
+    }
+
+    @Override
+    public StoreObjectAccessor newAccessor(final String path) {
+        if (!prepared) throw new IllegalStateException("prepare method not yet invoked: "+this);
+        return new StoreObjectAccessorLocking(new SingleThreadedInMemoryStoreObjectAccessor(filesByName, fileModTimesByName, path));
+    }
+    
+    public static class SingleThreadedInMemoryStoreObjectAccessor implements StoreObjectAccessor {
+        private final Map<String, String> map;
+        private final Map<String, Date> mapModTime;
+        private final String key;
+
+        public SingleThreadedInMemoryStoreObjectAccessor(Map<String,String> map, Map<String, Date> mapModTime, String key) {
+            this.map = map;
+            this.mapModTime = mapModTime;
+            this.key = key;
+        }
+        @Override
+        public String get() {
+            synchronized (map) {
+                return map.get(key);
+            }
+        }
+        @Override
+        public byte[] getBytes() {
+            return get().getBytes();
+        }
+        @Override
+        public boolean exists() {
+            synchronized (map) {
+                return map.containsKey(key);
+            }
+        }
+        @Override
+        public void put(String val) {
+            synchronized (map) {
+                map.put(key, val);
+                mapModTime.put(key, new Date());
+            }
+        }
+        @Override
+        public void append(String val) {
+            synchronized (map) {
+                String val2 = get();
+                if (val2==null) val2 = val;
+                else val2 = val2 + val;
+
+                map.put(key, val2);
+                mapModTime.put(key, new Date());
+            }
+        }
+        @Override
+        public void delete() {
+            synchronized (map) {
+                map.remove(key);
+                mapModTime.remove(key);
+            }
+        }
+        @Override
+        public Date getLastModifiedDate() {
+            synchronized (map) {
+                return mapModTime.get(key);
+            }
+        }
+    }
+
+    @Override
+    public List<String> listContentsWithSubPath(final String parentSubPath) {
+        if (!prepared) throw new IllegalStateException("prepare method not yet invoked: "+this);
+        synchronized (filesByName) {
+            List<String> result = MutableList.of();
+            for (String file: filesByName.keySet())
+                if (file.startsWith(parentSubPath))
+                    result.add(file);
+            return result;
+        }
+    }
+
+    @Override
+    public void close() {
+    }
+
+    @Override
+    public String toString() {
+        return Objects.toStringHelper(this).add("size", filesByName.size()).toString();
+    }
+
+    @Override
+    public void injectManagementContext(ManagementContext mgmt) {
+    }
+    
+    @Override
+    public void prepareForSharedUse(PersistMode persistMode, HighAvailabilityMode haMode) {
+        prepared = true;
+    }
+
+    @Override
+    public void deleteCompletely() {
+        synchronized (filesByName) {
+            filesByName.clear();
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/InMemoryStoreObjectAccessorWriterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/InMemoryStoreObjectAccessorWriterTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/InMemoryStoreObjectAccessorWriterTest.java
new file mode 100644
index 0000000..47d401d
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/InMemoryStoreObjectAccessorWriterTest.java
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import java.io.IOException;
+
+import org.apache.brooklyn.core.mgmt.persist.StoreObjectAccessorLocking;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore.StoreObjectAccessorWithLock;
+import org.testng.annotations.Test;
+
+@Test
+public class InMemoryStoreObjectAccessorWriterTest extends PersistenceStoreObjectAccessorWriterTestFixture {
+
+    protected StoreObjectAccessorWithLock newPersistenceStoreObjectAccessor() throws IOException {
+        InMemoryObjectStore store = new InMemoryObjectStore();
+        store.prepareForSharedUse(null, null);
+        return new StoreObjectAccessorLocking(store.newAccessor("foo"));
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/ListeningObjectStore.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/ListeningObjectStore.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/ListeningObjectStore.java
new file mode 100644
index 0000000..c27011e
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/ListeningObjectStore.java
@@ -0,0 +1,254 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import java.util.Date;
+import java.util.List;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.time.CountdownTimer;
+import org.apache.brooklyn.util.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+
+public class ListeningObjectStore implements PersistenceObjectStore {
+
+    protected final PersistenceObjectStore delegate;
+    protected final List<ObjectStoreTransactionListener> listeners = MutableList.of();
+    private boolean writesFailSilently = false;
+
+    public static interface ObjectStoreTransactionListener {
+        public void recordQueryOut(String summary, int size);
+        public void recordDataOut(String summary, int size);
+        public void recordDataIn(String summary, int size);
+    }
+    
+    public static class RecordingTransactionListener implements ObjectStoreTransactionListener {
+        private static final Logger log = LoggerFactory.getLogger(ListeningObjectStore.RecordingTransactionListener.class);
+        
+        protected final String prefix;
+        protected final AtomicLong bytesIn = new AtomicLong();
+        protected final AtomicLong bytesOut = new AtomicLong();
+        protected final AtomicInteger countQueriesOut = new AtomicInteger();
+        protected final AtomicInteger countDataOut = new AtomicInteger();
+        protected final AtomicInteger countDataIn = new AtomicInteger();
+        
+        public RecordingTransactionListener(String prefix) {
+            this.prefix = prefix;
+        }
+        
+        public long getBytesIn() {
+            return bytesIn.get();
+        }
+        
+        public long getBytesOut() {
+            return bytesOut.get();
+        }
+        
+        public int getCountQueriesOut() {
+            return countQueriesOut.get();
+        }
+        
+        public int getCountDataOut() {
+            return countDataOut.get();
+        }
+        
+        public int getCountDataIn() {
+            return countDataIn.get();
+        }
+        
+        public String getTotalString() {
+            return "totals: out="+Strings.makeSizeString(bytesOut.get())+" in="+Strings.makeSizeString(bytesIn.get());
+        }
+        
+        @Override
+        public void recordQueryOut(String summary, int size) {
+            synchronized (this) { this.notifyAll(); }
+            bytesOut.addAndGet(size);
+            countQueriesOut.incrementAndGet();
+            log.info(prefix+" "+summary+" -->"+size+"; "+getTotalString());
+        }
+        
+        @Override
+        public void recordDataOut(String summary, int size) {
+            synchronized (this) { this.notifyAll(); }
+            bytesOut.addAndGet(size);
+            countDataOut.incrementAndGet();
+            log.info(prefix+" "+summary+" -->"+size+"; "+getTotalString());
+        }
+        
+        @Override
+        public void recordDataIn(String summary, int size) {
+            synchronized (this) { this.notifyAll(); }
+            bytesIn.addAndGet(size);
+            countDataIn.incrementAndGet();
+            log.info(prefix+" "+summary+" <--"+size+"; "+getTotalString());
+        }
+
+        public void blockUntilDataWrittenExceeds(long count, Duration timeout) throws InterruptedException, TimeoutException {
+            CountdownTimer timer = CountdownTimer.newInstanceStarted(timeout);
+            synchronized (this) {
+                while (bytesOut.get()<count) {
+                    if (timer.isExpired())
+                        throw new TimeoutException();
+                    timer.waitOnForExpiry(this);
+                }
+            }
+        }
+    }
+
+    public ListeningObjectStore(PersistenceObjectStore delegate, ObjectStoreTransactionListener ...listeners) {
+        this.delegate = Preconditions.checkNotNull(delegate);
+        for (ObjectStoreTransactionListener listener: listeners)
+            this.listeners.add(listener);
+    }
+
+    @Override
+    public String getSummaryName() {
+        return delegate.getSummaryName();
+    }
+
+    @Override
+    public void prepareForMasterUse() {
+        delegate.prepareForMasterUse();
+    }
+
+    @Override
+    public StoreObjectAccessor newAccessor(String path) {
+        return new ListeningAccessor(path, delegate.newAccessor(path));
+    }
+
+    @Override
+    public void createSubPath(String subPath) {
+        if (writesFailSilently)
+            return;
+        
+        for (ObjectStoreTransactionListener listener: listeners)
+            listener.recordQueryOut("creating path "+subPath, 1+subPath.length());
+        delegate.createSubPath(subPath);
+    }
+
+    @Override
+    public List<String> listContentsWithSubPath(String subPath) {
+        for (ObjectStoreTransactionListener listener: listeners)
+            listener.recordQueryOut("requesting list "+subPath, 1+subPath.length());
+        
+        List<String> result = delegate.listContentsWithSubPath(subPath);
+        
+        for (ObjectStoreTransactionListener listener: listeners)
+            listener.recordDataIn("receiving list "+subPath, result.toString().length());
+        return result;
+    }
+
+    @Override
+    public void close() {
+        delegate.close();
+    }
+
+    @Override
+    public void injectManagementContext(ManagementContext managementContext) {
+        delegate.injectManagementContext(managementContext);
+    }
+    
+    @Override
+    public void prepareForSharedUse(PersistMode persistMode, HighAvailabilityMode haMode) {
+        delegate.prepareForSharedUse(persistMode, haMode);
+    }
+
+    @Override
+    public void deleteCompletely() {
+        for (ObjectStoreTransactionListener listener: listeners)
+            listener.recordDataOut("deleting completely", 1);
+        delegate.deleteCompletely();
+    }
+
+    public class ListeningAccessor implements StoreObjectAccessor {
+
+        protected final String path;
+        protected final StoreObjectAccessor delegate;
+        
+        public ListeningAccessor(String path, StoreObjectAccessor delegate) {
+            this.path = path;
+            this.delegate = delegate;
+        }
+        @Override
+        public boolean exists() {
+            return delegate.exists();
+        }
+        @Override
+        public void put(String val) {
+            if (writesFailSilently)
+                return;
+
+            for (ObjectStoreTransactionListener listener: listeners)
+                listener.recordDataOut("writing "+path, val.length());
+            delegate.put(val);
+        }
+        @Override
+        public void append(String s) {
+            if (writesFailSilently)
+                return;
+
+            for (ObjectStoreTransactionListener listener: listeners)
+                listener.recordDataOut("appending "+path, s.length());
+            delegate.append(s);
+        }
+        @Override
+        public void delete() {
+            if (writesFailSilently)
+                return;
+
+            for (ObjectStoreTransactionListener listener: listeners)
+                listener.recordQueryOut("deleting "+path, path.length());
+            delegate.delete();
+        }
+        @Override
+        public String get() {
+            for (ObjectStoreTransactionListener listener: listeners)
+                listener.recordQueryOut("requesting "+path, path.length());
+            String result = delegate.get();
+            
+            for (ObjectStoreTransactionListener listener: listeners)
+                listener.recordDataIn("reading "+path, (result==null ? 0 : result.length()));
+            return result;
+        }
+        @Override
+        public byte[] getBytes() {
+            return get().getBytes();
+        }
+        @Override
+        public Date getLastModifiedDate() {
+            return delegate.getLastModifiedDate();
+        }
+    }
+
+    public void setWritesFailSilently(boolean writesFailSilently) {
+        this.writesFailSilently = writesFailSilently;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/PersistenceStoreObjectAccessorWriterTestFixture.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/PersistenceStoreObjectAccessorWriterTestFixture.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/PersistenceStoreObjectAccessorWriterTestFixture.java
new file mode 100644
index 0000000..b4ac83f
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/PersistenceStoreObjectAccessorWriterTestFixture.java
@@ -0,0 +1,136 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.Date;
+import java.util.concurrent.Executors;
+
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore.StoreObjectAccessorWithLock;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+
+public abstract class PersistenceStoreObjectAccessorWriterTestFixture {
+
+    private static final Duration TIMEOUT = Duration.TEN_SECONDS;
+    
+    protected ListeningExecutorService executor;
+    protected StoreObjectAccessorWithLock accessor;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
+        accessor = newPersistenceStoreObjectAccessor();
+    }
+
+    protected abstract StoreObjectAccessorWithLock newPersistenceStoreObjectAccessor() throws IOException;
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (accessor != null) {
+            accessor.delete();
+            accessor.waitForCurrentWrites(Duration.TEN_SECONDS);
+        }
+        if (executor != null) executor.shutdownNow();
+    }
+
+    @Test
+    public void testWritesFile() throws Exception {
+        accessor.put("abc");
+        accessor.waitForCurrentWrites(TIMEOUT);
+
+        assertEquals(accessor.get(), "abc");
+    }
+
+    @Test
+    public void testExists() throws Exception {
+        accessor.put("abc");
+        accessor.waitForCurrentWrites(TIMEOUT);
+        assertTrue(accessor.exists());
+        
+        accessor.delete();
+        accessor.waitForCurrentWrites(TIMEOUT);
+        assertFalse(accessor.exists());
+    }
+    
+    @Test
+    public void testAppendsFile() throws Exception {
+        accessor.put("abc\n");
+        accessor.append("def\n");
+        accessor.waitForCurrentWrites(TIMEOUT);
+
+        assertEquals(accessor.get(), "abc\ndef\n");
+    }
+
+    /** most storage systems support <= 1ms resolution; but some file systems -- esp FAT and OSX HFS+ are much much higher! */
+    protected Duration getLastModifiedResolution() {
+        return Duration.millis(1);
+    }
+    
+    @Test
+    public void testLastModifiedTime() throws Exception {
+        accessor.delete();
+        Assert.assertNull(accessor.getLastModifiedDate());
+        accessor.put("abc");
+        accessor.waitForCurrentWrites(TIMEOUT);
+        Date write1 = accessor.getLastModifiedDate();
+        Assert.assertNotNull(write1);
+        
+        Time.sleep(getLastModifiedResolution().times(2));
+        accessor.put("abc");
+        accessor.waitForCurrentWrites(TIMEOUT);
+        Date write2 = accessor.getLastModifiedDate();
+        Assert.assertNotNull(write2);
+        Assert.assertTrue(write2.after(write1), "dates are "+write1+" ("+write1.getTime()+") and "+write2+" ("+write2.getTime()+") ");
+    }
+    
+    @Test
+    public void testWriteBacklogThenDeleteWillLeaveFileDeleted() throws Exception {
+        String big = makeBigString(biggishSize());
+        
+        accessor.put(big);
+        accessor.put(big);
+        accessor.delete();
+        
+        accessor.waitForCurrentWrites(TIMEOUT);
+        assertFalse(accessor.exists());
+    }
+
+    protected int biggishSize() {
+        return 100000;
+    }
+    
+    protected String makeBigString(int size) {
+        // prefer non-random so can't be compressed
+        return Identifiers.makeRandomBase64Id(size);
+//        return com.google.common.base.Strings.repeat("x", size);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/XmlMementoSerializerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/XmlMementoSerializerTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/XmlMementoSerializerTest.java
new file mode 100644
index 0000000..d95cc0a
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/persist/XmlMementoSerializerTest.java
@@ -0,0 +1,455 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist;
+
+import static org.testng.Assert.assertEquals;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Set;
+
+import org.apache.brooklyn.location.core.SimulatedLocation;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.test.TestResourceUnavailableException;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.collections.MutableSet;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.api.catalog.CatalogItem;
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoPersister.LookupContext;
+import org.apache.brooklyn.api.objs.BrooklynObject;
+import org.apache.brooklyn.api.objs.BrooklynObjectType;
+import org.apache.brooklyn.api.policy.Policy;
+import org.apache.brooklyn.api.sensor.Enricher;
+import org.apache.brooklyn.api.sensor.Feed;
+import org.apache.brooklyn.core.catalog.internal.CatalogItemBuilder;
+import org.apache.brooklyn.core.catalog.internal.CatalogItemDtoAbstract;
+import org.apache.brooklyn.core.catalog.internal.CatalogTestUtils;
+import org.apache.brooklyn.core.mgmt.osgi.OsgiTestResources;
+import org.apache.brooklyn.core.mgmt.osgi.OsgiVersionMoreEntityTest;
+import org.apache.brooklyn.core.mgmt.persist.XmlMementoSerializer;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.group.DynamicCluster;
+
+import com.google.common.base.Objects;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Maps;
+
+public class XmlMementoSerializerTest {
+
+    private static final Logger LOG = LoggerFactory.getLogger(XmlMementoSerializerTest.class);
+
+    private XmlMementoSerializer<Object> serializer;
+
+    @BeforeMethod(alwaysRun=true)
+    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 testArraysAsList() throws Exception {
+        // For some reason Arrays.asList used in the catalog's libraries can't be deserialized correctly,
+        // but here works perfectly - the generated catalog xml contains
+        //    <libraries class="list">
+        //      <a ...>
+        //        <bundle....>
+        // which is deserialized as an ArrayList with a single member array of bundles.
+        // The cause is the class="list" type which should be java.util.Arrays$ArrayList instead.
+        Collection<String> obj = Arrays.asList("a", "b");
+        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 testClass() throws Exception {
+        Class<?> t = XmlMementoSerializer.class;
+        assertSerializeAndDeserialize(t);
+    }
+
+    @Test
+    public void testEntity() throws Exception {
+        final TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
+        ManagementContext managementContext = app.getManagementContext();
+        try {
+            serializer.setLookupContext(new LookupContextImpl(managementContext,
+                    ImmutableList.of(app), ImmutableList.<Location>of(), ImmutableList.<Policy>of(),
+                    ImmutableList.<Enricher>of(), ImmutableList.<Feed>of(), ImmutableList.<CatalogItem<?, ?>>of(), true));
+            assertSerializeAndDeserialize(app);
+        } finally {
+            Entities.destroyAll(managementContext);
+        }
+    }
+
+    @Test
+    public void testLocation() throws Exception {
+        final TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
+        ManagementContext managementContext = app.getManagementContext();
+        try {
+            @SuppressWarnings("deprecation")
+            final Location loc = managementContext.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class));
+            serializer.setLookupContext(new LookupContextImpl(managementContext,
+                    ImmutableList.<Entity>of(), ImmutableList.of(loc), ImmutableList.<Policy>of(),
+                    ImmutableList.<Enricher>of(), ImmutableList.<Feed>of(), ImmutableList.<CatalogItem<?, ?>>of(), true));
+            assertSerializeAndDeserialize(loc);
+        } finally {
+            Entities.destroyAll(managementContext);
+        }
+    }
+
+    @Test
+    public void testCatalogItem() throws Exception {
+        final TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
+        ManagementContext managementContext = app.getManagementContext();
+        try {
+            CatalogItem<?, ?> catalogItem = CatalogItemBuilder.newEntity("symbolicName", "0.0.1")
+                    .displayName("test catalog item")
+                    .description("description")
+                    .plan("yaml plan")
+                    .iconUrl("iconUrl")
+                    .libraries(CatalogItemDtoAbstract.parseLibraries(ImmutableList.of("library-url")))
+                    .build();
+            serializer.setLookupContext(new LookupContextImpl(managementContext,
+                    ImmutableList.<Entity>of(), ImmutableList.<Location>of(), ImmutableList.<Policy>of(),
+                    ImmutableList.<Enricher>of(), ImmutableList.<Feed>of(), ImmutableList.of(catalogItem), true));
+            assertSerializeAndDeserialize(catalogItem);
+        } finally {
+            Entities.destroyAll(managementContext);
+        }
+    }
+
+    @Test
+    public void testEntitySpec() throws Exception {
+        EntitySpec<?> obj = EntitySpec.create(TestEntity.class);
+        assertSerializeAndDeserialize(obj);
+    }
+    
+    @Test
+    public void testEntitySpecFromOsgi() throws Exception {
+        TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), OsgiTestResources.BROOKLYN_TEST_MORE_ENTITIES_V1_PATH);
+        ManagementContext mgmt = LocalManagementContextForTests.builder(true).disableOsgi(false).build();
+        try {
+            CatalogItem<?, ?> ci = OsgiVersionMoreEntityTest.addMoreEntityV1(mgmt, "1.0");
+            
+            EntitySpec<DynamicCluster> spec = EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.INITIAL_SIZE, 1)
+                .configure(DynamicCluster.MEMBER_SPEC, CatalogTestUtils.createEssentialEntitySpec(mgmt, ci));
+    
+            serializer.setLookupContext(new LookupContextImpl(mgmt,
+                ImmutableList.<Entity>of(), ImmutableList.<Location>of(), ImmutableList.<Policy>of(),
+                ImmutableList.<Enricher>of(), ImmutableList.<Feed>of(), ImmutableList.<CatalogItem<?,?>>of(), true));
+            assertSerializeAndDeserialize(spec);
+        } finally {
+            Entities.destroyAllCatching(mgmt);
+        }
+    }
+
+    @Test
+    public void testImmutableCollectionsWithDanglingEntityRef() throws Exception {
+        // If there's a dangling entity in an ImmutableList etc, then discard it entirely.
+        // If we try to insert null then it fails, breaking the deserialization of that entire file.
+        
+        final TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
+        final TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
+        ManagementContext managementContext = app.getManagementContext();
+        try {
+            serializer.setLookupContext(new LookupContextImpl(managementContext,
+                    ImmutableList.of(app), ImmutableList.<Location>of(), ImmutableList.<Policy>of(),
+                    ImmutableList.<Enricher>of(), ImmutableList.<Feed>of(), ImmutableList.<CatalogItem<?, ?>>of(), false));
+            
+            List<?> resultList = serializeAndDeserialize(ImmutableList.of(app, entity));
+            assertEquals(resultList, ImmutableList.of(app));
+            
+            Set<?> resultSet = serializeAndDeserialize(ImmutableSet.of(app, entity));
+            assertEquals(resultSet, ImmutableSet.of(app));
+            
+            Map<?, ?> resultMap = serializeAndDeserialize(ImmutableMap.of(app, "appval", "appkey", app, entity, "entityval", "entityKey", entity));
+            assertEquals(resultMap, ImmutableMap.of(app, "appval", "appkey", app));
+
+        } finally {
+            Entities.destroyAll(managementContext);
+        }
+    }
+
+    @Test
+    public void testFieldReffingEntity() throws Exception {
+        final TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
+        ReffingEntity reffer = new ReffingEntity(app);
+        ManagementContext managementContext = app.getManagementContext();
+        try {
+            serializer.setLookupContext(new LookupContextImpl(managementContext,
+                    ImmutableList.of(app), ImmutableList.<Location>of(), ImmutableList.<Policy>of(),
+                    ImmutableList.<Enricher>of(), ImmutableList.<Feed>of(), ImmutableList.<CatalogItem<?, ?>>of(), true));
+            ReffingEntity reffer2 = assertSerializeAndDeserialize(reffer);
+            assertEquals(reffer2.entity, app);
+        } finally {
+            Entities.destroyAll(managementContext);
+        }
+    }
+
+    @Test
+    public void testUntypedFieldReffingEntity() throws Exception {
+        final TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
+        ReffingEntity reffer = new ReffingEntity((Object)app);
+        ManagementContext managementContext = app.getManagementContext();
+        try {
+            serializer.setLookupContext(new LookupContextImpl(managementContext,
+                    ImmutableList.of(app), ImmutableList.<Location>of(), ImmutableList.<Policy>of(),
+                    ImmutableList.<Enricher>of(), ImmutableList.<Feed>of(), ImmutableList.<CatalogItem<?, ?>>of(), true));
+            ReffingEntity reffer2 = assertSerializeAndDeserialize(reffer);
+            assertEquals(reffer2.obj, app);
+        } finally {
+            Entities.destroyAll(managementContext);
+        }
+    }
+
+    public static class ReffingEntity {
+        public Entity entity;
+        public Object obj;
+        public ReffingEntity(Entity entity) {
+            this.entity = entity;
+        }
+        public ReffingEntity(Object obj) {
+            this.obj = obj;
+        }
+        @Override
+        public boolean equals(Object o) {
+            return (o instanceof ReffingEntity) && Objects.equal(entity, ((ReffingEntity)o).entity) && Objects.equal(obj, ((ReffingEntity)o).obj);
+        }
+        @Override
+        public int hashCode() {
+            return Objects.hashCode(entity, obj);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private <T> T assertSerializeAndDeserialize(T obj) throws Exception {
+        String serializedForm = serializer.toString(obj);
+        LOG.info("serializedForm=" + serializedForm);
+        Object deserialized = serializer.fromString(serializedForm);
+        assertEquals(deserialized, obj, "serializedForm="+serializedForm);
+        return (T) deserialized;
+    }
+
+    @SuppressWarnings("unchecked")
+    private <T> T serializeAndDeserialize(T obj) throws Exception {
+        String serializedForm = serializer.toString(obj);
+        LOG.info("serializedForm=" + serializedForm);
+        return (T) serializer.fromString(serializedForm);
+    }
+
+    static class LookupContextImpl implements LookupContext {
+        private final ManagementContext mgmt;
+        private final Map<String, Entity> entities;
+        private final Map<String, Location> locations;
+        private final Map<String, Policy> policies;
+        private final Map<String, Enricher> enrichers;
+        private final Map<String, Feed> feeds;
+        private final Map<String, CatalogItem<?, ?>> catalogItems;
+        private final boolean failOnDangling;
+
+        LookupContextImpl(ManagementContext mgmt, Iterable<? extends Entity> entities, Iterable<? extends Location> locations,
+                Iterable<? extends Policy> policies, Iterable<? extends Enricher> enrichers, Iterable<? extends Feed> feeds,
+                Iterable<? extends CatalogItem<?, ?>> catalogItems, boolean failOnDangling) {
+            this.mgmt = mgmt;
+            this.entities = Maps.newLinkedHashMap();
+            this.locations = Maps.newLinkedHashMap();
+            this.policies = Maps.newLinkedHashMap();
+            this.enrichers = Maps.newLinkedHashMap();
+            this.feeds = Maps.newLinkedHashMap();
+            this.catalogItems = Maps.newLinkedHashMap();
+            for (Entity entity : entities) this.entities.put(entity.getId(), entity);
+            for (Location location : locations) this.locations.put(location.getId(), location);
+            for (Policy policy : policies) this.policies.put(policy.getId(), policy);
+            for (Enricher enricher : enrichers) this.enrichers.put(enricher.getId(), enricher);
+            for (Feed feed : feeds) this.feeds.put(feed.getId(), feed);
+            for (CatalogItem<?, ?> catalogItem : catalogItems) this.catalogItems.put(catalogItem.getId(), catalogItem);
+            this.failOnDangling = failOnDangling;
+        }
+        LookupContextImpl(ManagementContext mgmt, Map<String,? extends Entity> entities, Map<String,? extends Location> locations,
+                Map<String,? extends Policy> policies, Map<String,? extends Enricher> enrichers, Map<String,? extends Feed> feeds,
+                Map<String, ? extends CatalogItem<?, ?>> catalogItems, boolean failOnDangling) {
+            this.mgmt = mgmt;
+            this.entities = ImmutableMap.copyOf(entities);
+            this.locations = ImmutableMap.copyOf(locations);
+            this.policies = ImmutableMap.copyOf(policies);
+            this.enrichers = ImmutableMap.copyOf(enrichers);
+            this.feeds = ImmutableMap.copyOf(feeds);
+            this.catalogItems = ImmutableMap.copyOf(catalogItems);
+            this.failOnDangling = failOnDangling;
+        }
+        @Override public ManagementContext lookupManagementContext() {
+            return mgmt;
+        }
+        @Override public Entity lookupEntity(String id) {
+            if (entities.containsKey(id)) {
+                return entities.get(id);
+            }
+            if (failOnDangling) {
+                throw new NoSuchElementException("no entity with id "+id+"; contenders are "+entities.keySet());
+            }
+            return null;
+        }
+        @Override public Location lookupLocation(String id) {
+            if (locations.containsKey(id)) {
+                return locations.get(id);
+            }
+            if (failOnDangling) {
+                throw new NoSuchElementException("no location with id "+id+"; contenders are "+locations.keySet());
+            }
+            return null;
+        }
+        @Override public Policy lookupPolicy(String id) {
+            if (policies.containsKey(id)) {
+                return policies.get(id);
+            }
+            if (failOnDangling) {
+                throw new NoSuchElementException("no policy with id "+id+"; contenders are "+policies.keySet());
+            }
+            return null;
+        }
+        @Override public Enricher lookupEnricher(String id) {
+            if (enrichers.containsKey(id)) {
+                return enrichers.get(id);
+            }
+            if (failOnDangling) {
+                throw new NoSuchElementException("no enricher with id "+id+"; contenders are "+enrichers.keySet());
+            }
+            return null;
+        }
+        @Override public Feed lookupFeed(String id) {
+            if (feeds.containsKey(id)) {
+                return feeds.get(id);
+            }
+            if (failOnDangling) {
+                throw new NoSuchElementException("no feed with id "+id+"; contenders are "+feeds.keySet());
+            }
+            return null;
+        }
+        @Override public CatalogItem<?, ?> lookupCatalogItem(String id) {
+            if (catalogItems.containsKey(id)) {
+                return catalogItems.get(id);
+            }
+            if (failOnDangling) {
+                throw new NoSuchElementException("no catalog item with id "+id+"; contenders are "+catalogItems.keySet());
+            }
+            return null;
+        }
+        
+        @Override
+        public BrooklynObject lookup(BrooklynObjectType type, String id) {
+            switch (type) {
+            case CATALOG_ITEM: return lookupCatalogItem(id);
+            case ENRICHER: return lookupEnricher(id);
+            case ENTITY: return lookupEntity(id);
+            case FEED: return lookupFeed(id);
+            case LOCATION: return lookupLocation(id);
+            case POLICY: return lookupPolicy(id);
+            case UNKNOWN: return null;
+            }
+            throw new IllegalStateException("Unexpected type "+type+" / id "+id);
+        }
+        @Override
+        public BrooklynObject peek(BrooklynObjectType type, String id) {
+            switch (type) {
+            case CATALOG_ITEM: return catalogItems.get(id);
+            case ENRICHER: return enrichers.get(id);
+            case ENTITY: return entities.get(id);
+            case FEED: return feeds.get(id);
+            case LOCATION: return locations.get(id);
+            case POLICY: return policies.get(id);
+            case UNKNOWN: return null;
+            }
+            throw new IllegalStateException("Unexpected type "+type+" / id "+id);
+        }
+    };
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindCatalogItemTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindCatalogItemTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindCatalogItemTest.java
index e4f6df9..37f569e 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindCatalogItemTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindCatalogItemTest.java
@@ -46,7 +46,7 @@ import org.apache.brooklyn.core.test.camp.brooklyn.lite.CampPlatformWithJustBroo
 import org.apache.brooklyn.core.test.camp.brooklyn.lite.TestAppAssemblyInstantiator;
 import org.apache.brooklyn.core.test.entity.TestEntity;
 import org.apache.brooklyn.policy.core.AbstractPolicy;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Joiner;
 import com.google.common.base.Throwables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindEnricherTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindEnricherTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindEnricherTest.java
index e499dd9..c44c9ca 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindEnricherTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindEnricherTest.java
@@ -54,7 +54,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindEntityTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindEntityTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindEntityTest.java
index 7571bea..3a3d5f2 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindEntityTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindEntityTest.java
@@ -78,7 +78,7 @@ import org.apache.brooklyn.util.exceptions.RuntimeInterruptedException;
 import org.apache.brooklyn.util.time.Durations;
 import org.testng.Assert;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocationConfigTest.MyLocation;
+import org.apache.brooklyn.location.core.LocationConfigTest.MyLocation;
 
 import com.google.common.base.Objects;
 import com.google.common.base.Predicates;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindFeedTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindFeedTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindFeedTest.java
index 3620070..f27bf65 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindFeedTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindFeedTest.java
@@ -58,8 +58,8 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Function;
 import com.google.common.base.Predicates;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindLocalhostLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindLocalhostLocationTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindLocalhostLocationTest.java
index 647d9f8..91b6064 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindLocalhostLocationTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindLocalhostLocationTest.java
@@ -30,8 +30,8 @@ import org.testng.annotations.Test;
 import org.apache.brooklyn.api.location.LocationSpec;
 import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoManifest;
 import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindLocationTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindLocationTest.java
index b5608dd..fe60599 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindLocationTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindLocationTest.java
@@ -44,7 +44,7 @@ import org.apache.brooklyn.util.core.flags.SetFromFlag;
 import org.testng.Assert;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.AbstractLocation;
+import org.apache.brooklyn.location.core.AbstractLocation;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindOptions.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindOptions.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindOptions.java
index 5cc5893..71ce08a 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindOptions.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindOptions.java
@@ -22,7 +22,7 @@ import java.io.File;
 
 import org.apache.brooklyn.api.mgmt.ManagementContext;
 import org.apache.brooklyn.api.mgmt.rebind.RebindExceptionHandler;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
 
 /**
  * See {@link RebindTestFixture#rebind(RebindOptions)} and {@link RebindTestUtils#rebind(RebindOptions)}.

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindPolicyTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindPolicyTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindPolicyTest.java
index 2ec19ef..44ab0eb 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindPolicyTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindPolicyTest.java
@@ -47,7 +47,7 @@ import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.collections.MutableSet;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.Locations;
+import org.apache.brooklyn.location.core.Locations;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableSet;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindSshMachineLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindSshMachineLocationTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindSshMachineLocationTest.java
index 21de755..92fdb55 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindSshMachineLocationTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindSshMachineLocationTest.java
@@ -28,8 +28,8 @@ import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 import org.apache.brooklyn.api.location.LocationSpec;
 import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindTestFixture.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindTestFixture.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindTestFixture.java
index 2d9e60e..d75e563 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindTestFixture.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindTestFixture.java
@@ -43,9 +43,9 @@ import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoManifest;
 import org.apache.brooklyn.core.catalog.internal.CatalogUtils;
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynMementoPersisterToObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.FileBasedObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.FileBasedObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.core.EntityFunctions;
 import org.apache.brooklyn.entity.core.StartableApplication;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindTestUtils.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindTestUtils.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindTestUtils.java
index 6d1ac24..e5696c2f 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindTestUtils.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindTestUtils.java
@@ -42,15 +42,15 @@ import org.apache.brooklyn.core.internal.BrooklynProperties;
 import org.apache.brooklyn.core.mgmt.ha.ManagementPlaneSyncRecordPersisterToObjectStore;
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.FileBasedObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
 import org.apache.brooklyn.core.mgmt.rebind.PersistenceExceptionHandlerImpl;
 import org.apache.brooklyn.core.mgmt.rebind.RebindExceptionHandlerImpl;
 import org.apache.brooklyn.core.mgmt.rebind.RebindManagerImpl;
 import org.apache.brooklyn.core.mgmt.rebind.Dumpers.Pointer;
 import org.apache.brooklyn.core.mgmt.rebind.dto.MementosGenerators;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynMementoPersisterToObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.FileBasedObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
 import org.apache.brooklyn.core.server.BrooklynServerConfig;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
 import org.apache.brooklyn.util.io.FileUtil;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterFileBasedTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterFileBasedTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterFileBasedTest.java
deleted file mode 100644
index 608d4aa..0000000
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterFileBasedTest.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import java.io.File;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
-import org.apache.brooklyn.core.mgmt.rebind.persister.FileBasedObjectStore;
-import org.apache.brooklyn.util.javalang.JavaClassNames;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.time.Duration;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.Test;
-
-/**
- * @author Andrea Turli
- */
-@Test
-public class BrooklynMementoPersisterFileBasedTest extends BrooklynMementoPersisterTestFixture {
-
-    protected File mementoDir;
-    
-    @Override
-    protected ManagementContext newPersistingManagementContext() {
-        mementoDir = Os.newTempDir(JavaClassNames.cleanSimpleClassName(this));
-        Os.deleteOnExitRecursively(mementoDir);
-        return RebindTestUtils.managementContextBuilder(classLoader, new FileBasedObjectStore(mementoDir))
-            .persistPeriod(Duration.millis(10)).buildStarted();
-    }
-
-    @Override
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        super.tearDown();
-        mementoDir = Os.deleteRecursively(mementoDir).asNullOrThrowing();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterInMemorySizeIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterInMemorySizeIntegrationTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterInMemorySizeIntegrationTest.java
deleted file mode 100644
index 3aa176d..0000000
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterInMemorySizeIntegrationTest.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import java.io.IOException;
-import java.util.concurrent.TimeoutException;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
-import org.apache.brooklyn.core.mgmt.rebind.persister.ListeningObjectStore.RecordingTransactionListener;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-/** uses recorder to ensure not too much data is written */
-@Test
-public class BrooklynMementoPersisterInMemorySizeIntegrationTest extends BrooklynMementoPersisterTestFixture {
-
-    protected RecordingTransactionListener recorder;
-    
-    protected ManagementContext newPersistingManagementContext() {
-        recorder = new RecordingTransactionListener("in-mem-test-"+Identifiers.makeRandomId(4));
-        return RebindTestUtils.managementContextBuilder(classLoader, 
-            new ListeningObjectStore(new InMemoryObjectStore(), recorder))
-            .persistPeriod(Duration.millis(100)).buildStarted();
-    }
-    
-    public void testPersistenceVolumeFast() throws IOException, TimeoutException, InterruptedException {
-        doTestPersistenceVolume(50*1000, false, true);
-    }
-    @Test(groups="Integration",invocationCount=20)
-    public void testPersistenceVolumeFastManyTimes() throws IOException, TimeoutException, InterruptedException {
-        doTestPersistenceVolume(50*1000, false, true);
-    }
-    @Test(groups="Integration")
-    public void testPersistenceVolumeWaiting() throws IOException, TimeoutException, InterruptedException {
-        // by waiting we ensure there aren't extra writes going on
-        doTestPersistenceVolume(50*1000, true, true);
-    }
-    public void testPersistenceVolumeFastNoTrigger() throws IOException, TimeoutException, InterruptedException {
-        doTestPersistenceVolume(50*1000, false, false);
-    }
-    @Test(groups="Integration",invocationCount=20)
-    public void testPersistenceVolumeFastNoTriggerManyTimes() throws IOException, TimeoutException, InterruptedException {
-        doTestPersistenceVolume(50*1000, false, false);
-    }
-    
-    protected void doTestPersistenceVolume(int bigBlockSize, boolean forceDelay, boolean canTrigger) throws IOException, TimeoutException, InterruptedException {
-        if (forceDelay) Time.sleep(Duration.FIVE_SECONDS);
-        else recorder.blockUntilDataWrittenExceeds(512, Duration.FIVE_SECONDS);
-        localManagementContext.getRebindManager().waitForPendingComplete(Duration.FIVE_SECONDS, canTrigger);
-        
-        long out1 = recorder.getBytesOut();
-        int filesOut1 = recorder.getCountDataOut();
-        Assert.assertTrue(out1>512, "should have written at least 0.5k, only wrote "+out1);
-        Assert.assertTrue(out1<30*1000, "should have written less than 30k, wrote "+out1);
-        Assert.assertTrue(filesOut1<30, "should have written fewer than 30 files, wrote "+out1);
-        
-        ((EntityInternal)app).setAttribute(TestEntity.NAME, "hello world");
-        if (forceDelay) Time.sleep(Duration.FIVE_SECONDS);
-        else recorder.blockUntilDataWrittenExceeds(out1+10, Duration.FIVE_SECONDS);
-        localManagementContext.getRebindManager().waitForPendingComplete(Duration.FIVE_SECONDS, canTrigger);
-        
-        long out2 = recorder.getBytesOut();
-        Assert.assertTrue(out2-out1>10, "should have written more data");
-        int filesOut2 = recorder.getCountDataOut();
-        Assert.assertTrue(filesOut2>filesOut1, "should have written more files");
-        
-        Assert.assertTrue(out2<50*1000, "should have written less than 50k, wrote "+out1);
-        Assert.assertTrue(filesOut2<40, "should have written fewer than 40 files, wrote "+out1);
-        
-        ((EntityInternal)entity).setAttribute(TestEntity.NAME, Identifiers.makeRandomId(bigBlockSize));
-        if (forceDelay) Time.sleep(Duration.FIVE_SECONDS);
-        else recorder.blockUntilDataWrittenExceeds(out2+bigBlockSize, Duration.FIVE_SECONDS);
-        localManagementContext.getRebindManager().waitForPendingComplete(Duration.FIVE_SECONDS, canTrigger);
-
-        long out3 = recorder.getBytesOut();
-        Assert.assertTrue(out3-out2 > bigBlockSize, "should have written 50k more data, only wrote "+out3+" compared with "+out2);
-        int filesOut3 = recorder.getCountDataOut();
-        Assert.assertTrue(filesOut3>filesOut2, "should have written more files");
-        
-        Assert.assertTrue(out2<100*1000+bigBlockSize, "should have written less than 100k+block, wrote "+out1);
-        Assert.assertTrue(filesOut2<60, "should have written fewer than 60 files, wrote "+out1);
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterInMemoryTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterInMemoryTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterInMemoryTest.java
deleted file mode 100644
index 837c3c3..0000000
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterInMemoryTest.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
-import org.apache.brooklyn.util.time.Duration;
-import org.testng.annotations.Test;
-
-@Test
-public class BrooklynMementoPersisterInMemoryTest extends BrooklynMementoPersisterTestFixture {
-
-    protected ManagementContext newPersistingManagementContext() {
-        return RebindTestUtils.managementContextBuilder(classLoader, new InMemoryObjectStore())
-            .persistPeriod(Duration.millis(10)).buildStarted();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterTestFixture.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterTestFixture.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterTestFixture.java
deleted file mode 100644
index fb231d8..0000000
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynMementoPersisterTestFixture.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-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 org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.rebind.PersistenceExceptionHandler;
-import org.apache.brooklyn.api.mgmt.rebind.RebindManager.RebindFailureMode;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMemento;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoPersister;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
-import org.apache.brooklyn.api.policy.Policy;
-import org.apache.brooklyn.api.sensor.Enricher;
-import org.apache.brooklyn.core.mgmt.rebind.PersistenceExceptionHandlerImpl;
-import org.apache.brooklyn.core.mgmt.rebind.RebindContextImpl;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
-import org.apache.brooklyn.core.mgmt.rebind.RecordingRebindExceptionHandler;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynMementoPersisterToObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.core.test.policy.TestPolicy;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.sensor.enricher.Enrichers;
-import org.testng.SkipException;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-import com.google.common.collect.Iterables;
-
-/**
- * @author Andrea Turli
- */
-public abstract class BrooklynMementoPersisterTestFixture {
-
-    protected ClassLoader classLoader = getClass().getClassLoader();
-    protected BrooklynMementoPersister persister;
-    protected TestApplication app;
-    protected Entity entity;
-    protected Location location;
-    protected ManagementContext localManagementContext;
-    protected Enricher enricher;
-    protected Policy policy;
-    
-    protected PersistenceObjectStore objectStore;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        localManagementContext = newPersistingManagementContext();
-        if (persister==null) {
-            persister = localManagementContext.getRebindManager().getPersister();
-        }
-        if (objectStore==null && persister instanceof BrooklynMementoPersisterToObjectStore) {
-            objectStore = ((BrooklynMementoPersisterToObjectStore)persister).getObjectStore();
-        }
-        app = ApplicationBuilder.newManagedApp(EntitySpec.create(TestApplication.class), localManagementContext);
-        location =  localManagementContext.getLocationManager()
-            .createLocation(LocationSpec.create(SshMachineLocation.class)
-                .configure("address", "localhost"));
-        entity = app.createAndManageChild(EntitySpec.create(TestEntity.class).location(location));
-        enricher = app.addEnricher(Enrichers.builder().propagatingAll().from(entity).build());
-        app.addPolicy(policy = new TestPolicy());
-    }
-
-    protected abstract ManagementContext newPersistingManagementContext();
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (localManagementContext != null) Entities.destroyAll(localManagementContext);
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-        if (persister != null) persister.stop(false);
-        if (objectStore!=null) objectStore.deleteCompletely();
-        persister = null;
-    }
-
-    protected BrooklynMemento loadMemento() throws Exception {
-        RebindTestUtils.waitForPersisted(localManagementContext);
-        
-        RecordingRebindExceptionHandler failFast = new RecordingRebindExceptionHandler(RebindFailureMode.FAIL_FAST, RebindFailureMode.FAIL_FAST);
-        RebindContextImpl rebindContext = new RebindContextImpl(localManagementContext, failFast, classLoader);
-        // here we force these two to be reegistered in order to resolve the enricher and policy
-        // (normally rebind will do that after loading the manifests, but in this test we are just looking at persistence/manifest)
-        rebindContext.registerEntity(app.getId(), app);
-        rebindContext.registerEntity(entity.getId(), entity);
-        
-        BrooklynMemento reloadedMemento = persister.loadMemento(null, rebindContext.lookup(), failFast);
-        return reloadedMemento;
-    }
-    
-    protected BrooklynMementoRawData loadRawMemento(BrooklynMementoPersisterToObjectStore persister) throws Exception {
-        RebindTestUtils.waitForPersisted(localManagementContext);
-        
-        RecordingRebindExceptionHandler failFast = new RecordingRebindExceptionHandler(RebindFailureMode.FAIL_FAST, RebindFailureMode.FAIL_FAST);
-        BrooklynMementoRawData rawMemento = persister.loadMementoRawData(failFast);
-        return rawMemento;
-    }
-    
-    @Test
-    public void testCheckPointAndLoadMemento() throws Exception {
-        BrooklynMemento reloadedMemento = loadMemento();
-        
-        assertNotNull(reloadedMemento);
-        assertTrue(Iterables.contains(reloadedMemento.getEntityIds(), entity.getId()));
-        assertEquals(Iterables.getOnlyElement(reloadedMemento.getLocationIds()), location.getId());
-        assertEquals(Iterables.getOnlyElement(reloadedMemento.getPolicyIds()), policy.getId());
-        assertTrue(reloadedMemento.getEnricherIds().contains(enricher.getId()));
-    }
-
-    @Test
-    public void testDeleteAndLoadMemento() throws Exception {
-        Entities.destroy(entity);
-
-        BrooklynMemento reloadedMemento = loadMemento();
-        
-        assertNotNull(reloadedMemento);
-        assertFalse(Iterables.contains(reloadedMemento.getEntityIds(), entity.getId()));
-        assertEquals(Iterables.getOnlyElement(reloadedMemento.getLocationIds()), location.getId());
-    }
-    
-    @Test
-    public void testLoadAndCheckpointRawMemento() throws Exception {
-        if (persister instanceof BrooklynMementoPersisterToObjectStore) {
-            // Test loading
-            BrooklynMementoRawData rawMemento = loadRawMemento((BrooklynMementoPersisterToObjectStore)persister);
-            assertNotNull(rawMemento);
-            assertTrue(Iterables.contains(rawMemento.getEntities().keySet(), entity.getId()));
-            assertEquals(Iterables.getOnlyElement(rawMemento.getLocations().keySet()), location.getId());
-            assertEquals(Iterables.getOnlyElement(rawMemento.getPolicies().keySet()), policy.getId());
-            assertTrue(rawMemento.getEnrichers().keySet().contains(enricher.getId()));
-            
-            // And test persisting
-            PersistenceExceptionHandler exceptionHandler = PersistenceExceptionHandlerImpl.builder().build();
-            ((BrooklynMementoPersisterToObjectStore) persister).checkpoint(rawMemento, exceptionHandler);
-        } else {
-            throw new SkipException("Persister "+persister+" not a "+BrooklynMementoPersisterToObjectStore.class.getSimpleName());
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/FileBasedObjectStoreTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/FileBasedObjectStoreTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/FileBasedObjectStoreTest.java
deleted file mode 100644
index 56cc10a..0000000
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/FileBasedObjectStoreTest.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.FileBasedObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.util.io.FileUtil;
-import org.apache.brooklyn.util.os.Os;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.io.Files;
-
-public class FileBasedObjectStoreTest {
-
-    private LocalManagementContextForTests mgmt;
-    private File parentdir;
-    private File basedir;
-    private FileBasedObjectStore store;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        mgmt = new LocalManagementContextForTests();
-        parentdir = Files.createTempDir();
-        basedir = new File(parentdir, "mystore");
-        store = new FileBasedObjectStore(basedir);
-        store.injectManagementContext(mgmt);
-        store.prepareForSharedUse(PersistMode.AUTO, HighAvailabilityMode.DISABLED);
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (store != null) store.close();
-        if (parentdir != null) Os.deleteRecursively(basedir);
-        if (mgmt != null) Entities.destroyAll(mgmt);
-    }
-    
-    @Test(groups="Integration")
-    public void testSubPathCreatedWithPermission700() throws Exception {
-        store.createSubPath("mysubdir");
-        File subdir = new File(basedir, "mysubdir");
-        
-        assertFilePermission700(basedir);
-        assertFilePermission700(subdir);
-    }
-    
-    @Test
-    public void testIsMementoDirExistsButEmpty() throws Exception {
-        basedir = new File(parentdir, "testIsMementoDirExistsButEmpty");
-        assertFalse(FileBasedObjectStore.isMementoDirExistButEmpty(basedir));
-        assertFalse(FileBasedObjectStore.isMementoDirExistButEmpty(basedir.getAbsolutePath()));
-        
-        basedir.mkdir();
-        assertTrue(FileBasedObjectStore.isMementoDirExistButEmpty(basedir));
-        assertTrue(FileBasedObjectStore.isMementoDirExistButEmpty(basedir.getAbsolutePath()));
-        
-        new File(basedir, "entities").mkdir();
-        new File(basedir, "locations").mkdir();
-        assertTrue(FileBasedObjectStore.isMementoDirExistButEmpty(basedir));
-        assertTrue(FileBasedObjectStore.isMementoDirExistButEmpty(basedir.getAbsolutePath()));
-        
-        new File(new File(basedir, "locations"), "afile").createNewFile();
-        assertFalse(FileBasedObjectStore.isMementoDirExistButEmpty(basedir));
-        assertFalse(FileBasedObjectStore.isMementoDirExistButEmpty(basedir.getAbsolutePath()));
-    }
-    
-    static void assertFilePermission700(File file) throws FileNotFoundException {
-        assertEquals(FileUtil.getFilePermissions(file).get().substring(1), "rwx------");
-    }
-    
-    static void assertFilePermission600(File file) throws Exception {
-        assertEquals(FileUtil.getFilePermissions(file).get().substring(1), "rw-------");
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/FileBasedStoreObjectAccessorWriterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/FileBasedStoreObjectAccessorWriterTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/FileBasedStoreObjectAccessorWriterTest.java
deleted file mode 100644
index 2363f22..0000000
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/persister/FileBasedStoreObjectAccessorWriterTest.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import static org.testng.Assert.assertEquals;
-
-import java.io.File;
-import java.io.IOException;
-
-import org.apache.brooklyn.core.mgmt.rebind.persister.FileBasedStoreObjectAccessor;
-import org.apache.brooklyn.core.mgmt.rebind.persister.StoreObjectAccessorLocking;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore.StoreObjectAccessorWithLock;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.time.Duration;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Charsets;
-import com.google.common.collect.ImmutableList;
-import com.google.common.io.Files;
-
-@Test
-public class FileBasedStoreObjectAccessorWriterTest extends PersistenceStoreObjectAccessorWriterTestFixture {
-
-    private File file;
-    
-    protected StoreObjectAccessorWithLock newPersistenceStoreObjectAccessor() throws IOException {
-        file = Os.newTempFile(getClass(), "txt");
-        return new StoreObjectAccessorLocking(new FileBasedStoreObjectAccessor(file, ".tmp"));
-    }
-    
-    @Override
-    protected Duration getLastModifiedResolution() {
-        // OSX is 1s, Windows FAT is 2s !
-        return Duration.seconds(2);
-    }
-    
-    @Test(groups="Integration")
-    public void testLastModifiedTime() throws Exception {
-        super.testLastModifiedTime();
-    }
-    
-    @Test(groups="Integration")
-    public void testFilePermissions600() throws Exception {
-        accessor.put("abc");
-        assertEquals(Files.readLines(file, Charsets.UTF_8), ImmutableList.of("abc"));
-        
-        FileBasedObjectStoreTest.assertFilePermission600(file);
-    }
-}


[16/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/lifecycle/MyEntityImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/MyEntityImpl.java b/software/base/src/test/java/brooklyn/entity/basic/lifecycle/MyEntityImpl.java
deleted file mode 100644
index 2f0e336..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/MyEntityImpl.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic.lifecycle;
-
-import java.util.List;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.basic.SoftwareProcessDriver;
-import brooklyn.entity.basic.SoftwareProcessImpl;
-import brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.ResourceUtils;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.apache.brooklyn.util.text.Identifiers;
-
-public class MyEntityImpl extends SoftwareProcessImpl implements MyEntity {
-    @Override
-    public Class<?> getDriverInterface() {
-        return MyEntityDriver.class;
-    }
-
-    @Override
-    protected void connectSensors() {
-        super.connectSensors();
-        connectServiceUpIsRunning();
-    }
-    
-    @Override
-    protected void disconnectSensors() {
-        super.disconnectSensors();
-        disconnectServiceUpIsRunning();
-    }
-    
-    public interface MyEntityDriver extends SoftwareProcessDriver {}
-
-    public static class MyEntitySshDriver extends JavaSoftwareProcessSshDriver implements MyEntityDriver {
-
-        @SetFromFlag("version")
-        public static final ConfigKey<String> SUGGESTED_VERSION = ConfigKeys.newConfigKeyWithDefault(SoftwareProcess.SUGGESTED_VERSION, "0.1");
-
-        public MyEntitySshDriver(MyEntityImpl entity, SshMachineLocation machine) {
-            super(entity, machine);
-        }
-
-        @Override
-        protected String getLogFileLocation() {
-            return getRunDir()+"/nohup.out";
-        }
-        
-        @Override
-        public void install() {
-            String resourceName = "/"+MyEntityApp.class.getName().replace(".", "/")+".class";
-            ResourceUtils r = ResourceUtils.create(this);
-            if (r.getResourceFromUrl(resourceName) == null) 
-                throw new IllegalStateException("Cannot find resource "+resourceName);
-            String tmpFile = "/tmp/brooklyn-test-MyEntityApp-"+Identifiers.makeRandomId(6)+".class";
-            int result = getMachine().installTo(resourceName, tmpFile);
-            if (result!=0) throw new IllegalStateException("Cannot install "+resourceName+" to "+tmpFile);
-            String saveAs = "classes/"+MyEntityApp.class.getPackage().getName().replace(".", "/")+"/"+MyEntityApp.class.getSimpleName()+".class";
-            newScript(INSTALLING).
-                failOnNonZeroResultCode().
-                body.append(
-                    "curl -L \"file://"+tmpFile+"\" --create-dirs -o "+saveAs+" || exit 9"
-                ).execute();
-        }
-
-        @Override
-        public void customize() {
-            newScript(CUSTOMIZING)
-                .execute();
-        }
-        
-        @Override
-        public void launch() {
-            newScript(MutableMap.of("usePidFile", true), LAUNCHING)
-                .body.append(
-                    String.format("nohup java -classpath %s/classes $JAVA_OPTS %s &", getInstallDir(), MyEntityApp.class.getName())
-                ).execute();
-        }
-        
-        @Override
-        public boolean isRunning() {
-            //TODO use PID instead
-            return newScript(MutableMap.of("usePidFile", true), CHECK_RUNNING)
-                .execute() == 0;
-        }
-        
-        @Override
-        public void stop() {
-            newScript(MutableMap.of("usePidFile", true), STOPPING)
-                .execute();
-        }
-
-        @Override
-        public void kill() {
-            newScript(MutableMap.of("usePidFile", true), KILLING)
-                .execute();
-        }
-
-        @Override
-        protected List<String> getCustomJavaConfigOptions() {
-            return MutableList.<String>builder().addAll(super.getCustomJavaConfigOptions()).add("-Dabc=def").build();
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/lifecycle/NaiveScriptRunnerTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/NaiveScriptRunnerTest.java b/software/base/src/test/java/brooklyn/entity/basic/lifecycle/NaiveScriptRunnerTest.java
deleted file mode 100644
index 4ef2bde..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/NaiveScriptRunnerTest.java
+++ /dev/null
@@ -1,252 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic.lifecycle;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags.WrappedStream;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.task.BasicExecutionContext;
-import org.apache.brooklyn.util.core.task.BasicExecutionManager;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.repeat.Repeater;
-import org.apache.brooklyn.util.time.Duration;
-
-import com.google.common.base.Throwables;
-
-@Test
-public class NaiveScriptRunnerTest {
-    
-    private static final Logger log = LoggerFactory.getLogger(NaiveScriptRunnerTest.class);
-    
-    List<String> commands = new ArrayList<String>();
-    
-    @BeforeMethod
-    private void setup() { commands.clear(); }
-    
-    @SuppressWarnings("rawtypes")
-    private NaiveScriptRunner newMockRunner(final int result) {
-        return new NaiveScriptRunner() {
-            @Override
-            public int execute(List<String> script, String summaryForLogging) {
-                return execute(new MutableMap(), script, summaryForLogging);
-            }
-            @Override
-            public int execute(Map flags, List<String> script, String summaryForLogging) {
-                commands.addAll(script);
-                return result;                
-            }
-        };
-    }
-
-    @SuppressWarnings("rawtypes")
-    public static NaiveScriptRunner newLocalhostRunner() {
-        return new NaiveScriptRunner() {
-            LocalhostMachineProvisioningLocation location = new LocalhostMachineProvisioningLocation();
-            @Override
-            public int execute(List<String> script, String summaryForLogging) {
-                return execute(new MutableMap(), script, summaryForLogging);
-            }
-            @SuppressWarnings("unchecked")
-            @Override
-            public int execute(Map flags, List<String> script, String summaryForLogging) {
-                try {
-                    Map flags2 = MutableMap.of("logPrefix", "test");
-                    flags2.putAll(flags);
-                    return location.obtain().execScript(flags2, summaryForLogging, script);
-                } catch (NoMachinesAvailableException e) {
-                    throw Throwables.propagate(e);
-                }
-            }
-        };
-    };
-
-    public void testHeadBodyFootAndResult() {
-        ScriptHelper h = new ScriptHelper(newMockRunner(101), "mock");
-        int result = h.header.
-                append("h1", "h2").body.append("b1", "b2").footer.append("f1", "f2").
-                execute();
-        Assert.assertEquals(result, 101);
-        Assert.assertEquals(commands, Arrays.asList("h1", "h2", "b1", "b2", "f1", "f2"), "List wrong: "+commands);
-    }
-
-    public void testFailOnNonZero() {
-        ScriptHelper h = new ScriptHelper(newMockRunner(106), "mock");
-        boolean succeededWhenShouldntHave = false;
-        try {
-            h.body.append("ignored").
-                failOnNonZeroResultCode().   // will happen
-                execute();            
-            succeededWhenShouldntHave = true;
-        } catch (Exception e) {
-            log.info("ScriptHelper non-zero causes return code: "+e);
-        }
-        if (succeededWhenShouldntHave) Assert.fail("succeeded when shouldn't have");
-    }
-
-    public void testFailOnNonZeroDontFailIfZero() {
-        int result = new ScriptHelper(newMockRunner(0), "mock").body.append("ignored").
-                failOnNonZeroResultCode().   // will happen
-                execute();
-        Assert.assertEquals(result, 0);
-    }
-
-
-    @Test(groups = "Integration")
-    public void testFailingCommandFailsEarly() {
-        ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock").
-                body.append("curl road://to/nowhere", "exit 11").
-                gatherOutput();
-        int result = script.execute();
-        // should get _1_ from curl failing, not 11 from us
-        // TODO not sure why though!
-        Assert.assertEquals(1, result);
-    }
-
-    // TODO a good way to indicate when downloads fail, as that is quite a common case
-    // but i think we need quite a bit of scaffolding to detect that problem (without inspecting logs) ...
-
-    @Test(groups = "Integration")
-    public void testGatherOutputStdout() {
-        ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock").
-                body.append("echo `echo foo``echo bar`", "exit 8").
-                gatherOutput();
-        int result = script.execute();
-        Assert.assertEquals(8, result);
-        if (!script.getResultStdout().contains("foobar"))
-            Assert.fail("STDOUT does not contain expected text 'foobar'.\n"+script.getResultStdout()+
-                    "\nSTDERR:\n"+script.getResultStderr());
-    }
-
-    @Test(groups = "Integration")
-    public void testGatherOutputStderr() {
-        ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock").
-                body.append("set -x", "curl road://to/nowhere || exit 11").
-                gatherOutput();
-        int result = script.execute();
-        Assert.assertEquals(11, result);
-        if (!script.getResultStderr().contains("road"))
-            Assert.fail("STDERR does not contain expected text 'road'.\n"+script.getResultStderr()+
-                    "\nSTDOUT:\n"+script.getResultStdout());
-    }
-
-    @Test(groups = "Integration")
-    public void testGatherOutuputNotEnabled() {
-        ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock").
-                body.append("echo foo", "exit 11");
-        int result = script.execute();
-        Assert.assertEquals(11, result);
-        boolean succeededWhenShouldNotHave = false;
-        try {
-            script.getResultStdout();
-            succeededWhenShouldNotHave = true;
-        } catch (Exception e) { /* expected */ }
-        if (succeededWhenShouldNotHave) Assert.fail("Should have failed");
-    }
-
-    @Test(groups = "Integration")
-    public void testStreamsInTask() {
-        final ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock").
-                body.append("echo `echo foo``echo bar`", "grep absent-text badfile_which_does_not_exist_blaahblahasdewq").
-                gatherOutput();
-        Assert.assertNull(script.peekTask());
-        Task<Integer> task = script.newTask();
-        Assert.assertTrue(BrooklynTaskTags.streams(task).size() >= 3, "Expected at least 3 streams: "+BrooklynTaskTags.streams(task));
-        Assert.assertFalse(Tasks.isQueuedOrSubmitted(task));
-        WrappedStream in = BrooklynTaskTags.stream(task, BrooklynTaskTags.STREAM_STDIN);
-        Assert.assertNotNull(in);
-        Assert.assertTrue(in.streamContents.get().contains("echo foo"), "Expected 'echo foo' but had: "+in.streamContents.get());
-        Assert.assertTrue(in.streamSize.get() > 0);
-        Assert.assertNotNull(script.peekTask());
-    }
-
-    @Test(groups = "Integration")
-    public void testAutoQueueAndRuntimeStreamsInTask() {
-        final ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock").
-                body.append("echo `echo foo``echo bar`", "grep absent-text badfile_which_does_not_exist_blaahblahasdewq").
-                gatherOutput();
-        Task<Integer> submitter = Tasks.<Integer>builder().body(new Callable<Integer>() {
-            public Integer call() {
-                int result = script.execute();
-                return result;
-            } 
-        }).build();
-        BasicExecutionManager em = new BasicExecutionManager("tests");
-        BasicExecutionContext ec = new BasicExecutionContext(em);
-        try {
-            Assert.assertNull(script.peekTask());
-            ec.submit(submitter);
-            // soon there should be a task which is submitted
-            Assert.assertTrue(Repeater.create("get script").every(Duration.millis(10)).limitTimeTo(Duration.FIVE_SECONDS).until(new Callable<Boolean>() {
-                public Boolean call() { 
-                    return (script.peekTask() != null) && Tasks.isQueuedOrSubmitted(script.peekTask());
-                }
-            }).run());
-            Task<Integer> task = script.peekTask();
-            Assert.assertTrue(BrooklynTaskTags.streams(task).size() >= 3, "Expected at least 3 streams: "+BrooklynTaskTags.streams(task));
-            // stdin should be populated
-            WrappedStream in = BrooklynTaskTags.stream(task, BrooklynTaskTags.STREAM_STDIN);
-            Assert.assertNotNull(in);
-            Assert.assertTrue(in.streamContents.get().contains("echo foo"), "Expected 'echo foo' but had: "+in.streamContents.get());
-            Assert.assertTrue(in.streamSize.get() > 0);
-            
-            // out and err should exist
-            WrappedStream out = BrooklynTaskTags.stream(task, BrooklynTaskTags.STREAM_STDOUT);
-            WrappedStream err = BrooklynTaskTags.stream(task, BrooklynTaskTags.STREAM_STDERR);
-            Assert.assertNotNull(out);
-            Assert.assertNotNull(err);
-            
-            // it should soon finish, with exit code
-            Integer result = task.getUnchecked(Duration.TEN_SECONDS);
-            Assert.assertNotNull(result);
-            Assert.assertTrue(result > 0, "Expected non-zero exit code: "+result);
-            // and should contain foobar in stdout
-            if (!script.getResultStdout().contains("foobar"))
-                Assert.fail("Script STDOUT does not contain expected text 'foobar'.\n"+script.getResultStdout()+
-                        "\nSTDERR:\n"+script.getResultStderr());
-            if (!out.streamContents.get().contains("foobar"))
-                Assert.fail("Task STDOUT does not contain expected text 'foobar'.\n"+out.streamContents.get()+
-                        "\nSTDERR:\n"+script.getResultStderr());
-            // and "No such file or directory" in stderr
-            if (!script.getResultStderr().contains("No such file or directory"))
-                Assert.fail("Script STDERR does not contain expected text 'No such ...'.\n"+script.getResultStdout()+
-                        "\nSTDERR:\n"+script.getResultStderr());
-            if (!err.streamContents.get().contains("No such file or directory"))
-                Assert.fail("Task STDERR does not contain expected text 'No such...'.\n"+out.streamContents.get()+
-                        "\nSTDERR:\n"+script.getResultStderr());
-        } finally {
-            em.shutdownNow();
-        }
-    }
-
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/lifecycle/ScriptHelperTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/ScriptHelperTest.java b/software/base/src/test/java/brooklyn/entity/basic/lifecycle/ScriptHelperTest.java
deleted file mode 100644
index f0288f3..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/ScriptHelperTest.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic.lifecycle;
-
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.sensor.feed.function.FunctionFeed;
-import org.apache.brooklyn.sensor.feed.function.FunctionPollConfig;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.time.Duration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.TestException;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.basic.SoftwareProcessEntityTest;
-import brooklyn.entity.basic.SoftwareProcessEntityTest.MyService;
-import brooklyn.entity.basic.SoftwareProcessEntityTest.MyServiceImpl;
-
-import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-import com.google.common.base.Functions;
-import com.google.common.collect.ImmutableList;
-
-public class ScriptHelperTest extends BrooklynAppUnitTestSupport {
-    
-    private static final Logger log = LoggerFactory.getLogger(ScriptHelperTest.class);
-    
-    private SshMachineLocation machine;
-    private FixedListMachineProvisioningLocation<SshMachineLocation> loc;
-    boolean shouldFail = false;
-    int failCount = 0;
-    
-    @BeforeMethod(alwaysRun=true)
-    @SuppressWarnings("unchecked")
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-        loc = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class));
-        machine = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                .configure("address", "localhost"));
-        loc.addMachine(machine);
-    }
-
-    @Test
-    public void testCheckRunningForcesInessential() {
-        MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class, MyServiceInessentialDriverImpl.class));
-        
-        entity.start(ImmutableList.of(loc));
-        SimulatedInessentialIsRunningDriver driver = (SimulatedInessentialIsRunningDriver) entity.getDriver();
-        Assert.assertTrue(driver.isRunning());
-        
-        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, true);
-        EntityTestUtils.assertAttributeEqualsEventually(entity, Startable.SERVICE_UP, true);
-        
-        log.debug("up, now cause failure");
-        
-        driver.setFailExecution(true);
-        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, false);
-        
-        log.debug("caught failure, now clear");
-        driver.setFailExecution(false);
-        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, true);
-    }
-    
-    public static class MyServiceInessentialDriverImpl extends MyServiceImpl {
-
-        @Override public Class<?> getDriverInterface() {
-            return SimulatedInessentialIsRunningDriver.class;
-        }
-
-        @Override
-        protected void connectSensors() {
-            super.connectSensors();
-            connectServiceUpIsRunning();
-        }
-        
-        @Override
-        public void connectServiceUpIsRunning() {
-//            super.connectServiceUpIsRunning();
-            // run more often
-            FunctionFeed.builder()
-                .entity(this)
-                .period(Duration.millis(10))
-                .poll(new FunctionPollConfig<Boolean, Boolean>(SERVICE_PROCESS_IS_RUNNING)
-                    .onException(Functions.constant(Boolean.FALSE))
-                    .callable(new Callable<Boolean>() {
-                        public Boolean call() {
-                            return getDriver().isRunning();
-                        }
-                    }))
-                .build();
-        }
-    }
-    
-    public static class SimulatedInessentialIsRunningDriver extends SoftwareProcessEntityTest.SimulatedDriver {
-        private boolean failExecution = false;
-
-        public SimulatedInessentialIsRunningDriver(EntityLocal entity, SshMachineLocation machine) {
-            super(entity, machine);
-        }
-        
-        @Override
-        public boolean isRunning() {
-            return newScript(CHECK_RUNNING)
-                .execute() == 0;
-        }
-        
-        @Override
-        public int execute(List<String> script, String summaryForLogging) {
-            if (failExecution) {
-                throw new TestException("Simulated driver exception");
-            }
-            return 0;
-        }
-        
-        @SuppressWarnings("rawtypes")
-        @Override
-        public int execute(Map flags2, List<String> script, String summaryForLogging) {
-            if (failExecution) {
-                throw new TestException("Simulated driver exception");
-            }
-            return 0;
-        }
-        
-        public void setFailExecution(boolean failExecution) {
-            this.failExecution = failExecution;
-        }
-        
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/lifecycle/StartStopSshDriverTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/StartStopSshDriverTest.java b/software/base/src/test/java/brooklyn/entity/basic/lifecycle/StartStopSshDriverTest.java
deleted file mode 100644
index 48bc72c..0000000
--- a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/StartStopSshDriverTest.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic.lifecycle;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-
-import java.io.ByteArrayOutputStream;
-import java.lang.management.ManagementFactory;
-import java.lang.management.ThreadInfo;
-import java.lang.management.ThreadMXBean;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.core.test.entity.TestApplicationImpl;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.core.test.entity.TestEntityImpl;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableSet;
-import org.apache.brooklyn.util.core.internal.ssh.SshTool;
-import org.apache.brooklyn.util.core.internal.ssh.cli.SshCliTool;
-import org.apache.brooklyn.util.core.internal.ssh.sshj.SshjTool;
-import org.apache.brooklyn.util.stream.StreamGobbler;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-import com.google.common.base.Function;
-import com.google.common.collect.FluentIterable;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-
-public class StartStopSshDriverTest {
-
-    public class BasicStartStopSshDriver extends AbstractSoftwareProcessSshDriver {
-        public BasicStartStopSshDriver(EntityLocal entity, SshMachineLocation machine) {
-            super(entity, machine);
-        }
-        public boolean isRunning() { return true; }
-        public void stop() {}
-        public void kill() {}
-        public void install() {}
-        public void customize() {}
-        public void launch() {}
-    }
-
-    private static class ThreadIdTransformer implements Function<ThreadInfo, Long> {
-        @Override
-        public Long apply(ThreadInfo t) {
-            return t.getThreadId();
-        }
-    }
-
-    private TestApplication app;
-    private TestEntity entity;
-    private SshMachineLocationWithSshTool sshMachineLocation;
-    private AbstractSoftwareProcessSshDriver driver;
-
-    @SuppressWarnings("rawtypes")
-    protected static class SshMachineLocationWithSshTool extends SshMachineLocation {
-        private static final long serialVersionUID = 1L;
-
-        SshTool lastTool;
-        public SshMachineLocationWithSshTool(Map flags) { super(flags); }
-        public SshTool connectSsh(Map args) {
-            SshTool result = super.connectSsh(args);
-            lastTool = result;
-            return result;
-        }
-    }
-    
-    @BeforeMethod(alwaysRun = true)
-    public void setUp() {
-        app = new TestApplicationImpl();
-        entity = new TestEntityImpl(app);
-        Entities.startManagement(app);
-        sshMachineLocation = new SshMachineLocationWithSshTool(ImmutableMap.of("address", "localhost"));
-        driver = new BasicStartStopSshDriver(entity, sshMachineLocation);
-    }
-    
-    @Test(groups="Integration")
-    public void testExecuteDoesNotLeaveRunningStreamGobblerThread() {
-        List<ThreadInfo> existingThreads = getThreadsCalling(StreamGobbler.class);
-        final List<Long> existingThreadIds = getThreadId(existingThreads);
-        
-        List<String> script = Arrays.asList("echo hello");
-        driver.execute(script, "mytest");
-        
-        Asserts.succeedsEventually(ImmutableMap.of("timeout", 10*1000), new Runnable() {
-            @Override
-            public void run() {
-              List<ThreadInfo> currentThreads = getThreadsCalling(StreamGobbler.class);
-              Set<Long> currentThreadIds = MutableSet.copyOf(getThreadId(currentThreads));
-
-              currentThreadIds.removeAll(existingThreadIds);
-              assertEquals(currentThreadIds, ImmutableSet.<Long>of());
-            }
-        });
-    }
-
-    @Test(groups="Integration")
-    public void testSshScriptHeaderUsedWhenSpecified() {
-        entity.setConfig(BrooklynConfigKeys.SSH_CONFIG_SCRIPT_HEADER, "#!/bin/bash -e\necho hello world");
-        ByteArrayOutputStream out = new ByteArrayOutputStream();
-        driver.execute(ImmutableMap.of("out", out), Arrays.asList("echo goodbye"), "test");
-        String s = out.toString();
-        assertTrue(s.contains("goodbye"), "should have said goodbye: "+s);
-        assertTrue(s.contains("hello world"), "should have said hello: "+s);
-        assertTrue(sshMachineLocation.lastTool instanceof SshjTool, "expect sshj tool, got "+
-            (sshMachineLocation.lastTool!=null ? ""+sshMachineLocation.lastTool.getClass()+":" : "") + sshMachineLocation.lastTool);
-    }
-
-    @Test(groups="Integration")
-    public void testSshCliPickedUpWhenSpecified() {
-        entity.setConfig(BrooklynConfigKeys.SSH_TOOL_CLASS, SshCliTool.class.getName());
-        driver.execute(Arrays.asList("echo hi"), "test");
-        assertTrue(sshMachineLocation.lastTool instanceof SshCliTool, "expect CLI tool, got "+
-                        (sshMachineLocation.lastTool!=null ? ""+sshMachineLocation.lastTool.getClass()+":" : "") + sshMachineLocation.lastTool);
-    }
-    
-    private List<ThreadInfo> getThreadsCalling(Class<?> clazz) {
-        String clazzName = clazz.getCanonicalName();
-        List<ThreadInfo> result = MutableList.of();
-        ThreadMXBean threadMxbean = ManagementFactory.getThreadMXBean();
-        ThreadInfo[] threads = threadMxbean.dumpAllThreads(false, false);
-        
-        for (ThreadInfo thread : threads) {
-            StackTraceElement[] stackTrace = thread.getStackTrace();
-            for (StackTraceElement stackTraceElement : stackTrace) {
-                if (clazzName == stackTraceElement.getClassName()) {
-                    result.add(thread);
-                    break;
-                }
-            }
-        }
-        return result;
-    }
-
-    private ImmutableList<Long> getThreadId(List<ThreadInfo> existingThreads) {
-        return FluentIterable.from(existingThreads).transform(new ThreadIdTransformer()).toList();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java b/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java
deleted file mode 100644
index e69abc2..0000000
--- a/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import java.io.File;
-import java.util.List;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.javalang.JavaClassNames;
-import org.apache.brooklyn.util.net.Networking;
-import org.apache.brooklyn.util.os.Os;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.brooklynnode.BrooklynNode.ExistingFileBehaviour;
-
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-
-import com.google.common.base.Predicates;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-
-public class BrooklynClusterIntegrationTest extends BrooklynAppUnitTestSupport {
-
-    private static final Logger LOG = LoggerFactory.getLogger(BrooklynNodeIntegrationTest.class);
-
-    private File pseudoBrooklynPropertiesFile;
-    private File pseudoBrooklynCatalogFile;
-    private File persistenceDir;
-    private LocalhostMachineProvisioningLocation loc;
-    private List<LocalhostMachineProvisioningLocation> locs;
-
-    @BeforeMethod(alwaysRun=true)
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-        pseudoBrooklynPropertiesFile = Os.newTempFile("brooklynnode-test", ".properties");
-        pseudoBrooklynPropertiesFile.delete();
-
-        pseudoBrooklynCatalogFile = Os.newTempFile("brooklynnode-test", ".catalog");
-        pseudoBrooklynCatalogFile.delete();
-
-        loc = app.newLocalhostProvisioningLocation();
-        locs = ImmutableList.of(loc);
-    }
-
-    @AfterMethod(alwaysRun=true)
-    @Override
-    public void tearDown() throws Exception {
-        try {
-            super.tearDown();
-        } finally {
-            if (pseudoBrooklynPropertiesFile != null) pseudoBrooklynPropertiesFile.delete();
-            if (pseudoBrooklynCatalogFile != null) pseudoBrooklynCatalogFile.delete();
-            if (persistenceDir != null) Os.deleteRecursively(persistenceDir);
-        }
-    }
-
-    @Test(groups="Integration")
-    public void testCanStartAndStop() throws Exception {
-        BrooklynCluster cluster = app.createAndManageChild(EntitySpec.create(BrooklynCluster.class)
-                .configure(BrooklynCluster.INITIAL_SIZE, 1)
-                .configure(BrooklynNode.WEB_CONSOLE_BIND_ADDRESS, Networking.ANY_NIC)
-                .configure(BrooklynNode.ON_EXISTING_PROPERTIES_FILE, ExistingFileBehaviour.DO_NOT_USE));
-        app.start(locs);
-        Entity brooklynNode = Iterables.find(cluster.getMembers(), Predicates.instanceOf(BrooklynNode.class));
-        LOG.info("started "+app+" containing "+cluster+" for "+JavaClassNames.niceClassAndMethod());
-
-        EntityTestUtils.assertAttributeEqualsEventually(cluster, BrooklynNode.SERVICE_UP, true);
-        EntityTestUtils.assertAttributeEqualsEventually(brooklynNode, BrooklynNode.SERVICE_UP, true);
-
-        cluster.stop();
-        EntityTestUtils.assertAttributeEquals(cluster, BrooklynNode.SERVICE_UP, false);
-    }    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java b/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java
deleted file mode 100644
index fb4a99f..0000000
--- a/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java
+++ /dev/null
@@ -1,630 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
-
-import java.io.File;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.net.URI;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.ExecutionException;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.objs.proxy.EntityProxyImpl;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.entity.stock.BasicApplication;
-import org.apache.brooklyn.entity.stock.BasicApplicationImpl;
-import org.apache.brooklyn.sensor.feed.http.JsonFunctions;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.test.HttpTestUtils;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.http.HttpTool;
-import org.apache.brooklyn.util.core.http.HttpToolResponse;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.guava.Functionals;
-import org.apache.brooklyn.util.javalang.JavaClassNames;
-import org.apache.brooklyn.util.net.Networking;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.http.auth.UsernamePasswordCredentials;
-import org.apache.http.client.HttpClient;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.basic.SoftwareProcess.StopSoftwareParameters.StopMode;
-import brooklyn.entity.brooklynnode.BrooklynNode.DeployBlueprintEffector;
-import brooklyn.entity.brooklynnode.BrooklynNode.ExistingFileBehaviour;
-import brooklyn.entity.brooklynnode.BrooklynNode.StopNodeAndKillAppsEffector;
-
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.Locations;
-import org.apache.brooklyn.location.basic.PortRanges;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-import com.google.common.base.Charsets;
-import com.google.common.base.Function;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-import com.google.common.io.Files;
-
-/**
- * This test needs to able to access the binary artifact in order to run.
- * The default behaviour is to take this from maven, which works pretty well if you're downloading from hosted maven.
- * <p>
- * This class has been updated so that it does not effect or depend on the contents of ~/.brooklyn/brooklyn.properties .
- * <p>
- * If you wish to supply your own version (useful if testing changes locally!), you'll need to force download of this file.
- * The simplest way is to install:
- * <ul>
- * <li>file://$HOME/.brooklyn/repository/BrooklynNode/${VERSION}/BrooklynNode-${VERSION}.tar.gz - for snapshot versions (filename is default format due to lack of filename in sonatype inferencing; 
- *     note on case-sensitive systems it might have to be all in lower case!)
- * <li>file://$HOME/.brooklyn/repository/BrooklynNode/${VERSION}/brooklyn-${VERSION}-dist.tar.gz - for release versions, filename should match that in maven central
- * </ul>
- * In both cases, remember that you may also need to wipe the local apps cache ($BROOKLYN_DATA_DIR/installs/BrooklynNode).
- * The following commands may be useful:
- * <p>
- * <code>
- * cp ~/.m2/repository/org/apache/brooklyn/brooklyn-dist/0.7.0-SNAPSHOT/brooklyn-dist-0.7.0-SNAPSHOT-dist.tar.gz ~/.brooklyn/repository/BrooklynNode/0.7.0-SNAPSHOT/BrooklynNode-0.7.0-SNAPSHOT.tar.gz
- * rm -rf /tmp/brooklyn-`whoami`/installs/BrooklynNode*
- * </code>
- */
-public class BrooklynNodeIntegrationTest extends BrooklynAppUnitTestSupport {
-
-    private static final Logger log = LoggerFactory.getLogger(BrooklynNodeIntegrationTest.class);
-    
-    private File pseudoBrooklynPropertiesFile;
-    private File pseudoBrooklynCatalogFile;
-    private File persistenceDir;
-    private LocalhostMachineProvisioningLocation loc;
-    private List<LocalhostMachineProvisioningLocation> locs;
-
-    @BeforeMethod(alwaysRun=true)
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-        pseudoBrooklynPropertiesFile = Os.newTempFile("brooklynnode-test", ".properties");
-        pseudoBrooklynPropertiesFile.delete();
-
-        pseudoBrooklynCatalogFile = Os.newTempFile("brooklynnode-test", ".catalog");
-        pseudoBrooklynCatalogFile.delete();
-
-        loc = app.newLocalhostProvisioningLocation();
-        locs = ImmutableList.of(loc);
-    }
-
-    @AfterMethod(alwaysRun=true)
-    @Override
-    public void tearDown() throws Exception {
-        try {
-            super.tearDown();
-        } finally {
-            if (pseudoBrooklynPropertiesFile != null) pseudoBrooklynPropertiesFile.delete();
-            if (pseudoBrooklynCatalogFile != null) pseudoBrooklynCatalogFile.delete();
-            if (persistenceDir != null) Os.deleteRecursively(persistenceDir);
-        }
-    }
-
-    protected EntitySpec<BrooklynNode> newBrooklynNodeSpecForTest() {
-        // poor man's way to output which test is running
-        log.info("Creating entity spec for "+JavaClassNames.callerNiceClassAndMethod(1));
-        
-        return EntitySpec.create(BrooklynNode.class)
-                .configure(BrooklynNode.WEB_CONSOLE_BIND_ADDRESS, Networking.ANY_NIC)
-                .configure(BrooklynNode.ON_EXISTING_PROPERTIES_FILE, ExistingFileBehaviour.DO_NOT_USE);
-        
-        /* yaml equivalent, for testing:
-
-location: localhost
-services:
-- type: brooklyn.entity.brooklynnode.BrooklynNode
-  bindAddress: 127.0.0.1
-  onExistingProperties: do_not_use
-
-# some other options
-  enabledHttpProtocols: [ https ]
-  managementPassword: s3cr3t
-  brooklynLocalPropertiesContents: |
-    brooklyn.webconsole.security.https.required=true
-    brooklyn.webconsole.security.users=admin
-    brooklyn.webconsole.security.user.admin.password=s3cr3t
-    brooklyn.location.localhost.enabled=false
-
-         */
-    }
-
-    @Test(groups="Integration")
-    public void testCanStartAndStop() throws Exception {
-        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest());
-        app.start(locs);
-        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
-
-        EntityTestUtils.assertAttributeEqualsEventually(brooklynNode, BrooklynNode.SERVICE_UP, true);
-
-        brooklynNode.stop();
-        EntityTestUtils.assertAttributeEquals(brooklynNode, BrooklynNode.SERVICE_UP, false);
-    }
-
-    @Test(groups="Integration")
-    public void testSetsGlobalBrooklynPropertiesFromContents() throws Exception {
-        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
-                .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_REMOTE_PATH, pseudoBrooklynPropertiesFile.getAbsolutePath())
-                .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_CONTENTS, "abc=def"));
-        app.start(locs);
-        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
-
-        assertEquals(Files.readLines(pseudoBrooklynPropertiesFile, Charsets.UTF_8), ImmutableList.of("abc=def"));
-    }
-
-    @Test(groups="Integration")
-    public void testSetsLocalBrooklynPropertiesFromContents() throws Exception {
-        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
-                .configure(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_REMOTE_PATH, pseudoBrooklynPropertiesFile.getAbsolutePath())
-                .configure(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_CONTENTS, "abc=def"));
-        app.start(locs);
-        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
-
-        assertEquals(Files.readLines(pseudoBrooklynPropertiesFile, Charsets.UTF_8), ImmutableList.of("abc=def"));
-    }
-
-    @Test(groups="Integration")
-    public void testSetsBrooklynPropertiesFromUri() throws Exception {
-        File brooklynPropertiesSourceFile = File.createTempFile("brooklynnode-test", ".properties");
-        Files.write("abc=def", brooklynPropertiesSourceFile, Charsets.UTF_8);
-
-        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
-                .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_REMOTE_PATH, pseudoBrooklynPropertiesFile.getAbsolutePath())
-                .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_URI, brooklynPropertiesSourceFile.toURI().toString()));
-        app.start(locs);
-        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
-
-        assertEquals(Files.readLines(pseudoBrooklynPropertiesFile, Charsets.UTF_8), ImmutableList.of("abc=def"));
-    }
-
-    @Test(groups="Integration")
-    public void testSetsBrooklynCatalogFromContents() throws Exception {
-        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
-                .configure(BrooklynNode.BROOKLYN_CATALOG_REMOTE_PATH, pseudoBrooklynCatalogFile.getAbsolutePath())
-                .configure(BrooklynNode.BROOKLYN_CATALOG_CONTENTS, "<catalog/>"));
-        app.start(locs);
-        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
-
-        assertEquals(Files.readLines(pseudoBrooklynCatalogFile, Charsets.UTF_8), ImmutableList.of("<catalog/>"));
-    }
-
-    @Test(groups="Integration")
-    public void testSetsBrooklynCatalogFromUri() throws Exception {
-        File brooklynCatalogSourceFile = File.createTempFile("brooklynnode-test", ".catalog");
-        Files.write("abc=def", brooklynCatalogSourceFile, Charsets.UTF_8);
-
-        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
-                .configure(BrooklynNode.BROOKLYN_CATALOG_REMOTE_PATH, pseudoBrooklynCatalogFile.getAbsolutePath())
-                .configure(BrooklynNode.BROOKLYN_CATALOG_URI, brooklynCatalogSourceFile.toURI().toString()));
-        app.start(locs);
-        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
-
-        assertEquals(Files.readLines(pseudoBrooklynCatalogFile, Charsets.UTF_8), ImmutableList.of("abc=def"));
-    }
-
-    @Test(groups="Integration")
-    public void testCopiesResources() throws Exception {
-        File sourceFile = File.createTempFile("brooklynnode-test", ".properties");
-        Files.write("abc=def", sourceFile, Charsets.UTF_8);
-        File tempDir = Files.createTempDir();
-        File expectedFile = new File(tempDir, "myfile.txt");
-
-        try {
-            BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
-                    .configure(BrooklynNode.RUN_DIR, tempDir.getAbsolutePath())
-                    .configure(BrooklynNode.COPY_TO_RUNDIR, ImmutableMap.of(sourceFile.getAbsolutePath(), "${RUN}/myfile.txt")));
-            app.start(locs);
-            log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
-
-            assertEquals(Files.readLines(expectedFile, Charsets.UTF_8), ImmutableList.of("abc=def"));
-        } finally {
-            expectedFile.delete();
-            tempDir.delete();
-            sourceFile.delete();
-        }
-    }
-
-    @Test(groups="Integration")
-    public void testCopiesClasspathEntriesInConfigKey() throws Exception {
-        String content = "abc=def";
-        File classpathEntry1 = File.createTempFile("first", ".properties");
-        File classpathEntry2 = File.createTempFile("second", ".properties");
-        Files.write(content, classpathEntry1, Charsets.UTF_8);
-        Files.write(content, classpathEntry2, Charsets.UTF_8);
-        File tempDir = Files.createTempDir();
-        File expectedFile1 = new File(new File(tempDir, "lib"), classpathEntry1.getName());
-        File expectedFile2 = new File(new File(tempDir, "lib"), classpathEntry2.getName());
-
-        try {
-            BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
-                    .configure(BrooklynNode.RUN_DIR, tempDir.getAbsolutePath())
-                    .configure(BrooklynNode.CLASSPATH, ImmutableList.of(classpathEntry1.getAbsolutePath(), classpathEntry2.getAbsolutePath()))
-                    );
-            app.start(locs);
-            log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
-
-            assertEquals(Files.readLines(expectedFile1, Charsets.UTF_8), ImmutableList.of(content));
-            assertEquals(Files.readLines(expectedFile2, Charsets.UTF_8), ImmutableList.of(content));
-        } finally {
-            expectedFile1.delete();
-            expectedFile2.delete();
-            tempDir.delete();
-            classpathEntry1.delete();
-            classpathEntry2.delete();
-        }
-    }
-
-    @Test(groups="Integration")
-    public void testCopiesClasspathEntriesInBrooklynProperties() throws Exception {
-        String content = "abc=def";
-        File classpathEntry1 = File.createTempFile("first", ".properties");
-        File classpathEntry2 = File.createTempFile("second", ".properties");
-        Files.write(content, classpathEntry1, Charsets.UTF_8);
-        Files.write(content, classpathEntry2, Charsets.UTF_8);
-        File tempDir = Files.createTempDir();
-        File expectedFile1 = new File(new File(tempDir, "lib"), classpathEntry1.getName());
-        File expectedFile2 = new File(new File(tempDir, "lib"), classpathEntry2.getName());
-
-        try {
-            String propName = BrooklynNode.CLASSPATH.getName();
-            String propValue = classpathEntry1.toURI().toString() + "," + classpathEntry2.toURI().toString();
-            ((BrooklynProperties)app.getManagementContext().getConfig()).put(propName, propValue);
-    
-            BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
-                    .configure(BrooklynNode.RUN_DIR, tempDir.getAbsolutePath())
-                    );
-            app.start(locs);
-            log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
-
-            assertEquals(Files.readLines(expectedFile1, Charsets.UTF_8), ImmutableList.of(content));
-            assertEquals(Files.readLines(expectedFile2, Charsets.UTF_8), ImmutableList.of(content));
-        } finally {
-            expectedFile1.delete();
-            expectedFile2.delete();
-            tempDir.delete();
-            classpathEntry1.delete();
-            classpathEntry2.delete();
-        }
-    }
-    
-    // TODO test that the classpath set above is actually used
-
-    @Test(groups="Integration")
-    public void testSetsBrooklynWebConsolePort() throws Exception {
-        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
-                .configure(BrooklynNode.HTTP_PORT, PortRanges.fromString("45000+")));
-        app.start(locs);
-        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
-
-        Integer httpPort = brooklynNode.getAttribute(BrooklynNode.HTTP_PORT);
-        URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI);
-        assertTrue(httpPort >= 45000 && httpPort < 54100, "httpPort="+httpPort);
-        assertEquals((Integer)webConsoleUri.getPort(), httpPort);
-        HttpTestUtils.assertHttpStatusCodeEquals(webConsoleUri.toString(), 200, 401);
-    }
-
-    @Test(groups="Integration")
-    public void testStartsAppOnStartup() throws Exception {
-        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
-                .configure(BrooklynNode.APP, BasicApplicationImpl.class.getName()));
-        app.start(locs);
-        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
-
-        URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI);
-        waitForApps(webConsoleUri, 1);
-        String apps = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications");
-        List<String> appType = parseJsonList(apps, ImmutableList.of("spec", "type"), String.class);
-        assertEquals(appType, ImmutableList.of(BasicApplication.class.getName()));
-    }
-
-    protected static void waitForApps(String webConsoleUri) {
-        HttpTestUtils.assertHttpStatusCodeEquals(webConsoleUri+"/v1/applications", 200, 403);
-        HttpTestUtils.assertHttpStatusCodeEventuallyEquals(webConsoleUri+"/v1/applications", 200);
-    }
-
-    // TODO Should introduce startup stages and let the client select which stage it expects to be complete
-    protected void waitForApps(final URI webConsoleUri, final int num) {
-        waitForApps(webConsoleUri.toString());
-        
-        // e.g. [{"id":"UnBqPcqg","spec":{"name":"Application (UnBqPcqg)","type":"brooklyn.entity.basic.BasicApplication","locations":["pOL4NtiW"]},"status":"RUNNING","links":{"self":"/v1/applications/UnBqPcqg","entities":"/v1/applications/UnBqPcqg/entities"}}]
-        Asserts.succeedsEventually(new Runnable() {
-            @Override
-            public void run() {
-                //Wait all apps to become managed
-                String appsContent = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications");
-                List<String> appIds = parseJsonList(appsContent, ImmutableList.of("id"), String.class);
-                assertEquals(appIds.size(), num);
-                
-                // and then to start
-                List<String> statuses = parseJsonList(appsContent, ImmutableList.of("status"), String.class);
-                for (String status : statuses) {
-                    assertEquals(status, Lifecycle.RUNNING.toString().toUpperCase());
-                }
-            }});
-    }
-
-    @Test(groups="Integration")
-    public void testStartsAppViaEffector() throws Exception {
-        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest());
-        app.start(locs);
-        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
-        
-        // note there is also a test for this in DeployApplication
-        final URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI);
-        waitForApps(webConsoleUri.toString());
-
-        final String id = brooklynNode.invoke(BrooklynNode.DEPLOY_BLUEPRINT, ConfigBag.newInstance()
-            .configure(DeployBlueprintEffector.BLUEPRINT_TYPE, BasicApplication.class.getName())
-            .getAllConfig()).get();
-        
-        String apps = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications");
-        List<String> appType = parseJsonList(apps, ImmutableList.of("spec", "type"), String.class);
-        assertEquals(appType, ImmutableList.of(BasicApplication.class.getName()));
-        
-        HttpTestUtils.assertContentEventuallyMatches(
-            webConsoleUri.toString()+"/v1/applications/"+id+"/entities/"+id+"/sensors/service.state",
-            "\"?(running|RUNNING)\"?");
-    }
-    
-    @Test(groups="Integration")
-    public void testUsesLocation() throws Exception {
-        String brooklynPropertiesContents = 
-            "brooklyn.location.named.mynamedloc=localhost:(name=myname)\n"+
-                //force lat+long so test will work when offline
-                "brooklyn.location.named.mynamedloc.latitude=123\n"+ 
-                "brooklyn.location.named.mynamedloc.longitude=45.6\n";
-
-        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
-            .configure(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_CONTENTS, brooklynPropertiesContents)
-            .configure(BrooklynNode.APP, BasicApplicationImpl.class.getName())
-            .configure(BrooklynNode.LOCATIONS, "named:mynamedloc"));
-        app.start(locs);
-        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
-
-        URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI);
-        waitForApps(webConsoleUri, 1);
-
-        // Check that "mynamedloc" has been picked up from the brooklyn.properties
-        String locsContent = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/locations");
-        List<String> locNames = parseJsonList(locsContent, ImmutableList.of("name"), String.class);
-        assertTrue(locNames.contains("mynamedloc"), "locNames="+locNames);
-
-        // Find the id of the concrete location instance of the app
-        String appsContent = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications");
-        List<String[]> appLocationIds = parseJsonList(appsContent, ImmutableList.of("spec", "locations"), String[].class);
-        String appLocationId = Iterables.getOnlyElement(appLocationIds)[0];  // app.getManagementContext().getLocationRegistry()
-
-        // Check that the concrete location is of the required type
-        String locatedLocationsContent = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/locations/usage/LocatedLocations");
-        assertEquals(parseJson(locatedLocationsContent, ImmutableList.of(appLocationId, "name"), String.class), "myname");
-        assertEquals(parseJson(locatedLocationsContent, ImmutableList.of(appLocationId, "longitude"), Double.class), 45.6, 0.00001);
-    }
-
-    @Test(groups="Integration")
-    public void testAuthenticationAndHttps() throws Exception {
-        String adminPassword = "p4ssw0rd";
-        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
-            .configure(BrooklynNode.ENABLED_HTTP_PROTOCOLS, ImmutableList.of("https"))
-            .configure(BrooklynNode.MANAGEMENT_PASSWORD, adminPassword)
-            .configure(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_CONTENTS,
-                Strings.lines(
-                    "brooklyn.webconsole.security.https.required=true",
-                    "brooklyn.webconsole.security.users=admin",
-                    "brooklyn.webconsole.security.user.admin.password="+adminPassword,
-                    "brooklyn.location.localhost.enabled=false") )
-            );
-        app.start(locs);
-        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
-
-        URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI);
-        Assert.assertTrue(webConsoleUri.toString().startsWith("https://"), "web console not https: "+webConsoleUri);
-        Integer httpsPort = brooklynNode.getAttribute(BrooklynNode.HTTPS_PORT);
-        Assert.assertTrue(httpsPort!=null && httpsPort >= 8443 && httpsPort <= 8500);
-        Assert.assertTrue(webConsoleUri.toString().contains(""+httpsPort), "web console not using right https port ("+httpsPort+"): "+webConsoleUri);
-        HttpTestUtils.assertHttpStatusCodeEquals(webConsoleUri.toString(), 401);
-
-        HttpClient http = HttpTool.httpClientBuilder()
-            .trustAll()
-            .uri(webConsoleUri)
-            .laxRedirect(true)
-            .credentials(new UsernamePasswordCredentials("admin", adminPassword))
-            .build();
-        HttpToolResponse response = HttpTool.httpGet(http, webConsoleUri, MutableMap.<String,String>of());
-        Assert.assertEquals(response.getResponseCode(), 200);
-    }
-
-    @Test(groups="Integration")
-    public void testStopPlainThrowsException() throws Exception {
-        BrooklynNode brooklynNode = setUpBrooklynNodeWithApp();
-
-        // Not using annotation with `expectedExceptions = PropagatedRuntimeException.class` because want to 
-        // ensure exception comes from stop. On jenkins, was seeing setUpBrooklynNodeWithApp fail in 
-        // testStopAndKillAppsEffector; so can't tell if this method was really passing!
-        try {
-            brooklynNode.stop();
-            fail("Expected "+brooklynNode+" stop to fail, because has app");
-        } catch (Exception e) {
-            IllegalStateException ise = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
-            if (ise != null && ise.toString().contains("Can't stop instance with running applications")) {
-                // success
-            } else {
-                throw e;
-            }
-        } finally {
-            try {
-                brooklynNode.invoke(BrooklynNode.STOP_NODE_AND_KILL_APPS, ImmutableMap.of(StopNodeAndKillAppsEffector.TIMEOUT.getName(), Duration.THIRTY_SECONDS)).getUnchecked();
-            } catch (Exception e) {
-                log.warn("Error in stopNodeAndKillApps for "+brooklynNode+" (continuing)", e);
-            }
-        }
-    }
-
-    @Test(groups="Integration")
-    public void testStopAndKillAppsEffector() throws Exception {
-        createNodeAndExecStopEffector(BrooklynNode.STOP_NODE_AND_KILL_APPS);
-    }
-
-    @Test(groups="Integration")
-    public void testStopButLeaveAppsEffector() throws Exception {
-        createNodeAndExecStopEffector(BrooklynNode.STOP_NODE_BUT_LEAVE_APPS);
-    }
-    
-    @Test(groups="Integration")
-    public void testStopAndRestartProcess() throws Exception {
-        persistenceDir = Files.createTempDir();
-        BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()
-                .configure(BrooklynNode.EXTRA_LAUNCH_PARAMETERS, "--persist auto --persistenceDir "+persistenceDir.getAbsolutePath())
-                .configure(BrooklynNode.APP, BasicApplicationImpl.class.getName()));
-        app.start(locs);
-        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
-        File pidFile = new File(getDriver(brooklynNode).getPidFile());
-        URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI);
-
-        waitForApps(webConsoleUri, 1);
-
-        // Stop just the process; will not have unmanaged entity unless machine was being terminated 
-        brooklynNode.invoke(BrooklynNode.STOP, ImmutableMap.<String, Object>of(
-                BrooklynNode.StopSoftwareParameters.STOP_MACHINE_MODE.getName(), StopMode.NEVER,
-                BrooklynNode.StopSoftwareParameters.STOP_PROCESS_MODE.getName(), StopMode.ALWAYS)).getUnchecked();
-
-        assertTrue(Entities.isManaged(brooklynNode));
-        assertFalse(isPidRunning(pidFile), "pid in "+pidFile+" still running");
-        
-        // Clear the startup app so it's not started second time, in addition to the rebind state
-        // TODO remove this once the startup app is created only if no previous persistence state
-        brooklynNode.config().set(BrooklynNode.APP, (String)null);
-        ((EntityLocal)brooklynNode).setAttribute(BrooklynNode.APP, null);
-        
-        // Restart the process; expect persisted state to have been restored, so apps still known about
-        brooklynNode.invoke(BrooklynNode.RESTART, ImmutableMap.<String, Object>of(
-                BrooklynNode.RestartSoftwareParameters.RESTART_MACHINE.getName(), "false")).getUnchecked();
-
-        waitForApps(webConsoleUri.toString());
-        String apps = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications");
-        List<String> appType = parseJsonList(apps, ImmutableList.of("spec", "type"), String.class);
-        assertEquals(appType, ImmutableList.of(BasicApplication.class.getName()));
-    }
-
-    private void createNodeAndExecStopEffector(Effector<?> eff) throws Exception {
-        BrooklynNode brooklynNode = setUpBrooklynNodeWithApp();
-        File pidFile = new File(getDriver(brooklynNode).getPidFile());
-        assertTrue(isPidRunning(pidFile));
-        
-        brooklynNode.invoke(eff, Collections.<String, Object>emptyMap()).getUnchecked();
-
-        // Note can't use driver.isRunning to check shutdown; can't invoke scripts on an unmanaged entity
-        EntityTestUtils.assertAttributeEquals(brooklynNode, BrooklynNode.SERVICE_UP, false);
-        
-        // unmanaged if the machine is destroyed - ie false on localhost (this test by default), but true in the cloud 
-//        assertFalse(Entities.isManaged(brooklynNode));
-        
-        assertFalse(isPidRunning(pidFile), "pid in "+pidFile+" still running");
-    }
-
-    private boolean isPidRunning(File pidFile) throws Exception {
-        SshMachineLocation machine = loc.obtain();
-        try {
-            int result = machine.execScript("check-pid", ImmutableList.of(
-                    "test -f "+pidFile+" || exit 1",
-                    "ps -p `cat "+pidFile+"`"));
-            return result == 0;
-        } finally {
-            loc.release(machine);
-            Locations.unmanage(machine);
-        }
-    }
-    
-    private BrooklynNodeSshDriver getDriver(BrooklynNode brooklynNode) {
-        try {
-            EntityProxyImpl entityProxy = (EntityProxyImpl)Proxy.getInvocationHandler(brooklynNode);
-            Method getDriver = BrooklynNodeImpl.class.getMethod("getDriver");
-            return (BrooklynNodeSshDriver)entityProxy.invoke(brooklynNode, getDriver, new Object[]{});
-        } catch (Throwable e) {
-            throw Exceptions.propagate(e);
-        }
-    }
-
-    private BrooklynNode setUpBrooklynNodeWithApp() throws InterruptedException,
-            ExecutionException {
-        BrooklynNode brooklynNode = app.createAndManageChild(EntitySpec.create(BrooklynNode.class)
-                .configure(BrooklynNode.NO_WEB_CONSOLE_AUTHENTICATION, Boolean.TRUE));
-        app.start(locs);
-        log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod());
-
-        EntityTestUtils.assertAttributeEqualsEventually(brooklynNode, BrooklynNode.SERVICE_UP, true);
-
-        String baseUrl = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI).toString();
-        waitForApps(baseUrl);
-        
-        final String id = brooklynNode.invoke(BrooklynNode.DEPLOY_BLUEPRINT, ConfigBag.newInstance()
-                .configure(DeployBlueprintEffector.BLUEPRINT_TYPE, BasicApplication.class.getName())
-                .getAllConfig()).get();
-
-        String entityUrl = Urls.mergePaths(baseUrl, "v1/applications/", id, "entities", id);
-        
-        Entity mirror = brooklynNode.addChild(EntitySpec.create(BrooklynEntityMirror.class)
-                .configure(BrooklynEntityMirror.MIRRORED_ENTITY_URL, entityUrl)
-                .configure(BrooklynEntityMirror.MIRRORED_ENTITY_ID, id));
-        Entities.manage(mirror);
-
-        assertEquals(brooklynNode.getChildren().size(), 1);
-        return brooklynNode;
-    }
-
-    private <T> T parseJson(String json, List<String> elements, Class<T> clazz) {
-        Function<String, T> func = Functionals.chain(
-                JsonFunctions.asJson(),
-                JsonFunctions.walk(elements),
-                JsonFunctions.cast(clazz));
-        return func.apply(json);
-    }
-
-    private <T> List<T> parseJsonList(String json, List<String> elements, Class<T> clazz) {
-        Function<String, List<T>> func = Functionals.chain(
-                JsonFunctions.asJson(),
-                JsonFunctions.forEach(Functionals.chain(
-                        JsonFunctions.walk(elements),
-                        JsonFunctions.cast(clazz))));
-        return func.apply(json);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeTest.java b/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeTest.java
deleted file mode 100644
index 1745c38..0000000
--- a/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeTest.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
-import java.util.List;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.entity.drivers.downloads.DownloadResolver;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.collections.MutableSet;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableMap;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-
-public class BrooklynNodeTest {
-
-    // TODO Need test for copying/setting classpath
-    
-    private TestApplication app;
-    private SshMachineLocation loc;
-    
-    public static class SlowStopBrooklynNode extends BrooklynNodeImpl {
-        public SlowStopBrooklynNode() {}
-        
-        @Override
-        protected void postStop() {
-            super.postStop();
-            
-            //Make sure UnmanageTask will wait for the STOP effector to complete.
-            Time.sleep(Duration.FIVE_SECONDS);
-        }
-        
-    }
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        loc = new SshMachineLocation(MutableMap.of("address", "localhost"));
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-    }
-    
-    @Test
-    public void testGeneratesCorrectSnapshotDownload() throws Exception {
-        String version = "0.0.1-SNAPSHOT";
-        String expectedUrl = "https://repository.apache.org/service/local/artifact/maven/redirect?r=snapshots&g=org.apache.brooklyn&v="+version+"&a=brooklyn-dist&c=dist&e=tar.gz";
-        runTestGeneratesCorrectDownloadUrl(version, expectedUrl);
-    }
-    
-    @Test
-    public void testGeneratesCorrectReleaseDownload() throws Exception {
-        String version = "0.0.1";
-        String expectedUrl = "http://search.maven.org/remotecontent?filepath=org/apache/brooklyn/brooklyn-dist/"+version+"/brooklyn-dist-"+version+"-dist.tar.gz";
-        runTestGeneratesCorrectDownloadUrl(version, expectedUrl);
-    }
-    
-    private void runTestGeneratesCorrectDownloadUrl(String version, String expectedUrl) throws Exception {
-        // TODO Using BrooklynNodeImpl directly, because want to instantiate a BroolynNodeSshDriver.
-        //      Really want to make that easier to test, without going through "wrong" code path for creating entity.
-        BrooklynNodeImpl entity = new BrooklynNodeImpl();
-        entity.setConfig(BrooklynNode.SUGGESTED_VERSION, version);
-        entity.setParent(app);
-        Entities.manage(entity);
-        ConfigToAttributes.apply(entity);
-        BrooklynNodeSshDriver driver = new BrooklynNodeSshDriver(entity, loc);
-        
-        DownloadResolver resolver = Entities.newDownloader(driver);
-        List<String> urls = resolver.getTargets();
-        
-        System.out.println("urls="+urls);
-        assertTrue(urls.contains(expectedUrl), "urls="+urls);
-    }
-    
-    @Test(groups = "Integration")
-    public void testUnmanageOnStop() throws Exception {
-        final BrooklynNode node = app.addChild(EntitySpec.create(BrooklynNode.class).impl(SlowStopBrooklynNode.class));
-        Entities.manage(node);
-        assertTrue(Entities.isManaged(node), "Entity " + node + " must be managed.");
-        node.invoke(Startable.STOP, ImmutableMap.<String,Object>of()).asTask().getUnchecked();
-        //The UnmanageTask will unblock after the STOP effector completes, so we are competing with it here.
-        Asserts.succeedsEventually(new Runnable() {
-            @Override
-            public void run() {
-                assertFalse(Entities.isManaged(node));
-            }
-        });
-    }
-    
-
-    @Test
-    public void testCanStartSameNode() throws Exception {
-        // not very interesting as do not have REST when run in this project
-        // but test BrooklynNodeRestTest in downstream project does
-        BrooklynNode bn = app.createAndManageChild(EntitySpec.create(BrooklynNode.class, SameBrooklynNodeImpl.class));
-        bn.start(MutableSet.<Location>of());
-        
-        Assert.assertEquals(bn.getAttribute(Attributes.SERVICE_UP), (Boolean)true);
-        // no URI
-        Assert.assertNull(bn.getAttribute(BrooklynNode.WEB_CONSOLE_URI));
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/brooklynnode/CallbackEntityHttpClient.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/brooklynnode/CallbackEntityHttpClient.java b/software/base/src/test/java/brooklyn/entity/brooklynnode/CallbackEntityHttpClient.java
deleted file mode 100644
index 53712ab..0000000
--- a/software/base/src/test/java/brooklyn/entity/brooklynnode/CallbackEntityHttpClient.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.util.core.http.HttpToolResponse;
-import org.apache.brooklyn.util.core.http.HttpTool.HttpClientBuilder;
-import org.apache.http.HttpStatus;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpPost;
-
-import brooklyn.entity.brooklynnode.EntityHttpClient;
-
-import com.google.common.base.Function;
-import com.google.common.base.Predicate;
-
-public class CallbackEntityHttpClient implements EntityHttpClient {
-    public static class Request {
-        private Entity entity;
-        private String method;
-        private String path;
-        private Map<String, String> params;
-        public Request(Entity entity, String method, String path, Map<String, String> params) {
-            this.entity = entity;
-            this.method = method;
-            this.path = path;
-            this.params = params;
-        }
-        public Entity getEntity() {
-            return entity;
-        }
-        public String getMethod() {
-            return method;
-        }
-        public String getPath() {
-            return path;
-        }
-        public Map<String, String> getParams() {
-            return params;
-        }
-    }
-    private Function<Request, String> callback;
-    private Entity entity;
-
-    public CallbackEntityHttpClient(Entity entity, Function<Request, String> callback) {
-        this.entity = entity;
-        this.callback = callback;
-    }
-
-    @Override
-    public HttpClientBuilder getHttpClientForBrooklynNode() {
-        throw new IllegalStateException("Method call not expected");
-    }
-
-    @Override
-    public HttpToolResponse get(String path) {
-        String result = callback.apply(new Request(entity, HttpGet.METHOD_NAME, path, Collections.<String, String>emptyMap()));
-        return new HttpToolResponse(HttpStatus.SC_OK, null, result.getBytes(), 0, 0, 0);
-    }
-
-    @Override
-    public HttpToolResponse post(String path, Map<String, String> headers, byte[] body) {
-        throw new IllegalStateException("Method call not expected");
-    }
-
-    @Override
-    public HttpToolResponse post(String path, Map<String, String> headers, Map<String, String> formParams) {
-        String result = callback.apply(new Request(entity, HttpPost.METHOD_NAME, path, formParams));
-        return new HttpToolResponse(HttpStatus.SC_OK, Collections.<String, List<String>>emptyMap(), result.getBytes(), 0, 0, 0);
-    }
-    
-    @Override
-    public HttpToolResponse delete(String path, Map<String, String> headers) {
-        throw new IllegalStateException("Method call not expected");
-    }
-
-    @Override
-    public EntityHttpClient responseSuccess(Predicate<Integer> successPredicate) {
-        throw new IllegalStateException("Method call not expected");
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/brooklynnode/MockBrooklynNode.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/brooklynnode/MockBrooklynNode.java b/software/base/src/test/java/brooklyn/entity/brooklynnode/MockBrooklynNode.java
deleted file mode 100644
index 4a8cbb0..0000000
--- a/software/base/src/test/java/brooklyn/entity/brooklynnode/MockBrooklynNode.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import java.util.Collection;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.entity.core.AbstractEntity;
-import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
-
-import brooklyn.entity.brooklynnode.CallbackEntityHttpClient.Request;
-import brooklyn.entity.brooklynnode.effector.SetHighAvailabilityModeEffectorBody;
-import brooklyn.entity.brooklynnode.effector.SetHighAvailabilityPriorityEffectorBody;
-
-import com.google.common.base.Function;
-import com.google.common.reflect.TypeToken;
-
-public class MockBrooklynNode extends AbstractEntity implements BrooklynNode {
-    @SuppressWarnings("serial")
-    public static final ConfigKey<Function<Request, String>> HTTP_CLIENT_CALLBACK = ConfigKeys.newConfigKey(new TypeToken<Function<Request, String>>(){}, "httpClientCallback");
-    public static final AttributeSensor<Integer> HA_PRIORITY = new BasicAttributeSensor<Integer>(Integer.class, "priority");
-    
-    @Override
-    public void init() {
-        super.init();
-        getMutableEntityType().addEffector(SetHighAvailabilityPriorityEffectorBody.SET_HIGH_AVAILABILITY_PRIORITY);
-        getMutableEntityType().addEffector(SetHighAvailabilityModeEffectorBody.SET_HIGH_AVAILABILITY_MODE);
-        setAttribute(HA_PRIORITY, 0);
-    }
-
-    @Override
-    public EntityHttpClient http() {
-        return new CallbackEntityHttpClient(this, getConfig(HTTP_CLIENT_CALLBACK));
-    }
-
-    @Override
-    public void start(Collection<? extends Location> locations) {
-    }
-
-    @Override
-    public void stop() {
-    }
-
-    @Override
-    public void restart() {
-    }
-
-    @Override
-    public void populateServiceNotUpDiagnostics() {
-        // no-op
-    }    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/brooklynnode/SameBrooklynNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/brooklyn/entity/brooklynnode/SameBrooklynNodeImpl.java b/software/base/src/test/java/brooklyn/entity/brooklynnode/SameBrooklynNodeImpl.java
deleted file mode 100644
index dc35de0..0000000
--- a/software/base/src/test/java/brooklyn/entity/brooklynnode/SameBrooklynNodeImpl.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode;
-
-import java.net.URI;
-import java.util.Collection;
-
-import brooklyn.entity.brooklynnode.BrooklynNodeImpl.DeployBlueprintEffectorBody;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.entity.core.AbstractEntity;
-import org.apache.brooklyn.sensor.feed.http.HttpFeed;
-import org.apache.brooklyn.sensor.feed.http.HttpPollConfig;
-import org.apache.brooklyn.sensor.feed.http.HttpValueFunctions;
-
-/** Implementation of BrooklynNode which just presents the node where this is running, for convenience;
- * 
- *  start/stop/restart have no effect; 
- *  sensors are connected;
- *  deploy blueprint assumes that a REST endpoint is available */
-public class SameBrooklynNodeImpl extends AbstractEntity implements BrooklynNode {
-    
-    private HttpFeed httpFeed;
-
-    @Override
-    public void start(Collection<? extends Location> locations) {
-        connectSensors();
-    }
-
-    @Override
-    public void stop() {
-        disconnectSensors();
-    }
-
-    @Override
-    public void restart() {
-        return;
-    }
-
-    
-    @Override
-    public void init() {
-        super.init();
-        getMutableEntityType().addEffector(DeployBlueprintEffectorBody.DEPLOY_BLUEPRINT);
-    }
-    
-    protected void connectSensors() {
-        URI webConsoleUri = getManagementContext().getManagementNodeUri().orNull();
-        setAttribute(WEB_CONSOLE_URI, webConsoleUri);
-
-        if (webConsoleUri != null) {
-            httpFeed = HttpFeed.builder()
-                    .entity(this)
-                    .period(200)
-                    .baseUri(webConsoleUri)
-                    .credentialsIfNotNull(getConfig(MANAGEMENT_USER), getConfig(MANAGEMENT_PASSWORD))
-                    .poll(new HttpPollConfig<Boolean>(SERVICE_UP)
-                            .onSuccess(HttpValueFunctions.responseCodeEquals(200))
-                            .setOnFailureOrException(false))
-                    .build();
-
-        } else {
-            setAttribute(SERVICE_UP, true);
-        }
-    }
-    
-    protected void disconnectSensors() {
-        if (httpFeed != null) httpFeed.stop();
-    }
-
-    @Override
-    public EntityHttpClient http() {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
-    public void populateServiceNotUpDiagnostics() {
-        // no-op
-    }    
-}



[49/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/MultiLocationRebindTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/MultiLocationRebindTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/MultiLocationRebindTest.java
deleted file mode 100644
index 4728ab9..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/MultiLocationRebindTest.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.io.File;
-import java.util.List;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.location.cloud.AvailabilityZoneExtension;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.collections.MutableSet;
-import org.apache.brooklyn.util.net.Networking;
-import org.apache.brooklyn.util.os.Os;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Function;
-import com.google.common.base.Predicates;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-
-public class MultiLocationRebindTest {
-
-    private ClassLoader classLoader = getClass().getClassLoader();
-    private ManagementContext origManagementContext;
-    private ManagementContext newManagementContext;
-    private File mementoDir;
-    
-    private TestApplication origApp;
-    private TestApplication newApp;
-    private SshMachineLocation mac1a;
-    private SshMachineLocation mac2a;
-    private FixedListMachineProvisioningLocation<SshMachineLocation> loc1;
-    private FixedListMachineProvisioningLocation<SshMachineLocation> loc2;
-    private MultiLocation<SshMachineLocation> multiLoc;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        mementoDir = Os.newTempDir(getClass());
-        origManagementContext = RebindTestUtils.newPersistingManagementContext(mementoDir, classLoader, 1);
-        origApp = ApplicationBuilder.newManagedApp(EntitySpec.create(TestApplication.class), origManagementContext);
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (origManagementContext != null) Entities.destroyAll(origManagementContext);
-        if (newApp != null) Entities.destroyAll(newApp.getManagementContext());
-        if (newManagementContext != null) Entities.destroyAll(newManagementContext);
-        if (mementoDir != null) RebindTestUtils.deleteMementoDir(mementoDir);
-    }
-
-    @SuppressWarnings("unchecked")
-    @Test
-    public void testRebindsMultiLocation() throws Exception {
-        mac1a = origManagementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                .displayName("mac1a")
-                .configure("address", Networking.getInetAddressWithFixedName("1.1.1.1")));
-        mac2a = origManagementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                .displayName("mac2a")
-                .configure("address", Networking.getInetAddressWithFixedName("1.1.1.3")));
-        loc1 = origManagementContext.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
-                .displayName("loc1")
-                .configure("machines", MutableSet.of(mac1a)));
-        loc2 = origManagementContext.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
-                .displayName("loc2")
-                .configure("machines", MutableSet.of(mac2a)));
-        multiLoc = origManagementContext.getLocationManager().createLocation(LocationSpec.create(MultiLocation.class)
-                        .displayName("multiLoc")
-                        .configure("subLocations", ImmutableList.of(loc1, loc2)));
-        
-        newApp = rebind();
-        newManagementContext = newApp.getManagementContext();
-        
-        MultiLocation newMultiLoc = (MultiLocation) Iterables.find(newManagementContext.getLocationManager().getLocations(), Predicates.instanceOf(MultiLocation.class));
-        AvailabilityZoneExtension azExtension = newMultiLoc.getExtension(AvailabilityZoneExtension.class);
-        List<Location> newSublLocs = azExtension.getAllSubLocations();
-        Iterable<String> newSubLocNames = Iterables.transform(newSublLocs, new Function<Location, String>() {
-            @Override public String apply(Location input) {
-                return (input == null) ? null : input.getDisplayName();
-            }});
-        Asserts.assertEqualsIgnoringOrder(newSubLocNames, ImmutableList.of("loc1", "loc2"));
-    }
-    
-    private TestApplication rebind() throws Exception {
-        return rebind(true);
-    }
-    
-    private TestApplication rebind(boolean checkSerializable) throws Exception {
-        RebindTestUtils.waitForPersisted(origApp);
-        if (checkSerializable) {
-            RebindTestUtils.checkCurrentMementoSerializable(origApp);
-        }
-        return (TestApplication) RebindTestUtils.rebind(mementoDir, getClass().getClassLoader());
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/MultiLocationResolverTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/MultiLocationResolverTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/MultiLocationResolverTest.java
deleted file mode 100644
index ed20753..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/MultiLocationResolverTest.java
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
-
-import java.net.InetAddress;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.NoSuchElementException;
-
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.location.cloud.AvailabilityZoneExtension;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Objects;
-import com.google.common.base.Optional;
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-
-public class MultiLocationResolverTest {
-
-    private BrooklynProperties brooklynProperties;
-    private LocalManagementContext managementContext;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        managementContext = LocalManagementContextForTests.newInstance();
-        brooklynProperties = managementContext.getBrooklynProperties();
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (managementContext != null) Entities.destroyAll(managementContext);
-    }
-    
-    @Test
-    public void testThrowsOnInvalid() throws Exception {
-        assertThrowsNoSuchElement("wrongprefix:(hosts=\"1.1.1.1\")");
-        assertThrowsIllegalArgument("single");
-    }
-    
-    @Test
-    public void testThrowsOnInvalidTarget() throws Exception {
-        assertThrowsIllegalArgument("multi:()");
-        assertThrowsIllegalArgument("multi:(wrongprefix:(hosts=\"1.1.1.1\"))");
-        assertThrowsIllegalArgument("multi:(foo:bar)");
-    }
-
-    @Test
-    public void testCleansUpOnInvalidTarget() {
-        assertThrowsNoSuchElement("multi:(targets=\"localhost:(name=testCleansUpOnInvalidTarget),thisNamedLocationDoesNotExist\")");
-        Optional<Location> subtarget = Iterables.tryFind(managementContext.getLocationManager().getLocations(), LocationPredicates.displayNameEqualTo("testCleansUpOnInvalidTarget"));
-        assertFalse(subtarget.isPresent(), "subtarget="+subtarget);
-    }
-
-
-    @Test
-    public void testResolvesSubLocs() {
-        assertMultiLocation(resolve("multi:(targets=localhost)"), 1, ImmutableList.of(Predicates.instanceOf(LocalhostMachineProvisioningLocation.class)));
-        assertMultiLocation(resolve("multi:(targets=\"localhost,localhost\")"), 2, Collections.nCopies(2, Predicates.instanceOf(LocalhostMachineProvisioningLocation.class)));
-        assertMultiLocation(resolve("multi:(targets=\"localhost,localhost,localhost\")"), 3, Collections.nCopies(3, Predicates.instanceOf(LocalhostMachineProvisioningLocation.class)));
-        assertMultiLocation(resolve("multi:(targets=\"localhost:(name=mysubname)\")"), 1, ImmutableList.of(displayNameEqualTo("mysubname")));
-        assertMultiLocation(resolve("multi:(targets=byon:(hosts=\"1.1.1.1\"))"), 1, ImmutableList.of(Predicates.and(
-                Predicates.instanceOf(FixedListMachineProvisioningLocation.class),
-                new Predicate<MachineProvisioningLocation>() {
-                    @Override public boolean apply(MachineProvisioningLocation input) {
-                        SshMachineLocation machine;
-                        try {
-                            machine = (SshMachineLocation) input.obtain(ImmutableMap.of());
-                        } catch (NoMachinesAvailableException e) {
-                            throw Exceptions.propagate(e);
-                        }
-                        try {
-                            String addr = ((SshMachineLocation)machine).getAddress().getHostAddress();
-                            return addr != null && addr.equals("1.1.1.1");
-                        } finally {
-                            input.release(machine);
-                        }
-                    }
-                })));
-        assertMultiLocation(resolve("multi:(targets=\"byon:(hosts=1.1.1.1),byon:(hosts=1.1.1.2)\")"), 2, Collections.nCopies(2, Predicates.instanceOf(FixedListMachineProvisioningLocation.class)));
-    }
-
-    @Test
-    public void testResolvesName() {
-        MultiLocation<SshMachineLocation> multiLoc = resolve("multi:(name=myname,targets=localhost)");
-        assertEquals(multiLoc.getDisplayName(), "myname");
-    }
-    
-    @Test
-    public void testNamedByonLocation() throws Exception {
-        brooklynProperties.put("brooklyn.location.named.mynamed", "multi:(targets=byon:(hosts=\"1.1.1.1\"))");
-        
-        MultiLocation<SshMachineLocation> loc = resolve("named:mynamed");
-        assertEquals(loc.obtain(ImmutableMap.of()).getAddress(), InetAddress.getByName("1.1.1.1"));
-    }
-
-    @Test
-    public void testResolvesFromMap() throws NoMachinesAvailableException {
-        Location l = managementContext.getLocationRegistry().resolve("multi", MutableMap.of("targets", 
-            MutableList.of("localhost", MutableMap.of("byon", MutableMap.of("hosts", "127.0.0.127")))));
-        MultiLocation<?> ml = (MultiLocation<?>)l;
-        Iterator<MachineProvisioningLocation<?>> ci = ml.getSubLocations().iterator();
-        
-        l = ci.next();
-        Assert.assertTrue(l instanceof LocalhostMachineProvisioningLocation, "Expected localhost, got "+l);
-        
-        l = ci.next();
-        Assert.assertTrue(l instanceof FixedListMachineProvisioningLocation, "Expected fixed, got "+l);
-        MachineLocation sl = ((FixedListMachineProvisioningLocation<?>)l).obtain();
-        Assert.assertEquals(sl.getAddress().getHostAddress(), "127.0.0.127");
-        
-        Assert.assertFalse(ci.hasNext());
-    }
-
-
-    private void assertThrowsNoSuchElement(String val) {
-        try {
-            resolve(val);
-            fail();
-        } catch (NoSuchElementException e) {
-            // success
-        }
-    }
-    
-    private void assertThrowsIllegalArgument(String val) {
-        try {
-            resolve(val);
-            fail();
-        } catch (IllegalArgumentException e) {
-            // success
-        }
-    }
-    
-    @SuppressWarnings("unchecked")
-    private MultiLocation<SshMachineLocation> resolve(String val) {
-        return (MultiLocation<SshMachineLocation>) managementContext.getLocationRegistry().resolve(val);
-    }
-    
-    @SuppressWarnings("rawtypes")
-    private void assertMultiLocation(MultiLocation<?> multiLoc, int expectedSize, List<? extends Predicate> expectedSubLocationPredicates) {
-        AvailabilityZoneExtension zones = multiLoc.getExtension(AvailabilityZoneExtension.class);
-        List<Location> subLocs = zones.getAllSubLocations();
-        assertEquals(subLocs.size(), expectedSize, "zones="+subLocs);
-        for (int i = 0; i < subLocs.size(); i++) {
-            MachineProvisioningLocation subLoc = (MachineProvisioningLocation) subLocs.get(i);
-            assertTrue(expectedSubLocationPredicates.get(i).apply(subLoc), "index="+i+"; subLocs="+subLocs);
-        }
-    }
-    
-    public static <T> Predicate<Location> displayNameEqualTo(final T val) {
-        return new Predicate<Location>() {
-            @Override
-            public boolean apply(@Nullable Location input) {
-                return Objects.equal(input.getDisplayName(), val);
-            }
-        };
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/MultiLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/MultiLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/MultiLocationTest.java
deleted file mode 100644
index e5b3fda..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/MultiLocationTest.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertTrue;
-
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.collections.MutableSet;
-import org.apache.brooklyn.util.net.Networking;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.location.cloud.AvailabilityZoneExtension;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-public class MultiLocationTest {
-
-    private static final Logger log = LoggerFactory.getLogger(MultiLocationTest.class);
-    
-    private LocalManagementContext managementContext;
-    private SshMachineLocation mac1a;
-    private SshMachineLocation mac1b;
-    private SshMachineLocation mac2a;
-    private SshMachineLocation mac2b;
-    private FixedListMachineProvisioningLocation<SshMachineLocation> loc1;
-    private FixedListMachineProvisioningLocation<SshMachineLocation> loc2;
-    private MultiLocation<SshMachineLocation> multiLoc;
-    
-    @SuppressWarnings("unchecked")
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        managementContext = LocalManagementContextForTests.newInstance();
-        mac1a = managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                .displayName("mac1a")
-                .configure("address", Networking.getInetAddressWithFixedName("1.1.1.1")));
-        mac1b = managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                .displayName("mac1b")
-                .configure("address", Networking.getInetAddressWithFixedName("1.1.1.2")));
-        mac2a = managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                .displayName("mac2a")
-                .configure("address", Networking.getInetAddressWithFixedName("1.1.1.3")));
-        mac2b = managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                .displayName("mac2b")
-                .configure("address", Networking.getInetAddressWithFixedName("1.1.1.4")));
-        loc1 = managementContext.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
-                .displayName("loc1")
-                .configure("machines", MutableSet.of(mac1a, mac1b)));
-        loc2 = managementContext.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
-                .displayName("loc2")
-                .configure("machines", MutableSet.of(mac2a, mac2b)));
-        multiLoc = managementContext.getLocationManager().createLocation(LocationSpec.create(MultiLocation.class)
-                        .displayName("multiLoc")
-                        .configure("subLocations", ImmutableList.of(loc1, loc2)));
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (managementContext != null) Entities.destroyAll(managementContext);
-    }
-    
-    @Test
-    public void testHasAvailabilityZonesAsSubLocations() throws Exception {
-        multiLoc.hasExtension(AvailabilityZoneExtension.class);
-        AvailabilityZoneExtension extension = multiLoc.getExtension(AvailabilityZoneExtension.class);
-        Asserts.assertEqualsIgnoringOrder(extension.getAllSubLocations(), ImmutableList.of(loc1, loc2));
-        Asserts.assertEqualsIgnoringOrder(extension.getSubLocations(2), ImmutableList.of(loc1, loc2));
-        assertTrue(ImmutableList.of(loc1, loc2).containsAll(extension.getSubLocations(1)));
-    }
-    
-    @Test
-    public void testObtainAndReleaseDelegateToSubLocation() throws Exception {
-        SshMachineLocation obtained = multiLoc.obtain(ImmutableMap.of());
-        assertTrue(ImmutableList.of(mac1a, mac1b, mac2a, mac2b).contains(obtained));
-        multiLoc.release(obtained);
-    }
-    
-    @Test
-    public void testObtainsMovesThroughSubLocations() throws Exception {
-        Assert.assertEquals(multiLoc.obtain().getAddress().getHostAddress(), "1.1.1.1");
-        Assert.assertEquals(multiLoc.obtain().getAddress().getHostAddress(), "1.1.1.2");
-        Assert.assertEquals(multiLoc.obtain().getAddress().getHostAddress(), "1.1.1.3");
-        Assert.assertEquals(multiLoc.obtain().getAddress().getHostAddress(), "1.1.1.4");
-        try {
-            multiLoc.obtain();
-            Assert.fail();
-        } catch (NoMachinesAvailableException e) {
-            log.info("Error when no machines available across locations is: "+e);
-            Assert.assertTrue(e.toString().contains("loc1"), "Message should have referred to sub-location message: "+e);
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/PaasLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/PaasLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/PaasLocationTest.java
deleted file mode 100644
index 1322cc3..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/PaasLocationTest.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import org.apache.brooklyn.core.test.location.TestPaasLocation;
-import org.apache.brooklyn.location.paas.PaasLocation;
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-public class PaasLocationTest {
-
-    private PaasLocation location;
-    
-    @Test
-    public void testProviderName(){
-        location = new TestPaasLocation();
-        Assert.assertEquals(location.getPaasProviderName(), "TestPaas");
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/PortRangesTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/PortRangesTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/PortRangesTest.java
deleted file mode 100644
index f0c1f09..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/PortRangesTest.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-
-import java.util.Iterator;
-
-import org.testng.Assert;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.api.location.PortRange;
-import org.apache.brooklyn.util.core.flags.TypeCoercions;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-
-public class PortRangesTest {
-
-    @Test
-    public void testSingleRange() {
-        PortRange r = PortRanges.fromInteger(1234);
-        assertContents(r, 1234);
-    }
-
-    @Test
-    public void testFromCollection() {
-        PortRange r = PortRanges.fromCollection(ImmutableList.of(1234, 2345));
-        assertContents(r, 1234, 2345);
-    }
-
-    @Test
-    public void testFromString() {
-        PortRange r = PortRanges.fromString("80,8080,8000,8080-8099");
-        assertContents(r, 80, 8080, 8000, 
-                8080, 8081, 8082, 8083, 8084, 8085, 8086, 8087, 8088, 8089,
-                8090, 8091, 8092, 8093, 8094, 8095, 8096, 8097, 8098, 8099);
-    }
-
-    @Test
-    public void testFromStringWithSpaces() {
-        PortRange r = PortRanges.fromString(" 80 , 8080  , 8000 , 8080  - 8099 ");
-        assertContents(r, 80, 8080, 8000, 
-                8080, 8081, 8082, 8083, 8084, 8085, 8086, 8087, 8088, 8089,
-                8090, 8091, 8092, 8093, 8094, 8095, 8096, 8097, 8098, 8099);
-    }
-
-    @Test
-    public void testFromStringWithSpacesToString() {
-        PortRange r = PortRanges.fromString(" 80 , 8080  , 8000 , 8080  - 8099 ");
-        Assert.assertEquals(r.toString(), "80,8080,8000,8080-8099");
-    }
-    
-    @Test
-    public void testFromStringThrowsIllegalArgumentException() {
-        assertFromStringThrowsIllegalArgumentException("80-100000");
-        assertFromStringThrowsIllegalArgumentException("0-80");
-    }
-
-    @Test
-    public void testCoercion() {
-        PortRanges.init();
-        PortRange r = TypeCoercions.coerce("80", PortRange.class);
-        assertContents(r, 80);
-    }
-
-    @Test
-    public void testCoercionInt() {
-        PortRanges.init();
-        PortRange r = TypeCoercions.coerce(80, PortRange.class);
-        assertContents(r, 80);
-    }
-    
-    @Test
-    public void testLinearRangeOfSizeOne() throws Exception {
-        PortRanges.LinearPortRange range = new PortRanges.LinearPortRange(80, 80);
-        assertEquals(Lists.newArrayList(range), ImmutableList.of(80));
-    }
-
-    @Test
-    public void testLinearRangeCountingUpwards() throws Exception {
-        PortRanges.LinearPortRange range = new PortRanges.LinearPortRange(80, 81);
-        assertEquals(Lists.newArrayList(range), ImmutableList.of(80, 81));
-    }
-    
-    @Test
-    public void testLinearRangeCountingDownwards() throws Exception {
-        PortRanges.LinearPortRange range = new PortRanges.LinearPortRange(80, 79);
-        assertEquals(Lists.newArrayList(range), ImmutableList.of(80, 79));
-    }
-    
-    protected void assertFromStringThrowsIllegalArgumentException(String range) {
-        try {
-            PortRanges.fromString(range);
-            Assert.fail();
-        } catch (IllegalArgumentException e) {
-            // success
-        }
-    }
-
-    private static <T> void assertContents(Iterable<T> actual, T ...expected) {
-        Iterator<T> i = actual.iterator();
-        int c = 0;
-        while (i.hasNext()) {
-            if (expected.length<=c) {
-                Assert.fail("Iterable contained more than the "+c+" expected elements");
-            }
-            Assert.assertEquals(i.next(), expected[c++]);
-        }
-        if (expected.length>c) {
-            Assert.fail("Iterable contained only "+c+" elements, "+expected.length+" expected");
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/RecordingMachineLocationCustomizer.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/RecordingMachineLocationCustomizer.java b/core/src/test/java/org/apache/brooklyn/location/basic/RecordingMachineLocationCustomizer.java
deleted file mode 100644
index 53e261f..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/RecordingMachineLocationCustomizer.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.List;
-
-import com.google.common.base.Objects;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.MachineLocationCustomizer;
-
-public class RecordingMachineLocationCustomizer implements MachineLocationCustomizer {
-    public static class Call {
-        public final String methodName;
-        public final List<?> args;
-        
-        Call(String methodName, List<?> args) {
-            this.methodName = checkNotNull(methodName);
-            this.args = checkNotNull(args);
-        }
-        
-        @Override
-        public String toString() {
-            return methodName+args;
-        }
-        
-        @Override
-        public int hashCode() {
-            return Objects.hashCode(methodName, args);
-        }
-        
-        @Override
-        public boolean equals(Object other) {
-            return (other instanceof RecordingMachineLocationCustomizer.Call) && 
-                    methodName.equals(((RecordingMachineLocationCustomizer.Call)other).methodName) && 
-                    args.equals(((RecordingMachineLocationCustomizer.Call)other).args);
-        }
-    }
-    
-    public final List<RecordingMachineLocationCustomizer.Call> calls = Lists.newCopyOnWriteArrayList();
-    
-    @Override
-    public void customize(MachineLocation machine) {
-        calls.add(new Call("customize", ImmutableList.of(machine)));
-    }
-
-    @Override
-    public void preRelease(MachineLocation machine) {
-        calls.add(new Call("preRelease", ImmutableList.of(machine)));
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/SimulatedLocation.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/SimulatedLocation.java b/core/src/test/java/org/apache/brooklyn/location/basic/SimulatedLocation.java
deleted file mode 100644
index 1e2cd33..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/SimulatedLocation.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.net.InetAddress;
-import java.util.Collection;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.brooklyn.api.location.HardwareDetails;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineDetails;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.location.OsDetails;
-import org.apache.brooklyn.api.location.PortRange;
-import org.apache.brooklyn.api.location.PortSupplier;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.net.Networking;
-
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Sets;
-
-
-/** Location for use in dev/test, defining custom start/stop support, and/or tweaking the ports which are permitted to be available
- * (using setPermittedPorts(Iterable))
- */
-public class SimulatedLocation extends AbstractLocation implements MachineProvisioningLocation<MachineLocation>, MachineLocation, PortSupplier {
-
-    private static final long serialVersionUID = 1L;
-    
-    private static final InetAddress address;
-    static {
-        address = Networking.getLocalHost();
-    }
-
-    Iterable<Integer> permittedPorts = PortRanges.fromString("1+");
-    Set<Integer> usedPorts = Sets.newLinkedHashSet();
-
-    public SimulatedLocation() {
-        this(MutableMap.<String,Object>of());
-    }
-    public SimulatedLocation(Map<String,? extends Object> flags) {
-        super(flags);
-    }
-    
-    @Override
-    public SimulatedLocation newSubLocation(Map<?,?> newFlags) {
-        // TODO shouldn't have to copy config bag as it should be inherited (but currently it is not used inherited everywhere; just most places)
-        return getManagementContext().getLocationManager().createLocation(LocationSpec.create(getClass())
-                .parent(this)
-                .configure(config().getLocalBag().getAllConfig())  // FIXME Should this just be inherited?
-                .configure(newFlags));
-    }
-
-    public MachineLocation obtain(Map<?,?> flags) {
-        return this;
-    }
-
-    public void release(MachineLocation machine) {
-    }
-
-    public Map<String,Object> getProvisioningFlags(Collection<String> tags) {
-        return MutableMap.<String,Object>of();
-    }
-    
-    public InetAddress getAddress() {
-        return address;
-    }
-
-    @Override
-    public String getHostname() {
-        String hostname = address.getHostName();
-        return (hostname == null || hostname.equals(address.getHostAddress())) ? null : hostname;
-    }
-    
-    @Override
-    public Set<String> getPublicAddresses() {
-        return ImmutableSet.of(address.getHostAddress());
-    }
-    
-    @Override
-    public Set<String> getPrivateAddresses() {
-        return ImmutableSet.of();
-    }
-
-    public synchronized boolean obtainSpecificPort(int portNumber) {
-        if (!Iterables.contains(permittedPorts, portNumber)) return false;
-        if (usedPorts.contains(portNumber)) return false;
-        usedPorts.add(portNumber);
-        return true;
-    }
-
-    public synchronized int obtainPort(PortRange range) {
-        for (int p: range)
-            if (obtainSpecificPort(p)) return p;
-        return -1;
-    }
-
-    public synchronized void releasePort(int portNumber) {
-        usedPorts.remove(portNumber);
-    }
-    
-    public synchronized void setPermittedPorts(Iterable<Integer> ports) {
-        permittedPorts  = ports;
-    }
-
-    @Override
-    public OsDetails getOsDetails() {
-        return getMachineDetails().getOsDetails();
-    }
-
-    @Override
-    public MachineDetails getMachineDetails() {
-        HardwareDetails hardwareDetails = new BasicHardwareDetails(null, null);
-        OsDetails osDetails = BasicOsDetails.Factory.ANONYMOUS_LINUX;
-        return new BasicMachineDetails(hardwareDetails, osDetails);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/SingleMachineLocationResolverTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/SingleMachineLocationResolverTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/SingleMachineLocationResolverTest.java
deleted file mode 100644
index 6775352..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/SingleMachineLocationResolverTest.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.fail;
-
-import java.net.InetAddress;
-import java.util.Map;
-import java.util.NoSuchElementException;
-
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.core.Entities;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableMap;
-
-public class SingleMachineLocationResolverTest {
-
-    private BrooklynProperties brooklynProperties;
-    private LocalManagementContext managementContext;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        managementContext = LocalManagementContextForTests.newInstance();
-        brooklynProperties = managementContext.getBrooklynProperties();
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (managementContext != null) Entities.destroyAll(managementContext);
-    }
-    
-    @Test
-    public void testThrowsOnInvalid() throws Exception {
-        assertThrowsNoSuchElement("wrongprefix:(hosts=\"1.1.1.1\")");
-        assertThrowsIllegalArgument("single");
-    }
-    
-    @Test
-    public void testThrowsOnInvalidTarget() throws Exception {
-        assertThrowsIllegalArgument("single()");
-        assertThrowsIllegalArgument("single(wrongprefix:(hosts=\"1.1.1.1\"))");
-        assertThrowsIllegalArgument("single(foo:bar)");
-    }
-
-    @Test
-    public void resolveHosts() {
-        resolve("single(target=localhost)");
-        resolve("single(target=byon(hosts=\"1.1.1.1\"))");
-
-        brooklynProperties.put("brooklyn.location.named.mynamed", "single(target=byon:(hosts=\"1.1.1.1\"))");
-        managementContext.clearLocationRegistry();
-        resolve("single(target=named:mynamed)");
-    }
-    
-    @Test
-    public void resolveWithOldColonFormat() {
-        resolve("single:(target=localhost)");
-    }
-    
-    @Test
-    public void testNamedByonLocation() throws Exception {
-        brooklynProperties.put("brooklyn.location.named.mynamed", "single(target=byon:(hosts=\"1.1.1.1\"))");
-        
-        SingleMachineProvisioningLocation<SshMachineLocation> loc = resolve("named:mynamed");
-        assertEquals(loc.obtain(ImmutableMap.of()).getAddress(), InetAddress.getByName("1.1.1.1"));
-    }
-
-    @Test
-    public void testPropertyScopePrescedence() throws Exception {
-        brooklynProperties.put("brooklyn.location.named.mynamed", "single(target=byon:(hosts=\"1.1.1.1\"))");
-        
-        // prefer those in "named" over everything else
-        brooklynProperties.put("brooklyn.location.named.mynamed.privateKeyFile", "privateKeyFile-inNamed");
-        brooklynProperties.put("brooklyn.localhost.privateKeyFile", "privateKeyFile-inGeneric");
-
-        // prefer location-generic if nothing else
-        brooklynProperties.put("brooklyn.location.privateKeyData", "privateKeyData-inGeneric");
-
-        Map<String, Object> conf = resolve("named:mynamed").obtain(ImmutableMap.of()).config().getBag().getAllConfig();
-        
-        assertEquals(conf.get("privateKeyFile"), "privateKeyFile-inNamed");
-        assertEquals(conf.get("privateKeyData"), "privateKeyData-inGeneric");
-    }
-
-    private void assertThrowsNoSuchElement(String val) {
-        try {
-            resolve(val);
-            fail();
-        } catch (NoSuchElementException e) {
-            // success
-        }
-    }
-    
-    private void assertThrowsIllegalArgument(String val) {
-        try {
-            resolve(val);
-            fail();
-        } catch (IllegalArgumentException e) {
-            // success
-        }
-    }
-    
-    @SuppressWarnings("unchecked")
-    private SingleMachineProvisioningLocation<SshMachineLocation> resolve(String val) {
-        return (SingleMachineProvisioningLocation<SshMachineLocation>) managementContext.getLocationRegistry().resolve(val);
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/SingleMachineProvisioningLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/SingleMachineProvisioningLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/SingleMachineProvisioningLocationTest.java
deleted file mode 100644
index 77a0d3f..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/SingleMachineProvisioningLocationTest.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertNotNull;
-
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class SingleMachineProvisioningLocationTest {
-    
-    private static final Logger log = LoggerFactory.getLogger(SingleMachineProvisioningLocation.class);
-    
-    private LocalManagementContext managementContext;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        managementContext = LocalManagementContextForTests.newInstance();
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (managementContext != null) managementContext.terminate();
-    }
-    
-    @SuppressWarnings("unchecked") 
-    @Test
-    public void testLocalhostSingle() throws Exception {
-        SingleMachineProvisioningLocation<SshMachineLocation> l = (SingleMachineProvisioningLocation<SshMachineLocation>) 
-            managementContext.getLocationRegistry().resolve("single:(target='localhost')");
-        l.setManagementContext(managementContext);
-        
-        SshMachineLocation m1 = l.obtain();
-        
-        assertNotNull(m1);
-
-        log.info("GOT "+m1);
-        
-        l.release(m1);
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/SshMachineLocationIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/SshMachineLocationIntegrationTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/SshMachineLocationIntegrationTest.java
deleted file mode 100644
index af0ca0d..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/SshMachineLocationIntegrationTest.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.io.ByteArrayOutputStream;
-import java.security.KeyPair;
-import java.util.Arrays;
-import java.util.Map;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.crypto.SecureKeys;
-import org.apache.brooklyn.util.core.internal.ssh.SshTool;
-import org.apache.brooklyn.util.core.internal.ssh.sshj.SshjTool;
-import org.apache.brooklyn.util.core.internal.ssh.sshj.SshjTool.SshjToolBuilder;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Preconditions;
-
-import static org.testng.Assert.assertEquals;
-
-public class SshMachineLocationIntegrationTest {
-
-    protected TestApplication app;
-    protected ManagementContext mgmt;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setup() throws Exception {
-        mgmt = LocalManagementContextForTests.builder(true)
-            .useDefaultProperties()
-            .build();
-        app = TestApplication.Factory.newManagedInstanceForTests(mgmt);
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (mgmt != null) Entities.destroyAll(mgmt);
-        mgmt = null;
-    }
-
-    // Note: requires `named:localhost-passphrase` set up with a key whose passphrase is "localhost"
-    // * create the key with:
-    //      ssh-keygen -t rsa -N "brooklyn" -f ~/.ssh/id_rsa_passphrase
-    //      ssh-copy-id localhost
-    // * create brooklyn.properties, containing:
-    //      brooklyn.location.named.localhost-passphrase=localhost
-    //      brooklyn.location.named.localhost-passphrase.privateKeyFile=~/.ssh/id_rsa_passphrase
-    //      brooklyn.location.named.localhost-passphrase.privateKeyPassphrase=brooklyn
-    @Test(groups = "Integration")
-    public void testExtractingConnectablePassphraselessKey() throws Exception {
-        LocalhostMachineProvisioningLocation lhp = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("named:localhost-passphrase", true, null).orNull();
-        Preconditions.checkNotNull(lhp, "This test requires a localhost named location called 'localhost-passphrase' (which should have a passphrase set)");
-        SshMachineLocation sm = lhp.obtain();
-        
-        SshjToolBuilder builder = SshjTool.builder().host(sm.getAddress().getHostName()).user(sm.getUser());
-        
-        KeyPair data = sm.findKeyPair();
-        if (data!=null) builder.privateKeyData(SecureKeys.toPem(data));
-        String password = sm.findPassword();
-        if (password!=null) builder.password(password);
-        SshjTool tool = builder.build();
-        tool.connect();
-        ByteArrayOutputStream out = new ByteArrayOutputStream();
-        int result = tool.execCommands(MutableMap.<String,Object>of("out", out), Arrays.asList("date"));
-        Assert.assertTrue(out.toString().contains(" 20"), "out="+out);
-        assertEquals(result, 0);
-    }
-
-    @Test(groups = "Integration")
-    public void testExecScriptScriptDirFlagIsRespected() throws Exception {
-        // For explanation of (some of) the magic behind this command, see http://stackoverflow.com/a/229606/68898
-        final String command = "if [[ \"$0\" == \"/var/tmp/\"* ]]; then true; else false; fi";
-
-        LocalhostMachineProvisioningLocation lhp = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost", true, null).orNull();
-        SshMachineLocation sm = lhp.obtain();
-
-        Map<String, Object> props = ImmutableMap.<String, Object>builder()
-                .put(SshTool.PROP_SCRIPT_DIR.getName(), "/var/tmp")
-                .build();
-        int rc = sm.execScript(props, "Test script directory execution", ImmutableList.of(command));
-        assertEquals(rc, 0);
-    }
-
-    @Test(groups = "Integration")
-    public void testLocationScriptDirConfigIsRespected() throws Exception {
-        // For explanation of (some of) the magic behind this command, see http://stackoverflow.com/a/229606/68898
-        final String command = "if [[ \"$0\" == \"/var/tmp/\"* ]]; then true; else false; fi";
-
-        Map<String, Object> locationConfig = ImmutableMap.<String, Object>builder()
-                .put(SshMachineLocation.SCRIPT_DIR.getName(), "/var/tmp")
-                .build();
-
-        LocalhostMachineProvisioningLocation lhp = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost", locationConfig);
-        SshMachineLocation sm = lhp.obtain();
-
-        int rc = sm.execScript("Test script directory execution", ImmutableList.of(command));
-        assertEquals(rc, 0);
-    }
-    
-    @Test(groups = "Integration")
-    public void testMissingLocationScriptDirIsAlsoOkay() throws Exception {
-        final String command = "echo hello";
-
-        Map<String, Object> locationConfig = ImmutableMap.<String, Object>builder()
-//                .put(SshMachineLocation.SCRIPT_DIR.getName(), "/var/tmp")
-                .build();
-
-        LocalhostMachineProvisioningLocation lhp = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost", locationConfig);
-        SshMachineLocation sm = lhp.obtain();
-
-        int rc = sm.execScript("Test script directory execution", ImmutableList.of(command));
-        assertEquals(rc, 0);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/SshMachineLocationPerformanceTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/SshMachineLocationPerformanceTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/SshMachineLocationPerformanceTest.java
deleted file mode 100644
index cd254c9..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/SshMachineLocationPerformanceTest.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.io.ByteArrayOutputStream;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.brooklyn.test.PerformanceTestUtils;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.internal.ssh.SshTool;
-import org.apache.brooklyn.util.net.Networking;
-import org.apache.brooklyn.util.stream.Streams;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.apache.brooklyn.util.time.Time;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Stopwatch;
-import com.google.common.base.Throwables;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-
-/**
- * Test the performance of different variants of invoking the sshj tool.
- * 
- * Intended for human-invocation and inspection, to see which parts are most expensive.
- */
-public class SshMachineLocationPerformanceTest {
-
-    private static final Logger LOG = LoggerFactory.getLogger(SshMachineLocationPerformanceTest.class);
-    
-    private SshMachineLocation machine;
-    private ListeningExecutorService executor;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        machine = new SshMachineLocation(MutableMap.of("address", "localhost"));
-        executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void afterMethod() throws Exception {
-        if (executor != null) executor.shutdownNow();
-        Streams.closeQuietly(machine);
-    }
-
-    @Test(groups = {"Integration"})
-    public void testConsecutiveSmallCommands() throws Exception {
-        runExecManyCommands(ImmutableList.of("true"), "small-cmd", 10);
-    }
-
-    // Mimics SshSensorAdapter's polling
-    @Test(groups = {"Integration"})
-    public void testConsecutiveSmallCommandsWithCustomStdoutAndErr() throws Exception {
-        final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
-        final ByteArrayOutputStream stderr = new ByteArrayOutputStream();
-        
-        Runnable task = new Runnable() {
-            @Override public void run() {
-                machine.execScript(ImmutableMap.of("out", stdout, "err", stderr), "test", ImmutableList.of("true"));
-            }};
-        runMany(task, "small-cmd-custom-stdout", 1, 10);
-    }
-
-    @Test(groups = {"Integration"})
-    public void testConcurrentSmallCommands() throws Exception {
-        runExecManyCommands(ImmutableList.of("true"), "small-cmd", 10, 10);
-    }
-
-    @Test(groups = {"Integration"})
-    public void testConsecutiveBigStdoutCommands() throws Exception {
-        runExecManyCommands(ImmutableList.of("head -c 100000 /dev/urandom"), "big-stdout", 10);
-    }
-
-    @Test(groups = {"Integration"})
-    public void testConsecutiveBigStdinCommands() throws Exception {
-        String bigstr = Identifiers.makeRandomId(100000);
-        runExecManyCommands(ImmutableList.of("echo "+bigstr+" | wc -c"), "big-stdin", 10);
-    }
-
-    @Test(groups = {"Integration"})
-    public void testConsecutiveSmallCommandsWithDifferentProperties() throws Exception {
-        final Map<String, ?> emptyProperties = Collections.emptyMap();
-        final Map<String, ?> customProperties = MutableMap.of(
-                "address", Networking.getLocalHost(),
-                SshTool.PROP_SESSION_TIMEOUT.getName(), 20000,
-                SshTool.PROP_CONNECT_TIMEOUT.getName(), 50000,
-                SshTool.PROP_SCRIPT_HEADER.getName(), "#!/bin/bash");
-
-        Runnable task = new Runnable() {
-            @Override public void run() {
-                if (Math.random() < 0.5) {
-                    machine.execScript(emptyProperties, "test", ImmutableList.of("true"));
-                } else {
-                    machine.execScript(customProperties, "test", ImmutableList.of("true"));
-                }
-            }};
-        runMany(task, "small-cmd-custom-ssh-properties", 1, 10);
-    }
-
-    private void runExecManyCommands(final List<String> cmds, String context, int iterations) throws Exception {
-        runExecManyCommands(cmds, context, 1, iterations);
-    }
-    
-    private void runExecManyCommands(final List<String> cmds, String context, int concurrentRuns, int iterations) throws Exception {
-        Runnable task = new Runnable() {
-                @Override public void run() {
-                    execScript(cmds);
-                }};
-        runMany(task, context, concurrentRuns, iterations);
-    }
-    
-    private void runMany(final Runnable task, final String context, int concurrentRuns, int iterations) throws Exception {
-        long preCpuTime = PerformanceTestUtils.getProcessCpuTime();
-        Stopwatch stopwatch = Stopwatch.createStarted();
-
-        for (int i = 0; i < iterations; i++) {
-            List<ListenableFuture<?>> futures = Lists.newArrayList();
-            for (int j = 0; j < concurrentRuns; j++) {
-                futures.add(executor.submit(new Runnable() {
-                    public void run() {
-                        try {
-                            task.run();
-                        } catch (Exception e) {
-                            LOG.error("Error for "+context+", executing "+task, e);
-                            throw Throwables.propagate(e);
-                        }
-                    }}));
-            }
-            Futures.allAsList(futures).get();
-            
-            long postCpuTime = PerformanceTestUtils.getProcessCpuTime();
-            long elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
-            double fractionCpu = (elapsedTime > 0) ? ((double)postCpuTime-preCpuTime) / TimeUnit.MILLISECONDS.toNanos(elapsedTime) : -1;
-            LOG.info("Executing {}; completed {}; took {}; fraction cpu {}",
-                    new Object[] {context, (i+1), Time.makeTimeStringRounded(elapsedTime), fractionCpu});
-        }
-    }
-
-    private int execScript(List<String> cmds) {
-        return machine.execScript("mysummary", cmds);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/SshMachineLocationReuseIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/SshMachineLocationReuseIntegrationTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/SshMachineLocationReuseIntegrationTest.java
deleted file mode 100644
index 2b1d8e1..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/SshMachineLocationReuseIntegrationTest.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.internal.ssh.SshTool;
-import org.apache.brooklyn.util.core.internal.ssh.sshj.SshjTool;
-import org.apache.brooklyn.util.net.Networking;
-import org.apache.brooklyn.util.stream.Streams;
-import org.apache.brooklyn.util.time.Duration;
-
-import com.google.common.collect.ImmutableList;
-
-/**
- * Tests the re-use of SshTools in SshMachineLocation
- */
-public class SshMachineLocationReuseIntegrationTest {
-
-    public static class RecordingSshjTool extends SshjTool {
-        public static final AtomicBoolean forbidden = new AtomicBoolean(false); 
-        public static final AtomicInteger connectionCount = new AtomicInteger(0);
-        public static final AtomicInteger disconnectionCount = new AtomicInteger();
-        
-        public RecordingSshjTool(Map<String, ?> map) {
-            super(map);
-        }
-
-        @Override
-        public void connect() {
-            if (forbidden.get()) throw new IllegalStateException("forbidden at this time");
-            connectionCount.incrementAndGet();
-            super.connect();
-        }
-
-        @Override
-        public void disconnect() {
-            disconnectionCount.incrementAndGet();
-            super.disconnect();
-        }
-
-        public static void reset() {
-            forbidden.set(false);
-            connectionCount.set(0);
-            disconnectionCount.set(0);
-        }
-
-        @Override
-        public int execCommands(Map<String, ?> props, List<String> commands, Map<String, ?> env) {
-            if (forbidden.get()) throw new IllegalStateException("forbidden at this time");
-            return super.execCommands(props, commands, env);
-        }
-        
-        @Override
-        public int execScript(Map<String, ?> props, List<String> commands, Map<String, ?> env) {
-            if (forbidden.get()) throw new IllegalStateException("forbidden at this time");
-            return super.execScript(props, commands, env);
-        }
-        
-        @Override
-        public int execShellDirect(Map<String, ?> props, List<String> commands, Map<String, ?> env) {
-            if (forbidden.get()) throw new IllegalStateException("forbidden at this time");
-            return super.execShellDirect(props, commands, env);
-        }
-    }
-
-    private SshMachineLocation host;
-    private LocalManagementContext managementContext;
-
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        managementContext = new LocalManagementContext();
-        host = managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                .configure("address", Networking.getLocalHost())
-                .configure(SshTool.PROP_TOOL_CLASS, RecordingSshjTool.class.getName()));
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (host != null) Streams.closeQuietly(host);
-        if (managementContext != null) Entities.destroyAll(managementContext);
-        RecordingSshjTool.reset();
-    }
-
-    @Test(groups = "Integration")
-    public void testBasicReuse() throws Exception {
-        host.execScript("mysummary", ImmutableList.of("exit"));
-        host.execScript("mysummary", ImmutableList.of("exit"));
-        assertEquals(RecordingSshjTool.connectionCount.get(), 1, "Expected one SSH connection to have been recorded");
-    }
-
-    @Test(groups = "Integration")
-    public void testReuseWithInterestingProps() throws Exception {
-        host.execScript(customSshConfigKeys(), "mysummary", ImmutableList.of("exit"));
-        host.execScript(customSshConfigKeys(), "mysummary", ImmutableList.of("exit"));
-        assertEquals(RecordingSshjTool.connectionCount.get(), 1, "Expected one SSH connection to have been recorded");
-    }
-
-    @Test(groups = "Integration")
-    public void testNewConnectionForDifferentProps() throws Exception {
-        host.execScript("mysummary", ImmutableList.of("exit"));
-        host.execScript(customSshConfigKeys(), "mysummary", ImmutableList.of("exit"));
-        assertEquals(RecordingSshjTool.connectionCount.get(), 2, "Expected two SSH connections to have been recorded");
-    }
-
-    @Test(groups = "Integration")
-    public void testSshToolReusedWhenConfigDiffers() throws Exception {
-        Map<String, Object> props = customSshConfigKeys();
-        host.execScript(props, "mysummary", ImmutableList.of("exit"));
-
-        // Use another output stream for second request
-        props.put(SshTool.PROP_SCRIPT_HEADER.getName(), "#!/bin/bash -e\n");
-        host.execScript(props, "mysummary", ImmutableList.of("exit"));
-        assertEquals(RecordingSshjTool.connectionCount.get(), 1, "Expected one SSH connection to have been recorded even though out script header differed.");
-    }
-
-    @Test(groups = "Integration")
-    public void testSshCacheExpiresEvenIfNotUsed() throws Exception {
-        SshMachineLocation host2 = managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                .configure("address", InetAddress.getLocalHost())
-                .configure(SshMachineLocation.SSH_CACHE_EXPIRY_DURATION, Duration.ONE_SECOND)
-                .configure(SshTool.PROP_TOOL_CLASS, RecordingSshjTool.class.getName()));
-        
-        Map<String, Object> props = customSshConfigKeys();
-        host2.execScript(props, "mysummary", ImmutableList.of("exit"));
-
-        Asserts.succeedsEventually(new Runnable() {
-            @Override public void run() {
-                assertEquals(RecordingSshjTool.disconnectionCount.get(), 1);
-            }});
-    }
-
-    public Map<String, Object> customSshConfigKeys() throws UnknownHostException {
-        return MutableMap.<String, Object>of(
-                "address", Networking.getLocalHost(),
-                SshTool.PROP_SESSION_TIMEOUT.getName(), 20000,
-                SshTool.PROP_CONNECT_TIMEOUT.getName(), 50000,
-                SshTool.PROP_SCRIPT_HEADER.getName(), "#!/bin/bash");
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/basic/SshMachineLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/basic/SshMachineLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/basic/SshMachineLocationTest.java
deleted file mode 100644
index bbc0a7f..0000000
--- a/core/src/test/java/org/apache/brooklyn/location/basic/SshMachineLocationTest.java
+++ /dev/null
@@ -1,339 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertNull;
-import static org.testng.Assert.assertSame;
-import static org.testng.Assert.assertTrue;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.OutputStream;
-import java.net.InetAddress;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.entity.EntityInitializer;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineDetails;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.PortRange;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.effector.core.EffectorBody;
-import org.apache.brooklyn.effector.core.EffectorTaskTest;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.apache.brooklyn.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.file.ArchiveUtils;
-import org.apache.brooklyn.util.core.internal.ssh.RecordingSshTool;
-import org.apache.brooklyn.util.core.internal.ssh.SshException;
-import org.apache.brooklyn.util.core.internal.ssh.SshTool;
-import org.apache.brooklyn.util.core.task.BasicExecutionContext;
-import org.apache.brooklyn.util.core.task.BasicExecutionManager;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.net.Networking;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.stream.Streams;
-import org.apache.brooklyn.util.time.Duration;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Charsets;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.io.Files;
-
-/**
- * Test the {@link SshMachineLocation} implementation of the {@link Location} interface.
- */
-public class SshMachineLocationTest {
-
-    private SshMachineLocation host;
-    private ManagementContext mgmt;
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        mgmt = LocalManagementContextForTests.newInstance();
-        host = new SshMachineLocation(MutableMap.of("address", Networking.getLocalHost()));
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (host != null) Streams.closeQuietly(host);
-        if (mgmt != null) Entities.destroyAll(mgmt);
-    }
-    
-    @Test(groups = "Integration")
-    public void testGetMachineDetails() throws Exception {
-        BasicExecutionManager execManager = new BasicExecutionManager("mycontextid");
-        BasicExecutionContext execContext = new BasicExecutionContext(execManager);
-        try {
-            MachineDetails details = execContext.submit(new Callable<MachineDetails>() {
-                public MachineDetails call() {
-                    return host.getMachineDetails();
-                }}).get();
-            assertNotNull(details);
-        } finally {
-            execManager.shutdownNow();
-        }
-    }
-    
-    @Test
-    public void testSupplyingMachineDetails() throws Exception {
-        MachineDetails machineDetails = new BasicMachineDetails(new BasicHardwareDetails(1, 1024), new BasicOsDetails("myname", "myarch", "myversion"));
-        SshMachineLocation host2 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                .configure(SshMachineLocation.MACHINE_DETAILS, machineDetails));
-        
-        assertSame(host2.getMachineDetails(), machineDetails);
-    }
-    
-    @Test
-    public void testConfigurePrivateAddresses() throws Exception {
-        SshMachineLocation host2 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                .configure("address", Networking.getLocalHost())
-                .configure(SshMachineLocation.PRIVATE_ADDRESSES, ImmutableList.of("1.2.3.4"))
-                .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, true));
-
-        assertEquals(host2.getPrivateAddresses(), ImmutableSet.of("1.2.3.4"));
-    }
-    
-    // Wow, this is hard to test (until I accepted creating the entity + effector)! Code smell?
-    // Need to call getMachineDetails in a DynamicSequentialTask so that the "innessential" takes effect,
-    // to not fail its caller. But to get one of those outside of an effector is non-obvious.
-    @Test(groups = "Integration")
-    public void testGetMachineIsInessentialOnFailure() throws Exception {
-        SshMachineLocation host2 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
-                .configure("address", Networking.getLocalHost())
-                .configure(SshTool.PROP_TOOL_CLASS, FailingSshTool.class.getName()));
-
-        final Effector<MachineDetails> GET_MACHINE_DETAILS = Effectors.effector(MachineDetails.class, "getMachineDetails")
-                .impl(new EffectorBody<MachineDetails>() {
-                    public MachineDetails call(ConfigBag parameters) {
-                        Maybe<MachineLocation> machine = Machines.findUniqueMachineLocation(entity().getLocations());
-                        try {
-                            machine.get().getMachineDetails();
-                            throw new IllegalStateException("Expected failure in ssh");
-                        } catch (RuntimeException e) {
-                            return null;
-                        }
-                    }})
-                .build();
-
-        EntitySpec<TestApplication> appSpec = EntitySpec.create(TestApplication.class)
-                .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, true)
-                .addInitializer(new EntityInitializer() {
-                        public void apply(EntityLocal entity) {
-                            ((EntityInternal)entity).getMutableEntityType().addEffector(EffectorTaskTest.DOUBLE_1);
-                        }});
-
-        TestApplication app = ApplicationBuilder.newManagedApp(appSpec, mgmt);
-
-        app.start(ImmutableList.of(host2));
-        
-        MachineDetails details = app.invoke(GET_MACHINE_DETAILS, ImmutableMap.<String, Object>of()).get();
-        assertNull(details);
-    }
-    public static class FailingSshTool extends RecordingSshTool {
-        public FailingSshTool(Map<?, ?> props) {
-            super(props);
-        }
-        @Override public int execScript(Map<String, ?> props, List<String> commands, Map<String, ?> env) {
-            throw new RuntimeException("Simulating failure of ssh: cmds="+commands);
-        }
-        @Override public int execCommands(Map<String, ?> props, List<String> commands, Map<String, ?> env) {
-            throw new RuntimeException("Simulating failure of ssh: cmds="+commands);
-        }
-    }
-    
-    // Note: requires `ssh localhost` to be setup such that no password is required    
-    @Test(groups = "Integration")
-    public void testSshExecScript() throws Exception {
-        OutputStream outStream = new ByteArrayOutputStream();
-        String expectedName = Os.user();
-        host.execScript(MutableMap.of("out", outStream), "mysummary", ImmutableList.of("whoami; exit"));
-        String outString = outStream.toString();
-        
-        assertTrue(outString.contains(expectedName), outString);
-    }
-    
-    // Note: requires `ssh localhost` to be setup such that no password is required    
-    @Test(groups = "Integration")
-    public void testSshExecCommands() throws Exception {
-        OutputStream outStream = new ByteArrayOutputStream();
-        String expectedName = Os.user();
-        host.execCommands(MutableMap.of("out", outStream), "mysummary", ImmutableList.of("whoami; exit"));
-        String outString = outStream.toString();
-        
-        assertTrue(outString.contains(expectedName), outString);
-    }
-    
-    // For issue #230
-    @Test(groups = "Integration")
-    public void testOverridingPropertyOnExec() throws Exception {
-        SshMachineLocation host = new SshMachineLocation(MutableMap.of("address", Networking.getLocalHost(), "sshPrivateKeyData", "wrongdata"));
-        
-        OutputStream outStream = new ByteArrayOutputStream();
-        String expectedName = Os.user();
-        host.execCommands(MutableMap.of("sshPrivateKeyData", null, "out", outStream), "my summary", ImmutableList.of("whoami"));
-        String outString = outStream.toString();
-        
-        assertTrue(outString.contains(expectedName), "outString="+outString);
-    }
-
-    @Test(groups = "Integration", expectedExceptions={IllegalStateException.class, SshException.class})
-    public void testSshRunWithInvalidUserFails() throws Exception {
-        SshMachineLocation badHost = new SshMachineLocation(MutableMap.of("user", "doesnotexist", "address", Networking.getLocalHost()));
-        badHost.execScript("mysummary", ImmutableList.of("whoami; exit"));
-    }
-    
-    // Note: requires `ssh localhost` to be setup such that no password is required    
-    @Test(groups = "Integration")
-    public void testCopyFileTo() throws Exception {
-        File dest = Os.newTempFile(getClass(), ".dest.tmp");
-        File src = Os.newTempFile(getClass(), ".src.tmp");
-        try {
-            Files.write("abc", src, Charsets.UTF_8);
-            host.copyTo(src, dest);
-            assertEquals("abc", Files.readFirstLine(dest, Charsets.UTF_8));
-        } finally {
-            src.delete();
-            dest.delete();
-        }
-    }
-
-    // Note: requires `ssh localhost` to be setup such that no password is required    
-    @Test(groups = "Integration")
-    public void testCopyStreamTo() throws Exception {
-        String contents = "abc";
-        File dest = new File(Os.tmp(), "sssMachineLocationTest_dest.tmp");
-        try {
-            host.copyTo(Streams.newInputStreamWithContents(contents), dest.getAbsolutePath());
-            assertEquals("abc", Files.readFirstLine(dest, Charsets.UTF_8));
-        } finally {
-            dest.delete();
-        }
-    }
-
-    @Test(groups = "Integration")
-    public void testInstallUrlTo() throws Exception {
-        File dest = new File(Os.tmp(), "sssMachineLocationTest_dir/");
-        dest.mkdir();
-        try {
-            int result = host.installTo("https://raw.github.com/brooklyncentral/brooklyn/master/README.md", Urls.mergePaths(dest.getAbsolutePath(), "README.md"));
-            assertEquals(result, 0);
-            String contents = ArchiveUtils.readFullyString(new File(dest, "README.md"));
-            assertTrue(contents.contains("http://brooklyncentral.github.com"), "contents missing expected phrase; contains:\n"+contents);
-        } finally {
-            dest.delete();
-        }
-    }
-    
-    @Test(groups = "Integration")
-    public void testInstallClasspathCopyTo() throws Exception {
-        File dest = new File(Os.tmp(), "sssMachineLocationTest_dir/");
-        dest.mkdir();
-        try {
-            int result = host.installTo("classpath://brooklyn/config/sample.properties", Urls.mergePaths(dest.getAbsolutePath(), "sample.properties"));
-            assertEquals(result, 0);
-            String contents = ArchiveUtils.readFullyString(new File(dest, "sample.properties"));
-            assertTrue(contents.contains("Property 1"), "contents missing expected phrase; contains:\n"+contents);
-        } finally {
-            dest.delete();
-        }
-    }
-
-    // Note: requires `ssh localhost` to be setup such that no password is required    
-    @Test(groups = "Integration")
-    public void testIsSshableWhenTrue() throws Exception {
-        assertTrue(host.isSshable());
-    }
-    
-    // Note: on some (home/airport) networks, `ssh 123.123.123.123` hangs seemingly forever.
-    // Make sure we fail, waiting for longer than the 70 second TCP timeout.
-    //
-    // Times out in 2m7s on Ubuntu Vivid (syn retries set to 6)
-    @Test(groups = "Integration")
-    public void testIsSshableWhenFalse() throws Exception {
-        byte[] unreachableIp = new byte[] {123,123,123,123};
-        final SshMachineLocation unreachableHost = new SshMachineLocation(MutableMap.of("address", InetAddress.getByAddress("unreachablename", unreachableIp)));
-        Asserts.assertReturnsEventually(new Runnable() {
-            public void run() {
-                assertFalse(unreachableHost.isSshable());
-            }},
-            Duration.minutes(3));
-    }
-    
-    @Test
-    public void obtainSpecificPortGivesOutPortOnlyOnce() {
-        int port = 2345;
-        assertTrue(host.obtainSpecificPort(port));
-        assertFalse(host.obtainSpecificPort(port));
-        host.releasePort(port);
-        assertTrue(host.obtainSpecificPort(port));
-    }
-    
-    @Test
-    public void obtainPortInRangeGivesBackRequiredPortOnlyIfAvailable() {
-        int port = 2345;
-        assertEquals(host.obtainPort(new PortRanges.LinearPortRange(port, port)), port);
-        assertEquals(host.obtainPort(new PortRanges.LinearPortRange(port, port)), -1);
-        host.releasePort(port);
-        assertEquals(host.obtainPort(new PortRanges.LinearPortRange(port, port)), port);
-    }
-    
-    @Test
-    public void obtainPortInWideRange() {
-        int lowerPort = 2345;
-        int upperPort = 2350;
-        PortRange range = new PortRanges.LinearPortRange(lowerPort, upperPort);
-        for (int i = lowerPort; i <= upperPort; i++) {
-            assertEquals(host.obtainPort(range), i);
-        }
-        assertEquals(host.obtainPort(range), -1);
-        
-        host.releasePort(lowerPort);
-        assertEquals(host.obtainPort(range), lowerPort);
-        assertEquals(host.obtainPort(range), -1);
-    }
-    
-    @Test
-    public void testObtainPortDoesNotUsePreReservedPorts() {
-        host = new SshMachineLocation(MutableMap.of("address", Networking.getLocalHost(), "usedPorts", ImmutableSet.of(8000)));
-        assertEquals(host.obtainPort(PortRanges.fromString("8000")), -1);
-        assertEquals(host.obtainPort(PortRanges.fromString("8000+")), 8001);
-    }
-}


[09/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppTest.java
new file mode 100644
index 0000000..e4d30c3
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppTest.java
@@ -0,0 +1,352 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+
+import java.net.MalformedURLException;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.cert.Certificate;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import javax.management.remote.JMXConnector;
+import javax.management.remote.JMXConnectorFactory;
+import javax.management.remote.JMXServiceURL;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.sensor.SensorEvent;
+import org.apache.brooklyn.api.sensor.SensorEventListener;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.JavaAppUtils;
+import org.apache.brooklyn.entity.java.UsesJava;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.entity.java.VanillaJavaApp;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.sensor.feed.jmx.JmxHelper;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.ResourceUtils;
+import org.apache.brooklyn.util.core.crypto.FluentKeySigner;
+import org.apache.brooklyn.util.core.crypto.SecureKeys;
+import org.apache.brooklyn.util.crypto.SslTrustUtils;
+import org.apache.brooklyn.util.jmx.jmxmp.JmxmpAgent;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.basic.PortRanges;
+
+import com.google.common.base.Predicate;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Maps;
+
+public class VanillaJavaAppTest {
+
+    private static final Logger LOG = LoggerFactory.getLogger(VanillaJavaAppTest.class);
+    
+    private static final long TIMEOUT_MS = 10*1000;
+
+    // Static attributes such as number of processors and start time are only polled every 60 seconds
+    // so if they are not immediately available, it will be 60 seconds before they are polled again
+    private static final Object LONG_TIMEOUT_MS = 61*1000;
+
+    private static String BROOKLYN_THIS_CLASSPATH = null;
+    private static Class<?> MAIN_CLASS = ExampleVanillaMain.class;
+    private static Class<?> MAIN_CPU_HUNGRY_CLASS = ExampleVanillaMainCpuHungry.class;
+    
+    private TestApplication app;
+    private LocalhostMachineProvisioningLocation loc;
+
+    @BeforeMethod(alwaysRun = true)
+    public void setUp() throws Exception {
+        if (BROOKLYN_THIS_CLASSPATH==null) {
+            BROOKLYN_THIS_CLASSPATH = ResourceUtils.create(MAIN_CLASS).getClassLoaderDir();
+        }
+        app = TestApplication.Factory.newManagedInstanceForTests();
+        loc = app.newLocalhostProvisioningLocation(MutableMap.of("address", "localhost"));
+    }
+
+    @AfterMethod(alwaysRun = true)
+    public void tearDown() throws Exception {
+        if (app != null) Entities.destroyAll(app.getManagementContext());
+    }
+
+    @Test
+    public void testReadsConfigFromFlags() throws Exception {
+        final VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
+            .configure("main", "my.Main").configure("classpath", ImmutableList.of("c1", "c2"))
+            .configure("args", ImmutableList.of("a1", "a2")));
+
+        assertEquals(javaProcess.getMainClass(), "my.Main");
+        assertEquals(javaProcess.getClasspath(), ImmutableList.of("c1","c2"));
+        assertEquals(javaProcess.getConfig(VanillaJavaApp.ARGS), ImmutableList.of("a1", "a2"));
+    }
+
+    @Test(groups={"WIP", "Integration"})
+    public void testJavaSystemProperties() throws Exception {
+        final VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
+            .configure("main", "my.Main").configure("classpath", ImmutableList.of("c1", "c2"))
+            .configure("args", ImmutableList.of("a1", "a2")));
+        ((EntityLocal)javaProcess).setConfig(UsesJava.JAVA_SYSPROPS, ImmutableMap.of("fooKey", "fooValue", "barKey", "barValue"));
+        // TODO: how to test: launch standalone app that outputs system properties to stdout? Probe via JMX?
+    }
+
+    @Test(groups={"Integration"})
+    public void testStartsAndStops() throws Exception {
+        String main = MAIN_CLASS.getCanonicalName();
+        final VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
+            .configure("main", main).configure("classpath", ImmutableList.of(BROOKLYN_THIS_CLASSPATH))
+            .configure("args", ImmutableList.of()));
+        app.start(ImmutableList.of(loc));
+        assertEquals(javaProcess.getAttribute(VanillaJavaApp.SERVICE_STATE_ACTUAL), Lifecycle.RUNNING);
+
+        javaProcess.stop();
+        assertEquals(javaProcess.getAttribute(VanillaJavaApp.SERVICE_STATE_ACTUAL), Lifecycle.STOPPED);
+    }
+
+    @Test(groups={"Integration"})
+    public void testHasJvmMXBeanSensorVals() throws Exception {
+        String main = MAIN_CLASS.getCanonicalName();
+        final VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
+            .configure("main", main).configure("classpath", ImmutableList.of(BROOKLYN_THIS_CLASSPATH))
+            .configure("args", ImmutableList.of()));
+        app.start(ImmutableList.of(loc));
+        
+        // Memory MXBean
+        Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
+            public void run() {
+                assertNotNull(javaProcess.getAttribute(VanillaJavaApp.NON_HEAP_MEMORY_USAGE));
+                long init = javaProcess.getAttribute(VanillaJavaApp.INIT_HEAP_MEMORY);
+                long used = javaProcess.getAttribute(VanillaJavaApp.USED_HEAP_MEMORY);
+                long committed = javaProcess.getAttribute(VanillaJavaApp.COMMITTED_HEAP_MEMORY);
+                long max = javaProcess.getAttribute(VanillaJavaApp.MAX_HEAP_MEMORY);
+    
+                assertNotNull(used);
+                assertNotNull(init);
+                assertNotNull(committed);
+                assertNotNull(max);
+                assertTrue(init <= max, String.format("init %d > max %d heap memory", init, max));
+                assertTrue(used <= committed, String.format("used %d > committed %d heap memory", used, committed));
+                assertTrue(committed <= max, String.format("committed %d > max %d heap memory", committed, max));
+            }});
+        
+        // Threads MX Bean
+        Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
+            public void run() {
+                long current = javaProcess.getAttribute(VanillaJavaApp.CURRENT_THREAD_COUNT);
+                long peak = javaProcess.getAttribute(VanillaJavaApp.PEAK_THREAD_COUNT);
+    
+                assertNotNull(current);
+                assertNotNull(peak);
+                assertTrue(current <= peak, String.format("current %d > peak %d thread count", current, peak));
+            }});
+
+        // Runtime MX Bean
+        Asserts.succeedsEventually(MutableMap.of("timeout", LONG_TIMEOUT_MS), new Runnable() {
+            public void run() {
+                assertNotNull(javaProcess.getAttribute(VanillaJavaApp.START_TIME));
+                assertNotNull(javaProcess.getAttribute(VanillaJavaApp.UP_TIME));
+            }});
+        
+        // Operating System MX Bean
+        Asserts.succeedsEventually(MutableMap.of("timeout", LONG_TIMEOUT_MS), new Runnable() {
+            public void run() {
+                assertNotNull(javaProcess.getAttribute(VanillaJavaApp.PROCESS_CPU_TIME));
+                assertNotNull(javaProcess.getAttribute(VanillaJavaApp.SYSTEM_LOAD_AVERAGE));
+                assertNotNull(javaProcess.getAttribute(VanillaJavaApp.AVAILABLE_PROCESSORS));
+                assertNotNull(javaProcess.getAttribute(VanillaJavaApp.TOTAL_PHYSICAL_MEMORY_SIZE));
+                assertNotNull(javaProcess.getAttribute(VanillaJavaApp.FREE_PHYSICAL_MEMORY_SIZE));
+            }});
+        // TODO work on providing useful metrics from garbage collector MX Bean
+        // assertNotNull(javaProcess.getAttribute(VanillaJavaApp.GARBAGE_COLLECTION_TIME)) TODO: work on providing this
+    }
+    
+    @Test(groups={"Integration"})
+    public void testJvmMXBeanProcessCpuTimeGivesNonZeroPercentage() throws Exception {
+        String main = MAIN_CPU_HUNGRY_CLASS.getCanonicalName();
+        final VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
+            .configure("main", main).configure("classpath", ImmutableList.of(BROOKLYN_THIS_CLASSPATH))
+            .configure("args", ImmutableList.of()));
+        app.start(ImmutableList.of(loc));
+
+        JavaAppUtils.connectJavaAppServerPolicies((EntityLocal)javaProcess);
+        
+        final List<Double> fractions = new CopyOnWriteArrayList<Double>();
+        app.getManagementContext().getSubscriptionManager().subscribe(javaProcess, VanillaJavaApp.PROCESS_CPU_TIME_FRACTION_LAST, new SensorEventListener<Double>() {
+                public void onEvent(SensorEvent<Double> event) {
+                    fractions.add(event.getValue());
+                }});
+        
+        // Expect non-trivial load to be generated by the process.
+        // Expect load to be in the right order of magnitude (to ensure we haven't got a decimal point in the wrong place etc);
+        // But with multi-core could get big number; and on jenkins@releng3 we once saw [11.9, 0.6, 0.5]!
+        Asserts.succeedsEventually(new Runnable() {
+            public void run() {
+                Iterable<Double> nonTrivialFractions = Iterables.filter(fractions, new Predicate<Double>() {
+                        public boolean apply(Double input) {
+                            return input > 0.01;
+                        }});
+                assertTrue(Iterables.size(nonTrivialFractions) > 3, "fractions="+fractions); 
+            }});
+
+        Iterable<Double> tooBigFractions = Iterables.filter(fractions, new Predicate<Double>() {
+                public boolean apply(Double input) {
+                    return input > 50;
+                }});
+        assertTrue(Iterables.isEmpty(tooBigFractions), "fractions="+fractions); 
+        
+        Iterable<Double> ballparkRightFractions = Iterables.filter(fractions, new Predicate<Double>() {
+                public boolean apply(Double input) {
+                    return input > 0.01 && input < 4;
+                }});
+        assertTrue(Iterables.size(ballparkRightFractions) >= (fractions.size() / 2), "fractions="+fractions);
+        
+        LOG.info("VanillaJavaApp->ExampleVanillaMainCpuHuntry: ProcessCpuTime fractions="+fractions);
+    }
+
+    @Test(groups={"Integration"})
+    public void testStartsWithJmxPortSpecifiedInConfig() throws Exception {
+        int port = 53405;
+        String main = MAIN_CLASS.getCanonicalName();
+        VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
+            .configure("main", main).configure("classpath", ImmutableList.of(BROOKLYN_THIS_CLASSPATH))
+            .configure("args", ImmutableList.of()));
+        ((EntityLocal)javaProcess).setConfig(UsesJmx.JMX_PORT, PortRanges.fromInteger(port));
+        app.start(ImmutableList.of(loc));
+
+        assertEquals(javaProcess.getAttribute(UsesJmx.JMX_PORT), (Integer)port);
+    }
+
+    // FIXME Way test was written requires JmxSensorAdapter; need to rewrite...  
+    @Test(groups={"Integration", "WIP"})
+    public void testStartsWithSecureJmxPortSpecifiedInConfig() throws Exception {
+        int port = 53406;
+        String main = MAIN_CLASS.getCanonicalName();
+        final VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
+            .configure("main", main).configure("classpath", ImmutableList.of(BROOKLYN_THIS_CLASSPATH))
+            .configure("args", ImmutableList.of()));
+        ((EntityLocal)javaProcess).setConfig(UsesJmx.JMX_PORT, PortRanges.fromInteger(port));
+        ((EntityLocal)javaProcess).setConfig(UsesJmx.JMX_SSL_ENABLED, true);
+        
+        app.start(ImmutableList.of(loc));
+        // will fail above if JMX can't connect, but also do some add'l checks
+        
+        assertEquals(javaProcess.getAttribute(UsesJmx.JMX_PORT), (Integer)port);
+
+        // good key+cert succeeds
+        new AsserterForJmxConnection(javaProcess)
+                .customizeSocketFactory(null, null)
+                .connect();
+        
+        // bad cert fails
+        Asserts.assertFails(new Callable<Void>() {
+            public Void call() throws Exception {
+                new AsserterForJmxConnection(javaProcess)
+                        .customizeSocketFactory(null, new FluentKeySigner("cheater").newCertificateFor("jmx-access-key", SecureKeys.newKeyPair()))
+                        .connect();
+                return null;
+            }});
+
+        // bad key fails
+        Asserts.assertFails(new Callable<Void>() {
+            public Void call() throws Exception {
+                new AsserterForJmxConnection(javaProcess)
+                        .customizeSocketFactory(SecureKeys.newKeyPair().getPrivate(), null)
+                        .connect();
+                return null;
+            }});
+        
+        // bad profile fails
+        Asserts.assertFails(new Callable<Void>() {
+            public Void call() throws Exception {
+                AsserterForJmxConnection asserter = new AsserterForJmxConnection(javaProcess);
+                asserter.putEnv("jmx.remote.profiles", JmxmpAgent.TLS_JMX_REMOTE_PROFILES);
+                asserter.customizeSocketFactory(SecureKeys.newKeyPair().getPrivate(), null)
+                        .connect();
+                return null;
+            }});
+    }
+
+    private static class AsserterForJmxConnection {
+        final VanillaJavaApp entity;
+        final JMXServiceURL url;
+        final Map<String,Object> env;
+        
+        @SuppressWarnings("unchecked")
+        public AsserterForJmxConnection(VanillaJavaApp e) throws MalformedURLException {
+            this.entity = e;
+            
+            JmxHelper jmxHelper = new JmxHelper((EntityLocal)entity);
+            this.url = new JMXServiceURL(jmxHelper.getUrl());
+            this.env = Maps.newLinkedHashMap(jmxHelper.getConnectionEnvVars());
+        }
+        
+        public JMXServiceURL getJmxUrl() throws MalformedURLException {
+            return url;
+        }
+        
+        public void putEnv(String key, Object val) {
+            env.put(key, val);
+        }
+        
+        public AsserterForJmxConnection customizeSocketFactory(PrivateKey customKey, Certificate customCert) throws Exception {
+            PrivateKey key = (customKey == null) ? entity.getConfig(UsesJmx.JMX_SSL_ACCESS_KEY) : customKey;
+            Certificate cert = (customCert == null) ? entity.getConfig(UsesJmx.JMX_SSL_ACCESS_CERT) : customCert;
+            
+            KeyStore ks = SecureKeys.newKeyStore();
+            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+            if (key!=null) {
+                ks.setKeyEntry("brooklyn-jmx-access", key, "".toCharArray(), new Certificate[] {cert});
+            }
+            kmf.init(ks, "".toCharArray());
+
+            TrustManager tms =
+            // TODO use root cert for trusting server
+            //trustStore!=null ? SecureKeys.getTrustManager(trustStore) :
+                SslTrustUtils.TRUST_ALL;
+
+            SSLContext ctx = SSLContext.getInstance("TLSv1");
+            ctx.init(kmf.getKeyManagers(), new TrustManager[] {tms}, null);
+            SSLSocketFactory ssf = ctx.getSocketFactory();
+            env.put(JmxmpAgent.TLS_SOCKET_FACTORY_PROPERTY, ssf);
+            
+            return this;
+        }
+        
+        public JMXConnector connect() throws Exception {
+            return JMXConnectorFactory.connect(getJmxUrl(), env);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/machine/MachineEntityEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/machine/MachineEntityEc2LiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/machine/MachineEntityEc2LiveTest.java
new file mode 100644
index 0000000..9c4e571
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/machine/MachineEntityEc2LiveTest.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.machine;
+
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
+import org.apache.brooklyn.entity.machine.MachineEntity;
+import org.apache.brooklyn.test.Asserts;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+
+public class MachineEntityEc2LiveTest extends AbstractEc2LiveTest {
+
+    @Override
+    protected void doTest(Location loc) throws Exception {
+        final MachineEntity server = app.createAndManageChild(EntitySpec.create(MachineEntity.class));
+        
+        app.start(ImmutableList.of(loc));
+        
+        Asserts.succeedsEventually(new Runnable() {
+            @Override public void run() {
+                assertNotNull(server.getAttribute(MachineEntity.UPTIME));
+                assertNotNull(server.getAttribute(MachineEntity.LOAD_AVERAGE));
+                assertNotNull(server.getAttribute(MachineEntity.CPU_USAGE));
+                assertNotNull(server.getAttribute(MachineEntity.FREE_MEMORY));
+                assertNotNull(server.getAttribute(MachineEntity.TOTAL_MEMORY));
+                assertNotNull(server.getAttribute(MachineEntity.USED_MEMORY));
+            }});
+        
+        String result = server.execCommand("MY_ENV=myval && echo start $MY_ENV");
+        assertTrue(result.contains("start myval"), "result="+result);
+    }
+    
+    @Test(enabled=false)
+    public void testDummy() {} // Convince testng IDE integration that this really does have test methods
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/machine/MachineEntityRebindTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/machine/MachineEntityRebindTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/machine/MachineEntityRebindTest.java
new file mode 100644
index 0000000..cda1309
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/machine/MachineEntityRebindTest.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.machine;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestFixtureWithApp;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+
+public class MachineEntityRebindTest extends RebindTestFixtureWithApp {
+
+    @Test(groups = "Integration")
+    public void testRebindToMachineEntity() throws Exception {
+        EmptySoftwareProcess machine = origApp.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class));
+        origApp.start(ImmutableList.of(origManagementContext.getLocationRegistry().resolve("localhost")));
+        EntityTestUtils.assertAttributeEqualsEventually(machine, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
+        rebind(false);
+        Entity machine2 = newManagementContext.getEntityManager().getEntity(machine.getId());
+        EntityTestUtils.assertAttributeEqualsEventually(machine2, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/AbstractServerPoolTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/AbstractServerPoolTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/AbstractServerPoolTest.java
new file mode 100644
index 0000000..c31e458
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/AbstractServerPoolTest.java
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.machine.pool;
+
+import static org.testng.Assert.fail;
+
+import java.util.List;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.apache.brooklyn.entity.machine.pool.ServerPool;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+public abstract class AbstractServerPoolTest {
+
+    // Note not extending BrooklynAppUnitTestSupport because sub-classes of this are for live and for unit tests.
+    // Instead, we have to repeat that logic for setting SKIP_ON_BOX_BASE_DIR_RESOLUTION
+    
+    private static final int DEFAULT_POOL_SIZE = 3;
+
+    protected Location location;
+    protected ManagementContext mgmt;
+    protected TestApplication poolApp;
+    protected ServerPool pool;
+    private List<TestApplication> createdApps = Lists.newLinkedList();
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        createdApps.clear();
+        mgmt = createManagementContext();
+        location = createLocation();
+        EntitySpec<TestApplication> appSpec = EntitySpec.create(TestApplication.class)
+                .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, shouldSkipOnBoxBaseDirResolution());
+        poolApp = ApplicationBuilder.newManagedApp(appSpec, mgmt);
+
+        pool = poolApp.createAndManageChild(EntitySpec.create(ServerPool.class)
+                .configure(ServerPool.INITIAL_SIZE, getInitialPoolSize())
+                .configure(ServerPool.MEMBER_SPEC, EntitySpec.create(EmptySoftwareProcess.class)));
+        poolApp.start(ImmutableList.of(location));
+        EntityTestUtils.assertAttributeEqualsEventually(pool, Attributes.SERVICE_UP, true);
+        assertAvailableCountEventuallyEquals(getInitialPoolSize());
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        // Kills the apps before terminating the pool
+        for (TestApplication app : createdApps) {
+            Entities.destroy(app);
+        }
+        if (mgmt != null) {
+            Entities.destroyAll(mgmt);
+            mgmt = null;
+        }
+    }
+
+    protected int getInitialPoolSize() {
+        return DEFAULT_POOL_SIZE;
+    }
+
+    protected ManagementContext createManagementContext() {
+        return new LocalManagementContextForTests();
+    }
+    
+    protected boolean shouldSkipOnBoxBaseDirResolution() {
+        return true;
+    }
+
+    /** @return Creates a LocalhostMachineProvisioningLocation */
+    protected Location createLocation() {
+        return mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class));
+    }
+
+    protected void assertNoMachinesAvailableForApp(TestApplication app) {
+        try {
+            app.start(ImmutableList.of(pool.getDynamicLocation()));
+            fail("Expected exception when starting app with too many entities for pool");
+        } catch (Exception e) {
+            Throwable t = Exceptions.getFirstThrowableOfType(e, NoMachinesAvailableException.class);
+            if (t == null) {
+                throw new RuntimeException(e);
+            }
+        }
+    }
+
+    protected void assertAvailableCountEventuallyEquals(int count) {
+        assertAvailableCountEventuallyEquals(pool, count);
+    }
+
+    protected void assertAvailableCountEventuallyEquals(ServerPool pool, int count) {
+        EntityTestUtils.assertAttributeEqualsEventually(pool, ServerPool.AVAILABLE_COUNT, count);
+    }
+
+    protected void assertClaimedCountEventuallyEquals(int count) {
+        assertClaimedCountEventuallyEquals(pool, count);
+    }
+
+    protected void assertClaimedCountEventuallyEquals(ServerPool pool, Integer count) {
+        EntityTestUtils.assertAttributeEqualsEventually(pool, ServerPool.CLAIMED_COUNT, count);
+    }
+
+    protected TestApplication createAppWithChildren(int numChildren) {
+        if (numChildren < 0) fail("Invalid number of children for app: " + numChildren);
+        EntitySpec<TestApplication> appSpec = EntitySpec.create(TestApplication.class)
+                .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, shouldSkipOnBoxBaseDirResolution());
+        TestApplication app = ApplicationBuilder.newManagedApp(appSpec, mgmt);
+        while (numChildren-- > 0) {
+            app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class));
+        }
+        createdApps.add(app);
+        return app;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLiveTest.java
new file mode 100644
index 0000000..c1e1f18
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLiveTest.java
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.machine.pool;
+
+import static org.testng.Assert.assertTrue;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.testng.annotations.Test;
+
+import com.google.common.base.CaseFormat;
+import com.google.common.collect.ImmutableList;
+
+public class ServerPoolLiveTest extends AbstractServerPoolTest {
+
+    public static final String PROVIDER = "softlayer";
+
+    protected BrooklynProperties brooklynProperties;
+
+    @Override
+    protected Location createLocation() {
+        // Image: {id=CENTOS_6_64, providerId=CENTOS_6_64, os={family=centos, version=6.5, description=CentOS / CentOS / 6.5-64 LAMP for Bare Metal, is64Bit=true}, description=CENTOS_6_64, status=AVAILABLE, loginUser=root}
+        Map<String, ?> allFlags = MutableMap.<String, Object>builder()
+                .put("provider", PROVIDER)
+                .put("tags", ImmutableList.of(getClass().getName()))
+                .put("vmNameMaxLength", 30)
+                .put("imageId", "CENTOS_6_64")
+                .build();
+        return mgmt.getLocationRegistry().resolve(PROVIDER, allFlags);
+    }
+
+    @Override
+    protected ManagementContext createManagementContext() {
+        String[] propsToRemove = new String[]{"imageId", "imageDescriptionRegex", "imageNameRegex", "inboundPorts", "hardwareId", "minRam"};
+
+        // Don't let any defaults from brooklyn.properties (except credentials) interfere with test
+        brooklynProperties = BrooklynProperties.Factory.newDefault();
+        for (String propToRemove : propsToRemove) {
+            for (String propVariant : ImmutableList.of(propToRemove, CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propToRemove))) {
+                brooklynProperties.remove("brooklyn.locations.jclouds." + PROVIDER + "." + propVariant);
+                brooklynProperties.remove("brooklyn.locations." + propVariant);
+                brooklynProperties.remove("brooklyn.jclouds." + PROVIDER + "." + propVariant);
+                brooklynProperties.remove("brooklyn.jclouds." + propVariant);
+            }
+        }
+
+        // Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can cause "stdin: is not a tty")
+        brooklynProperties.remove("brooklyn.ssh.config.scriptHeader");
+        return new LocalManagementContextForTests(brooklynProperties);
+    }
+
+    protected boolean shouldSkipOnBoxBaseDirResolution() {
+        return false;
+    }
+
+    @Override
+    protected int getInitialPoolSize() {
+        return 1;
+    }
+
+    @Test(groups = "Live")
+    public void testAppCanBeDeployedToPool() {
+        TestApplication app = createAppWithChildren(1);
+        app.start(ImmutableList.of(pool.getDynamicLocation()));
+        assertTrue(app.getAttribute(Attributes.SERVICE_UP));
+        for (Entity child : app.getChildren()) {
+            assertTrue(child.getAttribute(Attributes.SERVICE_UP));
+        }
+        TestApplication app2 = createAppWithChildren(1);
+        assertNoMachinesAvailableForApp(app2);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolverTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolverTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolverTest.java
new file mode 100644
index 0000000..fb3974b
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolLocationResolverTest.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.machine.pool;
+
+import static org.testng.Assert.assertEquals;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.apache.brooklyn.entity.machine.pool.ServerPool;
+import org.apache.brooklyn.entity.machine.pool.ServerPoolLocation;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.dynamic.DynamicLocation;
+
+public class ServerPoolLocationResolverTest {
+
+    private LocalManagementContext managementContext;
+    private Entity locationOwner;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        managementContext = new LocalManagementContextForTests(BrooklynProperties.Factory.newEmpty());
+        TestApplication t = ApplicationBuilder.newManagedApp(TestApplication.class, managementContext);
+        locationOwner = t.createAndManageChild(EntitySpec.create(ServerPool.class)
+                .configure(ServerPool.INITIAL_SIZE, 0)
+                .configure(ServerPool.MEMBER_SPEC, EntitySpec.create(EmptySoftwareProcess.class)));
+        Location poolLocation = managementContext.getLocationManager()
+                .createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class));
+        t.start(ImmutableList.of(poolLocation));
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (managementContext != null) Entities.destroyAll(managementContext);
+    }
+
+    @Test
+    public void testResolve() {
+        ServerPoolLocation location = resolve("pool:" + locationOwner.getId());
+        assertEquals(location.getOwner().getId(), locationOwner.getId());
+    }
+
+    @Test
+    public void testSetsDisplayName() {
+        ServerPoolLocation location = resolve("pool:" + locationOwner.getId() + ":(displayName=xyz)");
+        assertEquals(location.getDisplayName(), "xyz");
+    }
+
+    private ServerPoolLocation resolve(String val) {
+        Map<String, Object> flags = MutableMap.<String, Object>of(DynamicLocation.OWNER.getName(), locationOwner);
+        Location l = managementContext.getLocationRegistry().resolve(val, flags);
+        Assert.assertNotNull(l);
+        return (ServerPoolLocation) l;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolRebindTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolRebindTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolRebindTest.java
new file mode 100644
index 0000000..2de22bb
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolRebindTest.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.machine.pool;
+
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+
+import java.io.File;
+import java.util.Collection;
+
+import org.apache.brooklyn.api.entity.Application;
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.mgmt.rebind.RebindOptions;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.machine.pool.ServerPool;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Predicates;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.io.Files;
+
+public class ServerPoolRebindTest extends AbstractServerPoolTest {
+
+    private static final Logger LOG = LoggerFactory.getLogger(ServerPoolRebindTest.class);
+    private ClassLoader classLoader = getClass().getClassLoader();
+    private File mementoDir;
+
+    @Override
+    protected ManagementContext createManagementContext() {
+        mementoDir = Files.createTempDir();
+        return RebindTestUtils.newPersistingManagementContext(mementoDir, classLoader);
+    }
+
+    @Override
+    @AfterMethod(alwaysRun = true)
+    public void tearDown() throws Exception {
+        super.tearDown();
+        if (mementoDir != null) RebindTestUtils.deleteMementoDir(mementoDir);
+    }
+
+    private Collection<Application> rebind(TestApplication app) throws Exception {
+        LOG.info("Rebind start");
+        RebindTestUtils.waitForPersisted(app);
+        ((LocalManagementContext) app.getManagementContext()).terminate();
+        Collection<Application> r = RebindTestUtils.rebindAll(RebindOptions.create().mementoDir(mementoDir).classLoader(classLoader));
+        LOG.info("Rebind complete");
+        return r;
+    }
+
+    @Test(enabled = false)
+    public void testRebindingToPool() throws Exception {
+        TestApplication app = createAppWithChildren(1);
+        app.start(ImmutableList.of(pool.getDynamicLocation()));
+        assertTrue(app.getAttribute(Attributes.SERVICE_UP));
+        assertAvailableCountEventuallyEquals(pool, getInitialPoolSize() - 1);
+        assertClaimedCountEventuallyEquals(pool, 1);
+
+        Collection<Application> reboundApps = rebind(poolApp);
+        ServerPool reboundPool = null;
+        for (Application reboundApp : reboundApps) {
+            Optional<Entity> np = Iterables.tryFind(reboundApp.getChildren(), Predicates.instanceOf(ServerPool.class));
+            if (np.isPresent()) {
+                mgmt = reboundApp.getManagementContext();
+                reboundPool = (ServerPool) np.get();
+                break;
+            }
+        }
+
+        assertNotNull(reboundPool, "No app in rebound context has " + ServerPool.class.getName() +
+                " child. Apps: " + reboundApps);
+        assertNotNull(reboundPool.getDynamicLocation());
+        assertTrue(reboundPool.getAttribute(Attributes.SERVICE_UP));
+        assertAvailableCountEventuallyEquals(reboundPool, getInitialPoolSize() - 1);
+        assertClaimedCountEventuallyEquals(reboundPool, 1);
+
+        TestApplication app2 = createAppWithChildren(1);
+        app2.start(ImmutableList.of(reboundPool.getDynamicLocation()));
+        assertTrue(app2.getAttribute(Attributes.SERVICE_UP));
+        assertAvailableCountEventuallyEquals(reboundPool, getInitialPoolSize() - 2);
+        assertClaimedCountEventuallyEquals(reboundPool, 2);
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolTest.java
new file mode 100644
index 0000000..9d9b3a2
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/machine/pool/ServerPoolTest.java
@@ -0,0 +1,175 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.machine.pool;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
+import java.util.Collection;
+import java.util.Iterator;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.machine.pool.ServerPoolImpl;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine;
+
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+
+public class ServerPoolTest extends AbstractServerPoolTest {
+
+    private static final Logger LOG = LoggerFactory.getLogger(ServerPoolTest.class);
+
+    @Test
+    public void testAppCanBeDeployedToServerPool() {
+        TestApplication app = createAppWithChildren(1);
+        app.start(ImmutableList.of(pool.getDynamicLocation()));
+        assertTrue(app.getAttribute(Attributes.SERVICE_UP));
+        for (Entity child : app.getChildren()) {
+            assertTrue(child.getAttribute(Attributes.SERVICE_UP));
+        }
+    }
+
+    @Test
+    public void testFailureWhenNotEnoughServersAvailable() {
+        TestApplication app = createAppWithChildren(getInitialPoolSize() + 1);
+        assertNoMachinesAvailableForApp(app);
+        EntityTestUtils.assertAttributeEqualsEventually(app, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);
+    }
+
+    @Test
+    public void testDeployReleaseDeploy() {
+        TestApplication app = createAppWithChildren(getInitialPoolSize());
+        TestApplication app2 = createAppWithChildren(1);
+
+        app.start(ImmutableList.of(pool.getDynamicLocation()));
+        EntityTestUtils.assertAttributeEqualsEventually(app, Attributes.SERVICE_UP, true);
+        assertAvailableCountEventuallyEquals(0);
+        assertNoMachinesAvailableForApp(app2);
+
+        app.stop();
+        assertFalse(app.getAttribute(Attributes.SERVICE_UP));
+        assertAvailableCountEventuallyEquals(getInitialPoolSize());
+
+        app2.start(ImmutableList.of(pool.getDynamicLocation()));
+        EntityTestUtils.assertAttributeEqualsEventually(app2, Attributes.SERVICE_UP, true);
+        
+        assertAvailableCountEventuallyEquals(getInitialPoolSize() - 1);
+        assertClaimedCountEventuallyEquals(1);
+    }
+
+    @Test
+    public void testResizingPoolUp() {
+        TestApplication app = createAppWithChildren(getInitialPoolSize());
+        app.start(ImmutableList.of(pool.getDynamicLocation()));
+        assertTrue(app.getAttribute(Attributes.SERVICE_UP));
+
+        TestApplication app2 = createAppWithChildren(1);
+        assertNoMachinesAvailableForApp(app2);
+
+        pool.resizeByDelta(1);
+        
+        assertAvailableCountEventuallyEquals(1);
+
+        assertEquals((int) pool.getCurrentSize(), getInitialPoolSize() + 1);
+        app2.start(ImmutableList.of(pool.getDynamicLocation()));
+        assertTrue(app2.getAttribute(Attributes.SERVICE_UP));
+    }
+
+    @Test
+    public void testResizePoolDownSucceedsWhenEnoughMachinesAreFree() {
+        TestApplication app = createAppWithChildren(1);
+        app.start(ImmutableList.of(pool.getDynamicLocation()));
+        assertAvailableCountEventuallyEquals(getInitialPoolSize() - 1);
+
+        pool.resize(1);
+
+        assertAvailableCountEventuallyEquals(0);
+    }
+
+    @Test
+    public void testResizeDownDoesNotReleaseClaimedMachines() {
+        TestApplication app = createAppWithChildren(getInitialPoolSize() - 1);
+        app.start(ImmutableList.of(pool.getDynamicLocation()));
+        assertAvailableCountEventuallyEquals(1);
+        assertClaimedCountEventuallyEquals(getInitialPoolSize() - 1);
+
+        LOG.info("Test attempting to resize to 0 members. Should only drop the one available machine.");
+        pool.resize(0);
+
+        assertAvailableCountEventuallyEquals(0);
+        assertEquals(Iterables.size(pool.getMembers()), getInitialPoolSize() - 1);
+        assertAvailableCountEventuallyEquals(0);
+        assertClaimedCountEventuallyEquals(getInitialPoolSize() - 1);
+    }
+
+    @Test
+    public void testCanAddExistingMachinesToPool() {
+        TestApplication app = createAppWithChildren(getInitialPoolSize());
+        app.start(ImmutableList.of(pool.getDynamicLocation()));
+        assertAvailableCountEventuallyEquals(0);
+
+        LocalhostMachine loc = mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachine.class));
+        Entity added = pool.addExistingMachine(loc);
+        assertFalse(added.getConfig(ServerPoolImpl.REMOVABLE));
+        assertAvailableCountEventuallyEquals(1);
+
+        TestApplication app2 = createAppWithChildren(1);
+        app2.start(ImmutableList.of(pool.getDynamicLocation()));
+        assertAvailableCountEventuallyEquals(0);
+    }
+
+    @Test
+    public void testExistingMachinesAreNotRemovedFromThePoolOnShrinkButAreOnStop() {
+        LocalhostMachine loc = mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachine.class));
+        pool.addExistingMachine(loc);
+        assertAvailableCountEventuallyEquals(getInitialPoolSize() + 1);
+        pool.resize(0);
+        assertAvailableCountEventuallyEquals(1);
+        pool.stop();
+        assertAvailableCountEventuallyEquals(0);
+    }
+
+    @Test
+    public void testAddExistingMachineFromSpec() {
+        TestApplication app = createAppWithChildren(getInitialPoolSize());
+        app.start(ImmutableList.of(pool.getDynamicLocation()));
+        assertAvailableCountEventuallyEquals(0);
+
+        Collection<Entity> added = pool.addExistingMachinesFromSpec("byon:(hosts=\"localhost,localhost\")");
+        assertEquals(added.size(), 2, "Added: " + Joiner.on(", ").join(added));
+        Iterator<Entity> it = added.iterator();
+        assertFalse(it.next().getConfig(ServerPoolImpl.REMOVABLE));
+        assertFalse(it.next().getConfig(ServerPoolImpl.REMOVABLE));
+        assertAvailableCountEventuallyEquals(2);
+
+        TestApplication app2 = createAppWithChildren(2);
+        app2.start(ImmutableList.of(pool.getDynamicLocation()));
+        assertAvailableCountEventuallyEquals(0);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/AbstractDockerLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/AbstractDockerLiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/AbstractDockerLiveTest.java
new file mode 100644
index 0000000..7a9fd6d
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/AbstractDockerLiveTest.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import com.google.common.base.CaseFormat;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Runs a test with many different distros and versions.
+ */
+public abstract class AbstractDockerLiveTest {
+    
+    public static final String PROVIDER = "docker";
+
+    protected BrooklynProperties brooklynProperties;
+    protected ManagementContext ctx;
+    
+    protected TestApplication app;
+    protected Location jcloudsLocation;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        List<String> propsToRemove = ImmutableList.of("imageDescriptionRegex", "imageNameRegex", "inboundPorts",
+                "hardwareId", "minRam");
+        
+     // Don't let any defaults from brooklyn.properties (except credentials) interfere with test
+        brooklynProperties = BrooklynProperties.Factory.newDefault();
+        for (String propToRemove : propsToRemove) {
+            for (String propVariant : ImmutableList.of(propToRemove, CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propToRemove))) {
+                brooklynProperties.remove("brooklyn.locations.jclouds."+PROVIDER+"."+propVariant);
+                brooklynProperties.remove("brooklyn.locations."+propVariant);
+                brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+"."+propVariant);
+                brooklynProperties.remove("brooklyn.jclouds."+propVariant);
+            }
+        }
+
+        // Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can cause "stdin: is not a tty")
+        brooklynProperties.remove("brooklyn.ssh.config.scriptHeader");
+        
+        ctx = new LocalManagementContext(brooklynProperties);
+        app = ApplicationBuilder.newManagedApp(TestApplication.class, ctx);
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (app != null) Entities.destroyAllCatching(app.getManagementContext());
+    }
+
+    @Test(groups={"Live", "WIP"})
+    public void test_Ubuntu_13_10() throws Exception {
+          runTest(ImmutableMap.of("imageId", "7fe2ec2ff748c411cf0d6833120741778c00e1b07a83c4104296b6258b5331c4",
+              "loginUser", "root",
+              "loginUser.password", "password"));
+     }
+
+    protected void runTest(Map<String,?> flags) throws Exception {
+        String tag = getClass().getSimpleName().toLowerCase();
+        Map<String,?> allFlags = MutableMap.<String,Object>builder()
+                .put("tags", ImmutableList.of(tag))
+                .putAll(flags)
+                .build();
+        jcloudsLocation = ctx.getLocationRegistry().resolve(PROVIDER, allFlags);
+        doTest(jcloudsLocation);
+    }
+
+    protected abstract void doTest(Location loc) throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessRestartIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessRestartIntegrationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessRestartIntegrationTest.java
new file mode 100644
index 0000000..67f5fc4
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessRestartIntegrationTest.java
@@ -0,0 +1,96 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.RestartSoftwareParameters;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.StopSoftwareParameters;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.collections.CollectionFunctionals;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+/**
+ * Tests restart of the software *process* (as opposed to the VM).
+ */
+public abstract class AbstractSoftwareProcessRestartIntegrationTest extends BrooklynAppLiveTestSupport {
+    
+    // TODO Remove duplication from TomcatServerRestartIntegrationTest and MySqlRestartIntegrationTest
+    
+    @SuppressWarnings("unused")
+    private static final Logger LOG = LoggerFactory.getLogger(AbstractSoftwareProcessRestartIntegrationTest.class);
+
+    protected abstract EntitySpec<? extends SoftwareProcess> newEntitySpec();
+    
+    @Test(groups="Integration")
+    public void testStopProcessAndRestart() throws Exception {
+        runStopProcessAndRestart(
+                SoftwareProcess.RESTART, 
+                ImmutableMap.of(RestartSoftwareParameters.RESTART_MACHINE.getName(), RestartSoftwareParameters.RestartMachineMode.FALSE));
+    }
+    
+    @Test(groups="Integration")
+    public void testStopProcessAndStart() throws Exception {
+        runStopProcessAndRestart(
+                SoftwareProcess.START, 
+                ImmutableMap.of("locations", ImmutableList.of()));
+    }
+    
+    protected void runStopProcessAndRestart(Effector<?> restartEffector, Map<String, ?> args) throws Exception {
+        LocalhostMachineProvisioningLocation loc = app.newLocalhostProvisioningLocation();
+        SoftwareProcess entity = app.createAndManageChild(newEntitySpec());
+        
+        // Start the app
+        app.start(ImmutableList.of(loc));
+        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_UP, true);
+        EntityTestUtils.assertAttributeEqualsEventually(app, SoftwareProcess.SERVICE_UP, true);
+
+        // Stop the process
+        Entities.invokeEffector(app, entity, SoftwareProcess.STOP, ImmutableMap.of(
+                StopSoftwareParameters.STOP_MACHINE_MODE.getName(), StopSoftwareParameters.StopMode.NEVER))
+                .get();
+        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_UP, false);
+        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_STATE_ACTUAL, Lifecycle.STOPPED);
+        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, false);
+        EntityTestUtils.assertAttributeEventually(entity, ServiceStateLogic.SERVICE_NOT_UP_INDICATORS, CollectionFunctionals.<String>mapSizeEquals(1));
+        
+        // Restart the process
+        Entities.invokeEffector(app, entity, restartEffector, args).get();
+        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_UP, true);
+        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
+        EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, true);
+        EntityTestUtils.assertAttributeEqualsEventually(entity, ServiceStateLogic.SERVICE_NOT_UP_INDICATORS, ImmutableMap.<String, Object>of());
+
+        EntityTestUtils.assertAttributeEqualsEventually(app, SoftwareProcess.SERVICE_UP, true);
+        EntityTestUtils.assertAttributeEqualsEventually(app, SoftwareProcess.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcess.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcess.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcess.java
new file mode 100644
index 0000000..4459db4
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcess.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+
+@ImplementedBy(DoNothingSoftwareProcessImpl.class)
+public interface DoNothingSoftwareProcess extends SoftwareProcess {
+    
+    public static final ConfigKey<Boolean> SKIP_ON_BOX_BASE_DIR_RESOLUTION = ConfigKeys.newConfigKeyWithDefault(
+            BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION,
+            true);
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcessDriver.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcessDriver.java
new file mode 100644
index 0000000..2e0ea00
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcessDriver.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+/**
+ * Implements methods in {@link org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver}
+ * such that no actions are performed.
+ * <p>
+ * {@link #isRunning()} returns true.
+ */
+public class DoNothingSoftwareProcessDriver extends AbstractSoftwareProcessSshDriver {
+
+    public DoNothingSoftwareProcessDriver(EntityLocal entity, SshMachineLocation machine) {
+        super(entity, machine);
+    }
+
+    @Override
+    public boolean isRunning() {
+        return true;
+    }
+
+    @Override
+    public void copyPreInstallResources() {
+    }
+
+    @Override
+    public void copyInstallResources() {
+    }
+
+    @Override
+    public void copyRuntimeResources() {
+    }
+
+    @Override
+    public void install() {
+    }
+
+    @Override
+    public void customize() {
+    }
+
+    @Override
+    public void launch() {
+    }
+
+    @Override
+    public void stop() {
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcessImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcessImpl.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcessImpl.java
new file mode 100644
index 0000000..a04c660
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/DoNothingSoftwareProcessImpl.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
+
+public class DoNothingSoftwareProcessImpl extends SoftwareProcessImpl implements DoNothingSoftwareProcess {
+
+    @Override
+    public Class getDriverInterface() {
+        return DoNothingSoftwareProcessDriver.class;
+    }
+    
+    @Override
+    protected void connectSensors() {
+        super.connectSensors();
+        if (getAttribute(SERVICE_STATE_ACTUAL) == Lifecycle.STARTING) {
+            setAttribute(SERVICE_UP, true);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/MachineLifecycleEffectorTasksTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/MachineLifecycleEffectorTasksTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/MachineLifecycleEffectorTasksTest.java
new file mode 100644
index 0000000..3d87dbb
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/MachineLifecycleEffectorTasksTest.java
@@ -0,0 +1,140 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
+import java.util.List;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.StopSoftwareParameters.StopMode;
+import org.apache.brooklyn.entity.software.base.lifecycle.MachineLifecycleEffectorTasks;
+import org.apache.brooklyn.entity.stock.BasicEntity;
+import org.apache.brooklyn.entity.stock.BasicEntityImpl;
+import org.apache.brooklyn.entity.trait.Startable;
+import org.apache.brooklyn.sensor.core.DependentConfiguration;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.core.task.TaskInternal;
+import org.apache.brooklyn.util.time.Duration;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+
+import org.apache.brooklyn.location.jclouds.BailOutJcloudsLocation;
+
+public class MachineLifecycleEffectorTasksTest {
+    public static boolean canStop(StopMode stopMode, boolean isEntityStopped) {
+        BasicEntityImpl entity = new BasicEntityImpl();
+        Lifecycle state = isEntityStopped ? Lifecycle.STOPPED : Lifecycle.RUNNING;
+        entity.setAttribute(SoftwareProcess.SERVICE_STATE_ACTUAL, state);
+        return MachineLifecycleEffectorTasks.canStop(stopMode, entity);
+    }
+    
+    @DataProvider(name = "canStopStates")
+    public Object[][] canStopStates() {
+        return new Object[][] {
+            { StopMode.ALWAYS, true, true },
+            { StopMode.ALWAYS, false, true },
+            { StopMode.IF_NOT_STOPPED, true, false },
+            { StopMode.IF_NOT_STOPPED, false, true },
+            { StopMode.NEVER, true, false },
+            { StopMode.NEVER, false, false },
+        };
+    }
+
+    @Test(dataProvider = "canStopStates")
+    public void testBasicSonftwareProcessCanStop(StopMode mode, boolean isEntityStopped, boolean expected) {
+        boolean canStop = canStop(mode, isEntityStopped);
+        assertEquals(canStop, expected);
+    }
+
+    @Test
+    public void testProvisionLatchObeyed() throws Exception {
+
+        AttributeSensor<Boolean> ready = Sensors.newBooleanSensor("readiness");
+
+        TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
+        BasicEntity triggerEntity = app.createAndManageChild(EntitySpec.create(BasicEntity.class));
+
+        EmptySoftwareProcess entity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class)
+                .configure(BrooklynConfigKeys.PROVISION_LATCH, DependentConfiguration.attributeWhenReady(triggerEntity, ready)));
+
+        final Task<Void> task = Entities.invokeEffector(app, app, Startable.START, ImmutableMap.of(
+                "locations", ImmutableList.of(BailOutJcloudsLocation.newBailOutJcloudsLocation(app.getManagementContext()))));
+
+        assertEffectorBlockingDetailsEventually(entity, "Waiting for config " + BrooklynConfigKeys.PROVISION_LATCH.getName());
+
+        Asserts.succeedsContinually(new Runnable() {
+            @Override
+            public void run() {
+                assertFalse(task.isDone());
+            }
+        });
+        try {
+            ((EntityLocal) triggerEntity).setAttribute(ready, true);
+            task.get(Duration.THIRTY_SECONDS);
+        } catch (Throwable t) {
+            // BailOut location throws but we don't care.
+        } finally {
+            Entities.destroyAll(app.getManagementContext());
+        }
+    }
+
+    private void assertEffectorBlockingDetailsEventually(final Entity entity, final String blockingDetailsSnippet) {
+        Asserts.succeedsEventually(new Runnable() {
+            @Override public void run() {
+                Task<?> entityTask = Iterables.getOnlyElement(entity.getApplication().getManagementContext().getExecutionManager().getTasksWithAllTags(
+                        ImmutableList.of(BrooklynTaskTags.EFFECTOR_TAG, BrooklynTaskTags.tagForContextEntity(entity))));
+                String blockingDetails = getBlockingDetails(entityTask);
+                assertTrue(blockingDetails.contains(blockingDetailsSnippet));
+            }});
+    }
+
+    private String getBlockingDetails(Task<?> task) {
+        List<TaskInternal<?>> taskChain = Lists.newArrayList();
+        TaskInternal<?> taskI = (TaskInternal<?>) task;
+        while (taskI != null) {
+            taskChain.add(taskI);
+            if (taskI.getBlockingDetails() != null) {
+                return taskI.getBlockingDetails();
+            }
+            taskI = (TaskInternal<?>) taskI.getBlockingTask();
+        }
+        throw new IllegalStateException("No blocking details for "+task+" (walked task chain "+taskChain+")");
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SameServerEntityTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SameServerEntityTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SameServerEntityTest.java
new file mode 100644
index 0000000..937c87d
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SameServerEntityTest.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertSame;
+import static org.testng.Assert.assertTrue;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.SameServerEntity;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+
+public class SameServerEntityTest {
+
+    private LocalhostMachineProvisioningLocation loc;
+    private ManagementContext mgmt;
+    private TestApplication app;
+    private SameServerEntity entity;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() {
+        loc = new LocalhostMachineProvisioningLocation();
+        app = TestApplication.Factory.newManagedInstanceForTests();
+        mgmt = app.getManagementContext();
+        entity = app.createAndManageChild(EntitySpec.create(SameServerEntity.class));
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() {
+        if (app != null) Entities.destroyAll(mgmt);
+    }
+    
+    @Test
+    public void testUsesSameMachineLocationForEachChild() throws Exception {
+        Entity child1 = entity.addChild(EntitySpec.create(TestEntity.class));
+        Entity child2 = entity.addChild(EntitySpec.create(TestEntity.class));
+        Entities.manage(child1);
+        Entities.manage(child2);
+        
+        app.start(ImmutableList.of(loc));
+        
+        Location child1Loc = Iterables.getOnlyElement(child1.getLocations());
+        Location child2Loc = Iterables.getOnlyElement(child2.getLocations());
+        
+        assertSame(child1Loc, child2Loc);
+        assertTrue(child1Loc instanceof LocalhostMachine, "loc="+child1Loc);
+        
+        assertEquals(ImmutableSet.of(child1Loc), ImmutableSet.copyOf(loc.getInUse()));
+
+        app.stop();
+        
+        assertEquals(ImmutableSet.of(), ImmutableSet.copyOf(loc.getInUse()));
+    }
+}


[20/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessWinRmDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessWinRmDriver.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessWinRmDriver.java
new file mode 100644
index 0000000..f7d6ccf
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessWinRmDriver.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base;
+
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.location.basic.WinRmMachineLocation;
+import org.apache.brooklyn.util.net.UserAndHostAndPort;
+
+public class VanillaWindowsProcessWinRmDriver extends AbstractSoftwareProcessWinRmDriver implements VanillaWindowsProcessDriver {
+
+    public VanillaWindowsProcessWinRmDriver(EntityLocal entity, WinRmMachineLocation location) {
+        super(entity, location);
+    }
+
+    @Override
+    public void start() {
+        WinRmMachineLocation machine = (WinRmMachineLocation) location;
+        UserAndHostAndPort winrmAddress = UserAndHostAndPort.fromParts(machine.getUser(), machine.getAddress().getHostName(), machine.config().get(WinRmMachineLocation.WINRM_PORT));
+        getEntity().setAttribute(Attributes.WINRM_ADDRESS, winrmAddress);
+
+        super.start();
+    }
+    
+    @Override
+    public void preInstall() {
+        super.preInstall();
+        executeCommand(VanillaWindowsProcess.PRE_INSTALL_COMMAND, VanillaWindowsProcess.PRE_INSTALL_POWERSHELL_COMMAND, true);
+        if (entity.getConfig(VanillaWindowsProcess.PRE_INSTALL_REBOOT_REQUIRED)) {
+            rebootAndWait();
+        }
+    }
+
+    @Override
+    public void install() {
+        // TODO: Follow install path of VanillaSoftwareProcessSshDriver
+        executeCommand(VanillaWindowsProcess.INSTALL_COMMAND, VanillaWindowsProcess.INSTALL_POWERSHELL_COMMAND, true);
+        if (entity.getConfig(VanillaWindowsProcess.INSTALL_REBOOT_REQUIRED)) {
+            rebootAndWait();
+        }
+    }
+
+    @Override
+    public void customize() {
+        // TODO: Follow customize path of VanillaSoftwareProcessSshDriver
+        executeCommand(VanillaWindowsProcess.CUSTOMIZE_COMMAND, VanillaWindowsProcess.CUSTOMIZE_POWERSHELL_COMMAND, true);
+        if (entity.getConfig(VanillaWindowsProcess.CUSTOMIZE_REBOOT_REQUIRED)) {
+            rebootAndWait();
+        }
+    }
+
+    @Override
+    public void launch() {
+        executeCommand(VanillaWindowsProcess.LAUNCH_COMMAND, VanillaWindowsProcess.LAUNCH_POWERSHELL_COMMAND, true);
+    }
+
+    @Override
+    public boolean isRunning() {
+        return executeCommand(VanillaWindowsProcess.CHECK_RUNNING_COMMAND,
+                VanillaWindowsProcess.CHECK_RUNNING_POWERSHELL_COMMAND, false).getStatusCode() == 0;
+    }
+
+    @Override
+    public void stop() {
+        executeCommand(VanillaWindowsProcess.STOP_COMMAND, VanillaWindowsProcess.STOP_POWERSHELL_COMMAND, true);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasks.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasks.java
new file mode 100644
index 0000000..c46277b
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasks.java
@@ -0,0 +1,951 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.lifecycle;
+
+import java.io.Serializable;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.MachineManagementMixins;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.api.location.MachineManagementMixins.SuspendsMachines;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.config.Sanitizer;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
+import org.apache.brooklyn.effector.core.EffectorBody;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
+import org.apache.brooklyn.entity.machine.MachineInitTasks;
+import org.apache.brooklyn.entity.machine.ProvidesProvisioningFlags;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.RestartSoftwareParameters;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.StopSoftwareParameters;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.RestartSoftwareParameters.RestartMachineMode;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess.StopSoftwareParameters.StopMode;
+import org.apache.brooklyn.entity.stock.EffectorStartableImpl.StartParameters;
+import org.apache.brooklyn.entity.trait.Startable;
+import org.apache.brooklyn.entity.trait.StartableMethods;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Supplier;
+import com.google.common.base.Suppliers;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+
+import org.apache.brooklyn.location.basic.AbstractLocation;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.basic.Locations;
+import org.apache.brooklyn.location.basic.Machines;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.cloud.CloudLocationConfig;
+import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.guava.Maybe;
+import org.apache.brooklyn.util.net.UserAndHostAndPort;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.ssh.BashCommands;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.time.Duration;
+
+/**
+ * Default skeleton for start/stop/restart tasks on machines.
+ * <p>
+ * Knows how to provision machines, making use of {@link ProvidesProvisioningFlags#obtainProvisioningFlags(MachineProvisioningLocation)},
+ * and provides hooks for injecting behaviour at common places.
+ * <p>
+ * Methods are designed for overriding, with the convention that *Async methods should queue (and not block).
+ * The following methods are commonly overridden (and you can safely queue tasks, block, or return immediately in them):
+ * <ul>
+ *  <li> {@link #startProcessesAtMachine(Supplier)} (required)
+ *  <li> {@link #stopProcessesAtMachine()} (required, but can be left blank if you assume the VM will be destroyed)
+ *  <li> {@link #preStartCustom(MachineLocation)}
+ *  <li> {@link #postStartCustom()}
+ *  <li> {@link #preStopCustom()}
+ *  <li> {@link #postStopCustom()}
+ * </ul>
+ * Note methods at this level typically look after the {@link Attributes#SERVICE_STATE} sensor.
+ *
+ * @since 0.6.0
+ */
+@Beta
+public abstract class MachineLifecycleEffectorTasks {
+
+    private static final Logger log = LoggerFactory.getLogger(MachineLifecycleEffectorTasks.class);
+
+    public static final ConfigKey<Boolean> ON_BOX_BASE_DIR_RESOLVED = ConfigKeys.newBooleanConfigKey("onbox.base.dir.resolved",
+        "Whether the on-box base directory has been resolved (for internal use)");
+
+    public static final ConfigKey<Collection<? extends Location>> LOCATIONS = StartParameters.LOCATIONS;
+    public static final ConfigKey<Duration> STOP_PROCESS_TIMEOUT = ConfigKeys.newConfigKey(Duration.class,
+            "process.stop.timeout", "How long to wait for the processes to be stopped; use null to mean forever", Duration.TWO_MINUTES);
+
+    protected final MachineInitTasks machineInitTasks = new MachineInitTasks();
+    
+    /** Attaches lifecycle effectors (start, restart, stop) to the given entity post-creation. */
+    public void attachLifecycleEffectors(Entity entity) {
+        ((EntityInternal) entity).getMutableEntityType().addEffector(newStartEffector());
+        ((EntityInternal) entity).getMutableEntityType().addEffector(newRestartEffector());
+        ((EntityInternal) entity).getMutableEntityType().addEffector(newStopEffector());
+    }
+
+    /**
+     * Return an effector suitable for setting in a {@code public static final} or attaching dynamically.
+     * <p>
+     * The effector overrides the corresponding effector from {@link Startable} with
+     * the behaviour in this lifecycle class instance.
+     */
+    public Effector<Void> newStartEffector() {
+        return Effectors.effector(Startable.START).impl(newStartEffectorTask()).build();
+    }
+
+    /** @see {@link #newStartEffector()} */
+    public Effector<Void> newRestartEffector() {
+        return Effectors.effector(Startable.RESTART)
+                .parameter(RestartSoftwareParameters.RESTART_CHILDREN)
+                .parameter(RestartSoftwareParameters.RESTART_MACHINE)
+                .impl(newRestartEffectorTask())
+                .build();
+    }
+    
+    /** @see {@link #newStartEffector()} */
+    public Effector<Void> newStopEffector() {
+        return Effectors.effector(Startable.STOP)
+                .parameter(StopSoftwareParameters.STOP_PROCESS_MODE)
+                .parameter(StopSoftwareParameters.STOP_MACHINE_MODE)
+                .impl(newStopEffectorTask())
+                .build();
+    }
+
+    /** @see {@link #newStartEffector()} */
+    public Effector<Void> newSuspendEffector() {
+        return Effectors.effector(Void.class, "suspend")
+                .description("Suspend the process/service represented by an entity")
+                .parameter(StopSoftwareParameters.STOP_PROCESS_MODE)
+                .parameter(StopSoftwareParameters.STOP_MACHINE_MODE)
+                .impl(newSuspendEffectorTask())
+                .build();
+    }
+
+    /**
+     * Returns the {@link EffectorBody} which supplies the implementation for the start effector.
+     * <p>
+     * Calls {@link #start(Collection)} in this class.
+     */
+    public EffectorBody<Void> newStartEffectorTask() {
+        // TODO included anonymous inner class for backwards compatibility with persisted state.
+        new EffectorBody<Void>() {
+            @Override
+            public Void call(ConfigBag parameters) {
+                Collection<? extends Location> locations  = null;
+
+                Object locationsRaw = parameters.getStringKey(LOCATIONS.getName());
+                locations = Locations.coerceToCollection(entity().getManagementContext(), locationsRaw);
+
+                if (locations==null) {
+                    // null/empty will mean to inherit from parent
+                    locations = Collections.emptyList();
+                }
+
+                start(locations);
+                return null;
+            }
+        };
+        return new StartEffectorBody();
+    }
+
+    private class StartEffectorBody extends EffectorBody<Void> {
+        @Override
+        public Void call(ConfigBag parameters) {
+            Collection<? extends Location> locations = null;
+
+            Object locationsRaw = parameters.getStringKey(LOCATIONS.getName());
+            locations = Locations.coerceToCollection(entity().getManagementContext(), locationsRaw);
+
+            if (locations == null) {
+                // null/empty will mean to inherit from parent
+                locations = Collections.emptyList();
+            }
+
+            start(locations);
+            return null;
+        }
+
+    }
+
+    /**
+     * Calls {@link #restart(ConfigBag)}.
+     *
+     * @see {@link #newStartEffectorTask()}
+     */
+    public EffectorBody<Void> newRestartEffectorTask() {
+        // TODO included anonymous inner class for backwards compatibility with persisted state.
+        new EffectorBody<Void>() {
+            @Override
+            public Void call(ConfigBag parameters) {
+                restart(parameters);
+                return null;
+            }
+        };
+        return new RestartEffectorBody();
+    }
+
+    private class RestartEffectorBody extends EffectorBody<Void> {
+        @Override
+        public Void call(ConfigBag parameters) {
+            restart(parameters);
+            return null;
+        }
+    }
+
+    /**
+     * Calls {@link #stop(ConfigBag)}.
+     *
+     * @see {@link #newStartEffectorTask()}
+     */
+    public EffectorBody<Void> newStopEffectorTask() {
+        // TODO included anonymous inner class for backwards compatibility with persisted state.
+        new EffectorBody<Void>() {
+            @Override
+            public Void call(ConfigBag parameters) {
+                stop(parameters);
+                return null;
+            }
+        };
+        return new StopEffectorBody();
+    }
+
+    private class StopEffectorBody extends EffectorBody<Void> {
+        @Override
+        public Void call(ConfigBag parameters) {
+            stop(parameters);
+            return null;
+        }
+    }
+
+    /**
+     * Calls {@link #suspend(ConfigBag)}.
+     *
+     * @see {@link #newStartEffectorTask()}
+     */
+    public EffectorBody<Void> newSuspendEffectorTask() {
+        return new SuspendEffectorBody();
+    }
+
+    private class SuspendEffectorBody extends EffectorBody<Void> {
+        @Override
+        public Void call(ConfigBag parameters) {
+            suspend(parameters);
+            return null;
+        }
+    }
+
+    protected EntityInternal entity() {
+        return (EntityInternal) BrooklynTaskTags.getTargetOrContextEntity(Tasks.current());
+    }
+
+    protected Location getLocation(@Nullable Collection<? extends Location> locations) {
+        if (locations==null || locations.isEmpty()) locations = entity().getLocations();
+        if (locations.isEmpty()) {
+            MachineProvisioningLocation<?> provisioner = entity().getAttribute(SoftwareProcess.PROVISIONING_LOCATION);
+            if (provisioner!=null) locations = Arrays.<Location>asList(provisioner);
+        }
+        locations = Locations.getLocationsCheckingAncestors(locations, entity());
+
+        Maybe<MachineLocation> ml = Locations.findUniqueMachineLocation(locations);
+        if (ml.isPresent()) return ml.get();
+
+        if (locations.isEmpty())
+            throw new IllegalArgumentException("No locations specified when starting "+entity());
+        if (locations.size() != 1 || Iterables.getOnlyElement(locations)==null)
+            throw new IllegalArgumentException("Ambiguous locations detected when starting "+entity()+": "+locations);
+        return Iterables.getOnlyElement(locations);
+    }
+    
+    /** runs the tasks needed to start, wrapped by setting {@link Attributes#SERVICE_STATE_EXPECTED} appropriately */ 
+    public void start(Collection<? extends Location> locations) {
+        ServiceStateLogic.setExpectedState(entity(), Lifecycle.STARTING);
+        try {
+            startInLocations(locations);
+            DynamicTasks.waitForLast();
+            ServiceStateLogic.setExpectedState(entity(), Lifecycle.RUNNING);
+        } catch (Throwable t) {
+            ServiceStateLogic.setExpectedState(entity(), Lifecycle.ON_FIRE);
+            throw Exceptions.propagate(t);
+        }
+    }
+
+    /** Asserts there is a single location and calls {@link #startInLocation(Location)} with that location. */
+    protected void startInLocations(Collection<? extends Location> locations) {
+        startInLocation(getLocation(locations));
+    }
+
+    /** Dispatches to the appropriate method(s) to start in the given location. */
+    protected void startInLocation(final Location location) {
+        Supplier<MachineLocation> locationS = null;
+        if (location instanceof MachineProvisioningLocation) {
+            Task<MachineLocation> machineTask = provisionAsync((MachineProvisioningLocation<?>)location);
+            locationS = Tasks.supplier(machineTask);
+        } else if (location instanceof MachineLocation) {
+            locationS = Suppliers.ofInstance((MachineLocation)location);
+        }
+        Preconditions.checkState(locationS != null, "Unsupported location "+location+", when starting "+entity());
+
+        final Supplier<MachineLocation> locationSF = locationS;
+        preStartAtMachineAsync(locationSF);
+        DynamicTasks.queue("start (processes)", new StartProcessesAtMachineTask(locationSF));
+        postStartAtMachineAsync();
+    }
+
+    private class StartProcessesAtMachineTask implements Runnable {
+        private final Supplier<MachineLocation> machineSupplier;
+        private StartProcessesAtMachineTask(Supplier<MachineLocation> machineSupplier) {
+            this.machineSupplier = machineSupplier;
+        }
+        @Override
+        public void run() {
+            startProcessesAtMachine(machineSupplier);
+        }
+    }
+
+    /**
+     * Returns a queued {@link Task} which provisions a machine in the given location
+     * and returns that machine. The task can be used as a supplier to subsequent methods.
+     */
+    protected Task<MachineLocation> provisionAsync(final MachineProvisioningLocation<?> location) {
+        return DynamicTasks.queue(Tasks.<MachineLocation>builder().name("provisioning (" + location.getDisplayName() + ")").body(
+                new ProvisionMachineTask(location)).build());
+    }
+
+    private class ProvisionMachineTask implements Callable<MachineLocation> {
+        final MachineProvisioningLocation<?> location;
+
+        private ProvisionMachineTask(MachineProvisioningLocation<?> location) {
+            this.location = location;
+        }
+
+        public MachineLocation call() throws Exception {
+            // Blocks if a latch was configured.
+            entity().getConfig(BrooklynConfigKeys.PROVISION_LATCH);
+            final Map<String, Object> flags = obtainProvisioningFlags(location);
+            if (!(location instanceof LocalhostMachineProvisioningLocation))
+                log.info("Starting {}, obtaining a new location instance in {} with ports {}", new Object[]{entity(), location, flags.get("inboundPorts")});
+            entity().setAttribute(SoftwareProcess.PROVISIONING_LOCATION, location);
+            MachineLocation machine;
+            try {
+                machine = Tasks.withBlockingDetails("Provisioning machine in " + location, new ObtainLocationTask(location, flags));
+                if (machine == null)
+                    throw new NoMachinesAvailableException("Failed to obtain machine in " + location.toString());
+            } catch (Exception e) {
+                throw Exceptions.propagate(e);
+            }
+
+            if (log.isDebugEnabled())
+                log.debug("While starting {}, obtained new location instance {}", entity(),
+                        (machine instanceof SshMachineLocation ?
+                         machine + ", details " + ((SshMachineLocation) machine).getUser() + ":" + Sanitizer.sanitize(((SshMachineLocation) machine).config().getLocalBag())
+                                                               : machine));
+            return machine;
+        }
+    }
+
+    private static class ObtainLocationTask implements Callable<MachineLocation> {
+        final MachineProvisioningLocation<?> location;
+        final Map<String, Object> flags;
+
+        private ObtainLocationTask(MachineProvisioningLocation<?> location, Map<String, Object> flags) {
+            this.flags = flags;
+            this.location = location;
+        }
+
+        public MachineLocation call() throws NoMachinesAvailableException {
+            return location.obtain(flags);
+        }
+    }
+
+    /** Wraps a call to {@link #preStartCustom(MachineLocation)}, after setting the hostname and address. */
+    protected void preStartAtMachineAsync(final Supplier<MachineLocation> machineS) {
+        DynamicTasks.queue("pre-start", new PreStartTask(machineS.get()));
+    }
+
+    private class PreStartTask implements Runnable {
+        final MachineLocation machine;
+        private PreStartTask(MachineLocation machine) {
+            this.machine = machine;
+        }
+        public void run() {
+            log.info("Starting {} on machine {}", entity(), machine);
+            Collection<Location> oldLocs = entity().getLocations();
+            if (!oldLocs.isEmpty()) {
+                List<MachineLocation> oldSshLocs = ImmutableList.copyOf(Iterables.filter(oldLocs, MachineLocation.class));
+                if (!oldSshLocs.isEmpty()) {
+                    // check if existing locations are compatible
+                    log.debug("Entity " + entity() + " had machine locations " + oldSshLocs + " when starting at " + machine + "; checking if they are compatible");
+                    for (MachineLocation oldLoc : oldSshLocs) {
+                        // machines are deemed compatible if hostname and address are the same, or they are localhost
+                        // this allows a machine create by jclouds to then be defined with an ip-based spec
+                        if (!"localhost".equals(machine.getConfig(AbstractLocation.ORIGINAL_SPEC))) {
+                            checkLocationParametersCompatible(machine, oldLoc, "hostname",
+                                    oldLoc.getAddress().getHostName(), machine.getAddress().getHostName());
+                            checkLocationParametersCompatible(machine, oldLoc, "address",
+                                    oldLoc.getAddress().getHostAddress(), machine.getAddress().getHostAddress());
+                        }
+                    }
+                    log.debug("Entity " + entity() + " old machine locations " + oldSshLocs + " were compatible, removing them to start at " + machine);
+                    entity().removeLocations(oldSshLocs);
+                }
+            }
+            entity().addLocations(ImmutableList.of((Location) machine));
+
+            // elsewhere we rely on (public) hostname being set _after_ subnet_hostname
+            // (to prevent the tiny possibility of races resulting in hostname being returned
+            // simply because subnet is still being looked up)
+            Maybe<String> lh = Machines.getSubnetHostname(machine);
+            Maybe<String> la = Machines.getSubnetIp(machine);
+            if (lh.isPresent()) entity().setAttribute(Attributes.SUBNET_HOSTNAME, lh.get());
+            if (la.isPresent()) entity().setAttribute(Attributes.SUBNET_ADDRESS, la.get());
+            entity().setAttribute(Attributes.HOSTNAME, machine.getAddress().getHostName());
+            entity().setAttribute(Attributes.ADDRESS, machine.getAddress().getHostAddress());
+            if (machine instanceof SshMachineLocation) {
+                @SuppressWarnings("resource")
+                SshMachineLocation sshMachine = (SshMachineLocation) machine;
+                UserAndHostAndPort sshAddress = UserAndHostAndPort.fromParts(sshMachine.getUser(), sshMachine.getAddress().getHostName(), sshMachine.getPort());
+                entity().setAttribute(Attributes.SSH_ADDRESS, sshAddress);
+            }
+
+            if (Boolean.TRUE.equals(entity().getConfig(SoftwareProcess.OPEN_IPTABLES))) {
+                if (machine instanceof SshMachineLocation) {
+                    Iterable<Integer> inboundPorts = (Iterable<Integer>) machine.config().get(CloudLocationConfig.INBOUND_PORTS);
+                    machineInitTasks.openIptablesAsync(inboundPorts, (SshMachineLocation)machine);
+                } else {
+                    log.warn("Ignoring flag OPEN_IPTABLES on non-ssh location {}", machine);
+                }
+            }
+            if (Boolean.TRUE.equals(entity().getConfig(SoftwareProcess.STOP_IPTABLES))) {
+                if (machine instanceof SshMachineLocation) {
+                    machineInitTasks.stopIptablesAsync((SshMachineLocation)machine);
+                } else {
+                    log.warn("Ignoring flag STOP_IPTABLES on non-ssh location {}", machine);
+                }
+            }
+            if (Boolean.TRUE.equals(entity().getConfig(SoftwareProcess.DONT_REQUIRE_TTY_FOR_SUDO))) {
+                if (machine instanceof SshMachineLocation) {
+                    machineInitTasks.dontRequireTtyForSudoAsync((SshMachineLocation)machine);
+                } else {
+                    log.warn("Ignoring flag DONT_REQUIRE_TTY_FOR_SUDO on non-ssh location {}", machine);
+                }
+            }
+            resolveOnBoxDir(entity(), machine);
+            preStartCustom(machine);
+        }
+    }
+
+    /**
+     * Resolves the on-box dir.
+     * <p>
+     * Initialize and pre-create the right onbox working dir, if an ssh machine location.
+     * Logs a warning if not.
+     */
+    @SuppressWarnings("deprecation")
+    public static String resolveOnBoxDir(EntityInternal entity, MachineLocation machine) {
+        String base = entity.getConfig(BrooklynConfigKeys.ONBOX_BASE_DIR);
+        if (base==null) base = machine.getConfig(BrooklynConfigKeys.ONBOX_BASE_DIR);
+        if (base!=null && Boolean.TRUE.equals(entity.getConfig(ON_BOX_BASE_DIR_RESOLVED))) return base;
+        if (base==null) base = entity.getManagementContext().getConfig().getConfig(BrooklynConfigKeys.ONBOX_BASE_DIR);
+        if (base==null) base = entity.getConfig(BrooklynConfigKeys.BROOKLYN_DATA_DIR);
+        if (base==null) base = machine.getConfig(BrooklynConfigKeys.BROOKLYN_DATA_DIR);
+        if (base==null) base = entity.getManagementContext().getConfig().getConfig(BrooklynConfigKeys.BROOKLYN_DATA_DIR);
+        if (base==null) base = "~/brooklyn-managed-processes";
+        if (base.equals("~")) base=".";
+        if (base.startsWith("~/")) base = "."+base.substring(1);
+
+        String resolvedBase = null;
+        if (entity.getConfig(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION) || machine.getConfig(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION)) {
+            if (log.isDebugEnabled()) log.debug("Skipping on-box base dir resolution for "+entity+" at "+machine);
+            if (!Os.isAbsolutish(base)) base = "~/"+base;
+            resolvedBase = Os.tidyPath(base);
+        } else if (machine instanceof SshMachineLocation) {
+            SshMachineLocation ms = (SshMachineLocation)machine;
+            ProcessTaskWrapper<Integer> baseTask = SshEffectorTasks.ssh(
+                BashCommands.alternatives("mkdir -p \"${BASE_DIR}\"",
+                    BashCommands.chain(
+                        BashCommands.sudo("mkdir -p \"${BASE_DIR}\""),
+                        BashCommands.sudo("chown "+ms.getUser()+" \"${BASE_DIR}\""))),
+                "cd ~",
+                "cd ${BASE_DIR}",
+                "echo BASE_DIR_RESULT':'`pwd`:BASE_DIR_RESULT")
+                .environmentVariable("BASE_DIR", base)
+                .requiringExitCodeZero()
+                .summary("initializing on-box base dir "+base).newTask();
+            DynamicTasks.queueIfPossible(baseTask).orSubmitAsync(entity);
+            resolvedBase = Strings.getFragmentBetween(baseTask.block().getStdout(), "BASE_DIR_RESULT:", ":BASE_DIR_RESULT");
+        }
+        if (resolvedBase==null) {
+            if (!Os.isAbsolutish(base)) base = "~/"+base;
+            resolvedBase = Os.tidyPath(base);
+            log.warn("Could not resolve on-box directory for "+entity+" at "+machine+"; using "+resolvedBase+", though this may not be accurate at the target (and may fail shortly)");
+        }
+        entity.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, resolvedBase);
+        entity.setConfig(ON_BOX_BASE_DIR_RESOLVED, true);
+        return resolvedBase;
+    }
+
+    protected void checkLocationParametersCompatible(MachineLocation oldLoc, MachineLocation newLoc, String paramSummary,
+            Object oldParam, Object newParam) {
+        if (oldParam==null || newParam==null || !oldParam.equals(newParam))
+            throw new IllegalStateException("Cannot start "+entity()+" in "+newLoc+" as it has already been started with incompatible location "+oldLoc+" " +
+                    "("+paramSummary+" not compatible: "+oldParam+" / "+newParam+"); "+newLoc+" may require manual removal.");
+    }
+
+    /**
+     * Default pre-start hooks.
+     * <p>
+     * Can be extended by subclasses if needed.
+     */
+    protected void preStartCustom(MachineLocation machine) {
+        ConfigToAttributes.apply(entity());
+
+        // Opportunity to block startup until other dependent components are available
+        Object val = entity().getConfig(SoftwareProcess.START_LATCH);
+        if (val != null) log.debug("{} finished waiting for start-latch; continuing...", entity(), val);
+    }
+
+    protected Map<String, Object> obtainProvisioningFlags(final MachineProvisioningLocation<?> location) {
+        if (entity() instanceof ProvidesProvisioningFlags) {
+            return ((ProvidesProvisioningFlags)entity()).obtainProvisioningFlags(location).getAllConfig();
+        }
+        return MutableMap.<String, Object>of();
+    }
+
+    protected abstract String startProcessesAtMachine(final Supplier<MachineLocation> machineS);
+
+    protected void postStartAtMachineAsync() {
+        DynamicTasks.queue("post-start", new PostStartTask());
+    }
+
+    private class PostStartTask implements Runnable {
+        public void run() {
+            postStartCustom();
+        }
+    }
+
+    /**
+     * Default post-start hooks.
+     * <p>
+     * Can be extended by subclasses, and typically will wait for confirmation of start.
+     * The service not set to running until after this. Also invoked following a restart.
+     */
+    protected void postStartCustom() {
+        // nothing by default
+    }
+
+    /**
+     * whether when 'auto' mode is specified, the machine should be stopped when the restart effector is called
+     * <p>
+     * with {@link MachineLifecycleEffectorTasks}, a machine will always get created on restart if there wasn't one already
+     * (unlike certain subclasses which might attempt a shortcut process-level restart)
+     * so there is no reason for default behaviour of restart to throw away a provisioned machine,
+     * hence default impl returns <code>false</code>.
+     * <p>
+     * if it is possible to tell that a machine is unhealthy, or if {@link #restart(ConfigBag)} is overridden,
+     * then it might be appropriate to return <code>true</code> here.
+     */
+    protected boolean getDefaultRestartStopsMachine() {
+        return false;
+    }
+
+    /**
+     * Default restart implementation for an entity.
+     * <p>
+     * Stops processes if possible, then starts the entity again.
+     */
+    public void restart(ConfigBag parameters) {
+        ServiceStateLogic.setExpectedState(entity(), Lifecycle.STOPPING);
+
+        RestartMachineMode isRestartMachine = parameters.get(RestartSoftwareParameters.RESTART_MACHINE_TYPED);
+        if (isRestartMachine==null)
+            isRestartMachine=RestartMachineMode.AUTO;
+        if (isRestartMachine==RestartMachineMode.AUTO)
+            isRestartMachine = getDefaultRestartStopsMachine() ? RestartMachineMode.TRUE : RestartMachineMode.FALSE;
+
+        // Calling preStopCustom without a corresponding postStopCustom invocation
+        // doesn't look right so use a separate callback pair; Also depending on the arguments
+        // stop() could be called which will call the {pre,post}StopCustom on its own.
+        DynamicTasks.queue("pre-restart", new PreRestartTask());
+
+        if (isRestartMachine==RestartMachineMode.FALSE) {
+            DynamicTasks.queue("stopping (process)", new StopProcessesAtMachineTask());
+        } else {
+            DynamicTasks.queue("stopping (machine)", new StopMachineTask());
+        }
+
+        DynamicTasks.queue("starting", new StartInLocationsTask());
+        restartChildren(parameters);
+        DynamicTasks.queue("post-restart", new PostRestartTask());
+
+        DynamicTasks.waitForLast();
+        ServiceStateLogic.setExpectedState(entity(), Lifecycle.RUNNING);
+    }
+
+    private class PreRestartTask implements Runnable {
+        @Override
+        public void run() {
+            preRestartCustom();
+        }
+    }
+    private class PostRestartTask implements Runnable {
+        @Override
+        public void run() {
+            postRestartCustom();
+        }
+    }
+    private class StartInLocationsTask implements Runnable {
+        @Override
+        public void run() {
+            // startInLocations will look up the location, and provision a machine if necessary
+            // (if it remembered the provisioning location)
+            ServiceStateLogic.setExpectedState(entity(), Lifecycle.STARTING);
+            startInLocations(null);
+        }
+    }
+
+    protected void restartChildren(ConfigBag parameters) {
+        // TODO should we consult ChildStartableMode?
+
+        Boolean isRestartChildren = parameters.get(RestartSoftwareParameters.RESTART_CHILDREN);
+        if (isRestartChildren==null || !isRestartChildren) {
+            return;
+        }
+
+        if (isRestartChildren) {
+            DynamicTasks.queue(StartableMethods.restartingChildren(entity(), parameters));
+            return;
+        }
+
+        throw new IllegalArgumentException("Invalid value '"+isRestartChildren+"' for "+RestartSoftwareParameters.RESTART_CHILDREN.getName());
+    }
+
+    /**
+     * Default stop implementation for an entity.
+     * <p>
+     * Aborts if already stopped, otherwise sets state {@link Lifecycle#STOPPING} then
+     * invokes {@link #preStopCustom()}, {@link #stopProcessesAtMachine()}, then finally
+     * {@link #stopAnyProvisionedMachines()} and sets state {@link Lifecycle#STOPPED}.
+     * If no errors were encountered call {@link #postStopCustom()} at the end.
+     */
+    public void stop(ConfigBag parameters) {
+        doStop(parameters, new StopAnyProvisionedMachinesTask());
+    }
+
+    /**
+     * As {@link #stop} but calling {@link #suspendAnyProvisionedMachines} rather than
+     * {@link #stopAnyProvisionedMachines}.
+     */
+    public void suspend(ConfigBag parameters) {
+        doStop(parameters, new SuspendAnyProvisionedMachinesTask());
+    }
+
+    protected void doStop(ConfigBag parameters, Callable<StopMachineDetails<Integer>> stopTask) {
+        preStopConfirmCustom();
+
+        log.info("Stopping {} in {}", entity(), entity().getLocations());
+
+        StopMode stopMachineMode = getStopMachineMode(parameters);
+        StopMode stopProcessMode = parameters.get(StopSoftwareParameters.STOP_PROCESS_MODE);
+
+        DynamicTasks.queue("pre-stop", new PreStopCustomTask());
+
+        Maybe<MachineLocation> machine = Machines.findUniqueMachineLocation(entity().getLocations());
+        Task<String> stoppingProcess = null;
+        if (canStop(stopProcessMode, entity())) {
+            stoppingProcess = DynamicTasks.queue("stopping (process)", new StopProcessesAtMachineTask());
+        }
+
+        Task<StopMachineDetails<Integer>> stoppingMachine = null;
+        if (canStop(stopMachineMode, machine.isAbsent())) {
+            // Release this machine (even if error trying to stop process - we rethrow that after)
+            stoppingMachine = DynamicTasks.queue("stopping (machine)", stopTask);
+
+            DynamicTasks.drain(entity().getConfig(STOP_PROCESS_TIMEOUT), false);
+
+            // shutdown the machine if stopping process fails or takes too long
+            synchronized (stoppingMachine) {
+                // task also used as mutex by DST when it submits it; ensure it only submits once!
+                if (!stoppingMachine.isSubmitted()) {
+                    // force the stoppingMachine task to run by submitting it here
+                    StringBuilder msg = new StringBuilder("Submitting machine stop early in background for ").append(entity());
+                    if (stoppingProcess == null) {
+                        msg.append(". Process stop skipped, pre-stop not finished?");
+                    } else {
+                        msg.append(" because process stop has ").append(
+                                (stoppingProcess.isDone() ? "finished abnormally" : "not finished"));
+                    }
+                    log.warn(msg.toString());
+                    Entities.submit(entity(), stoppingMachine);
+                }
+            }
+        }
+
+        try {
+            // This maintains previous behaviour of silently squashing any errors on the stoppingProcess task if the
+            // stoppingMachine exits with a nonzero value
+            boolean checkStopProcesses = (stoppingProcess != null && (stoppingMachine == null || stoppingMachine.get().value == 0));
+
+            if (checkStopProcesses) {
+                // TODO we should test for destruction above, not merely successful "stop", as things like localhost and ssh won't be destroyed
+                DynamicTasks.waitForLast();
+                if (machine.isPresent()) {
+                    // throw early errors *only if* there is a machine and we have not destroyed it
+                    stoppingProcess.get();
+                }
+            }
+        } catch (Throwable e) {
+            ServiceStateLogic.setExpectedState(entity(), Lifecycle.ON_FIRE);
+            Exceptions.propagate(e);
+        }
+        entity().setAttribute(SoftwareProcess.SERVICE_UP, false);
+        ServiceStateLogic.setExpectedState(entity(), Lifecycle.STOPPED);
+
+        DynamicTasks.queue("post-stop", new PostStopCustomTask());
+
+        if (log.isDebugEnabled()) log.debug("Stopped software process entity "+entity());
+    }
+
+    private class StopAnyProvisionedMachinesTask implements Callable<StopMachineDetails<Integer>> {
+        public StopMachineDetails<Integer> call() {
+            return stopAnyProvisionedMachines();
+        }
+    }
+
+    private class SuspendAnyProvisionedMachinesTask implements Callable<StopMachineDetails<Integer>> {
+        public StopMachineDetails<Integer> call() {
+            return suspendAnyProvisionedMachines();
+        }
+    }
+
+    private class StopProcessesAtMachineTask implements Callable<String> {
+        public String call() {
+            DynamicTasks.markInessential();
+            stopProcessesAtMachine();
+            DynamicTasks.waitForLast();
+            return "Stop processes completed with no errors.";
+        }
+    }
+
+    private class StopMachineTask implements Callable<String> {
+        public String call() {
+            DynamicTasks.markInessential();
+            stop(ConfigBag.newInstance().configure(StopSoftwareParameters.STOP_MACHINE_MODE, StopMode.IF_NOT_STOPPED));
+            DynamicTasks.waitForLast();
+            return "Stop of machine completed with no errors.";
+        }
+    }
+
+    private class PreStopCustomTask implements Callable<String> {
+        public String call() {
+            if (entity().getAttribute(SoftwareProcess.SERVICE_STATE_ACTUAL) == Lifecycle.STOPPED) {
+                log.debug("Skipping stop of entity " + entity() + " when already stopped");
+                return "Already stopped";
+            }
+            ServiceStateLogic.setExpectedState(entity(), Lifecycle.STOPPING);
+            entity().setAttribute(SoftwareProcess.SERVICE_UP, false);
+            preStopCustom();
+            return null;
+        }
+    }
+
+    private class PostStopCustomTask implements Callable<Void> {
+        public Void call() {
+            postStopCustom();
+            return null;
+        }
+    }
+
+    public static StopMode getStopMachineMode(ConfigBag parameters) {
+        final StopMode stopMachineMode = parameters.get(StopSoftwareParameters.STOP_MACHINE_MODE);
+        return stopMachineMode;
+    }
+
+    public static boolean canStop(StopMode stopMode, Entity entity) {
+        boolean isEntityStopped = entity.getAttribute(SoftwareProcess.SERVICE_STATE_ACTUAL)==Lifecycle.STOPPED;
+        return canStop(stopMode, isEntityStopped);
+    }
+
+    protected static boolean canStop(StopMode stopMode, boolean isStopped) {
+        return stopMode == StopMode.ALWAYS ||
+                stopMode == StopMode.IF_NOT_STOPPED && !isStopped;
+    }
+
+    /** 
+     * Override to check whether stop can be executed.
+     * Throw if stop should be aborted.
+     */
+    protected void preStopConfirmCustom() {
+        // nothing needed here
+    }
+
+    protected void preStopCustom() {
+        // nothing needed here
+    }
+
+    protected void postStopCustom() {
+        // nothing needed here
+    }
+
+    protected void preRestartCustom() {
+        // nothing needed here
+    }
+
+    protected void postRestartCustom() {
+        // nothing needed here
+    }
+
+    public static class StopMachineDetails<T> implements Serializable {
+        private static final long serialVersionUID = 3256747214315895431L;
+        final String message;
+        final T value;
+        protected StopMachineDetails(String message, T value) {
+            this.message = message;
+            this.value = value;
+        }
+        @Override
+        public String toString() {
+            return message;
+        }
+    }
+
+    /**
+     * Return string message of result.
+     * <p>
+     * Can run synchronously or not, caller will submit/queue as needed, and will block on any submitted tasks.
+     */
+    protected abstract String stopProcessesAtMachine();
+
+    /**
+     * Stop and release the {@link MachineLocation} the entity is provisioned at.
+     * <p>
+     * Can run synchronously or not, caller will submit/queue as needed, and will block on any submitted tasks.
+     */
+    protected StopMachineDetails<Integer> stopAnyProvisionedMachines() {
+        @SuppressWarnings("unchecked")
+        MachineProvisioningLocation<MachineLocation> provisioner = entity().getAttribute(SoftwareProcess.PROVISIONING_LOCATION);
+
+        if (Iterables.isEmpty(entity().getLocations())) {
+            log.debug("No machine decommissioning necessary for "+entity()+" - no locations");
+            return new StopMachineDetails<Integer>("No machine decommissioning necessary - no locations", 0);
+        }
+
+        // Only release this machine if we ourselves provisioned it (e.g. it might be running other services)
+        if (provisioner==null) {
+            log.debug("No machine decommissioning necessary for "+entity()+" - did not provision");
+            return new StopMachineDetails<Integer>("No machine decommissioning necessary - did not provision", 0);
+        }
+
+        Location machine = getLocation(null);
+        if (!(machine instanceof MachineLocation)) {
+            log.debug("No decommissioning necessary for "+entity()+" - not a machine location ("+machine+")");
+            return new StopMachineDetails<Integer>("No machine decommissioning necessary - not a machine ("+machine+")", 0);
+        }
+        
+        clearEntityLocationAttributes(machine);
+        provisioner.release((MachineLocation)machine);
+
+        return new StopMachineDetails<Integer>("Decommissioned "+machine, 1);
+    }
+
+    /**
+     * Suspend the {@link MachineLocation} the entity is provisioned at.
+     * <p>
+     * Expects the entity's {@link SoftwareProcess#PROVISIONING_LOCATION provisioner} to be capable of
+     * {@link SuspendsMachines suspending machines}.
+     *
+     * @throws java.lang.UnsupportedOperationException if the entity's provisioner cannot suspend machines.
+     * @see MachineManagementMixins.SuspendsMachines
+     */
+    protected StopMachineDetails<Integer> suspendAnyProvisionedMachines() {
+        @SuppressWarnings("unchecked")
+        MachineProvisioningLocation<MachineLocation> provisioner = entity().getAttribute(SoftwareProcess.PROVISIONING_LOCATION);
+
+        if (Iterables.isEmpty(entity().getLocations())) {
+            log.debug("No machine decommissioning necessary for " + entity() + " - no locations");
+            return new StopMachineDetails<>("No machine suspend necessary - no locations", 0);
+        }
+
+        // Only release this machine if we ourselves provisioned it (e.g. it might be running other services)
+        if (provisioner == null) {
+            log.debug("No machine decommissioning necessary for " + entity() + " - did not provision");
+            return new StopMachineDetails<>("No machine suspend necessary - did not provision", 0);
+        }
+
+        Location machine = getLocation(null);
+        if (!(machine instanceof MachineLocation)) {
+            log.debug("No decommissioning necessary for " + entity() + " - not a machine location (" + machine + ")");
+            return new StopMachineDetails<>("No machine suspend necessary - not a machine (" + machine + ")", 0);
+        }
+
+        if (!(provisioner instanceof SuspendsMachines)) {
+            log.debug("Location provisioner ({}) cannot suspend machines", provisioner);
+            throw new UnsupportedOperationException("Location provisioner cannot suspend machines: " + provisioner);
+        }
+
+        clearEntityLocationAttributes(machine);
+        SuspendsMachines.class.cast(provisioner).suspendMachine(MachineLocation.class.cast(machine));
+
+        return new StopMachineDetails<>("Suspended " + machine, 1);
+    }
+
+    /**
+     * Nulls the attached entity's hostname, address, subnet hostname and subnet address sensors
+     * and removes the given machine from its locations.
+     */
+    protected void clearEntityLocationAttributes(Location machine) {
+        entity().removeLocations(ImmutableList.of(machine));
+        entity().setAttribute(Attributes.HOSTNAME, null);
+        entity().setAttribute(Attributes.ADDRESS, null);
+        entity().setAttribute(Attributes.SUBNET_HOSTNAME, null);
+        entity().setAttribute(Attributes.SUBNET_ADDRESS, null);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/NaiveScriptRunner.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/NaiveScriptRunner.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/NaiveScriptRunner.java
new file mode 100644
index 0000000..29b729e
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/NaiveScriptRunner.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.lifecycle;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.util.core.task.ssh.SshTasks;
+
+/** Marks something which can run scripts. Called "Naive" because it hides too much of the complexity,
+ * about script execution and other ssh-related tasks (put, etc). The {@link SshTasks} approach seems better.
+ * <p> 
+ * Not gone so far as deprecating (yet, in 0.6.0) although we might.  Feedback welcome. 
+ * @since 0.6.0 */
+public interface NaiveScriptRunner {
+
+    /** Runs a script and returns the result code */
+    int execute(List<String> script, String summaryForLogging);
+
+    /** Runs a script and returns the result code, supporting flags including:
+     *  out, err as output/error streams;
+     *  logPrefix, prefix string to put in log output;
+     *  env, map of environment vars to pass to shell environment */
+    @SuppressWarnings("rawtypes")
+    int execute(Map flags, List<String> script, String summaryForLogging);
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelper.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelper.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelper.java
new file mode 100644
index 0000000..bb974c5
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptHelper.java
@@ -0,0 +1,436 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.lifecycle;
+
+import static java.lang.String.format;
+import groovy.lang.Closure;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.api.mgmt.ExecutionContext;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.api.mgmt.TaskQueueingContext;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.util.GroovyJavaMethods;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.internal.ssh.ShellTool;
+import org.apache.brooklyn.util.core.mutex.WithMutexes;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.TaskBuilder;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.exceptions.RuntimeInterruptedException;
+import org.apache.brooklyn.util.stream.Streams;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.apache.brooklyn.util.text.Strings;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Predicate;
+import com.google.common.base.Predicates;
+
+public class ScriptHelper {
+
+    public static final Logger log = LoggerFactory.getLogger(ScriptHelper.class);
+
+    protected final NaiveScriptRunner runner;
+    public final String summary;
+
+    public final ScriptPart header = new ScriptPart(this);
+    public final ScriptPart body = new ScriptPart(this);
+    public final ScriptPart footer = new ScriptPart(this);
+    
+    @SuppressWarnings("rawtypes")
+    protected final Map flags = new LinkedHashMap();
+    protected Predicate<? super Integer> resultCodeCheck = Predicates.alwaysTrue();
+    protected Predicate<? super ScriptHelper> executionCheck = Predicates.alwaysTrue();
+    
+    protected boolean isTransient = false;
+    protected boolean isInessential = false;
+    protected boolean closeSshConnection = false;
+    protected boolean gatherOutput = false;
+    protected boolean noExtraOutput = false;
+    protected ByteArrayOutputStream stdout, stderr;
+    protected Task<Integer> task;
+
+    public ScriptHelper(NaiveScriptRunner runner, String summary) {
+        this.runner = runner;
+        this.summary = summary;
+    }
+
+    /**
+     * Takes a closure which accepts this ScriptHelper and returns true or false
+     * as to whether the script needs to run (or can throw error if desired)
+     */
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    public ScriptHelper executeIf(Closure c) {
+        Predicate<ScriptHelper> predicate = GroovyJavaMethods.predicateFromClosure(c);
+        return executeIf(predicate);
+    }
+
+    public ScriptHelper executeIf(Predicate<? super ScriptHelper> c) {
+        executionCheck = c;
+        return this;
+    }
+
+    public ScriptHelper skipIfBodyEmpty() {
+        Predicate<ScriptHelper> p = new Predicate<ScriptHelper>() {
+            @Override
+            public boolean apply(ScriptHelper input) {
+                return !input.body.isEmpty();
+            }
+        };
+
+        return executeIf(p);
+    }
+
+    public ScriptHelper failIfBodyEmpty() {
+        Predicate<ScriptHelper> p = new Predicate<ScriptHelper>() {
+            @Override
+            public boolean apply(ScriptHelper input) {
+                if (input.body.isEmpty()) {
+                    throw new IllegalStateException("body empty for " + summary);
+                }
+                return true;
+            }
+        };
+
+        return executeIf(p);
+    }
+
+    public ScriptHelper failOnNonZeroResultCode(boolean val) {
+        if (val) {
+            failOnNonZeroResultCode();
+        } else {
+            requireResultCode(Predicates.alwaysTrue());
+        }
+        return this;
+    }
+
+    public ScriptHelper failOnNonZeroResultCode() {
+        return updateTaskAndFailOnNonZeroResultCode();
+    }
+
+    public ScriptHelper failOnNonZeroResultCodeWithoutUpdatingTask() {
+        requireResultCode(Predicates.equalTo(0));
+        return this;
+    }
+    
+    public ScriptHelper updateTaskAndFailOnNonZeroResultCode() {
+        gatherOutput();
+        // a failure listener would be a cleaner way
+
+        resultCodeCheck = new Predicate<Integer>() {
+            @Override
+            public boolean apply(@Nullable Integer input) {
+                if (input==0) return true;
+
+                try {
+                    String notes = "";
+                    if (!getResultStderr().isEmpty())
+                        notes += "STDERR\n" + getResultStderr()+"\n";
+                    if (!getResultStdout().isEmpty())
+                        notes += "\n" + "STDOUT\n" + getResultStdout()+"\n";
+                    Tasks.setExtraStatusDetails(notes.trim());
+                } catch (Exception e) {
+                    log.warn("Unable to collect additional metadata on failure of "+summary+": "+e);
+                }
+
+                return false;
+            }
+        };
+        
+        return this;
+    }
+    
+    /**
+     * Convenience for error-checking the result.
+     * <p/>
+     * Takes closure which accepts bash exit code (integer),
+     * and returns false if it is invalid. Default is that this resultCodeCheck
+     * closure always returns true (and the exit code is made available to the
+     * caller if they care)
+     */
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    public ScriptHelper requireResultCode(Closure integerFilter) {
+        Predicate<Integer> objectPredicate = GroovyJavaMethods.predicateFromClosure(integerFilter);
+        return requireResultCode(objectPredicate);
+    }
+
+    public ScriptHelper requireResultCode(Predicate<? super Integer> integerFilter) {
+        resultCodeCheck = integerFilter;
+        return this;
+    }
+
+    protected Runnable mutexAcquire = new Runnable() {
+        public void run() {
+        }
+    };
+
+    protected Runnable mutexRelease = new Runnable() {
+        public void run() {
+        }
+    };
+
+    /**
+     * indicates that the script should acquire the given mutexId on the given mutexSupport
+     * and maintain it for the duration of script execution;
+     * typically used to prevent parallel scripts from conflicting in access to a resource
+     * (e.g. a folder, or a config file used by a process)
+     */
+    public ScriptHelper useMutex(final WithMutexes mutexSupport, final String mutexId, final String description) {
+        mutexAcquire = new Runnable() {
+            public void run() {
+                try {
+                    mutexSupport.acquireMutex(mutexId, description);
+                } catch (InterruptedException e) {
+                    throw new RuntimeInterruptedException(e);
+                }
+            }
+        };
+
+        mutexRelease = new Runnable() {
+            public void run() {
+                mutexSupport.releaseMutex(mutexId);
+            }
+        };
+
+        return this;
+    }
+
+    public ScriptHelper gatherOutput() {
+        return gatherOutput(true);
+    }
+    public ScriptHelper gatherOutput(boolean gather) {
+        gatherOutput = gather;
+        return this;
+    }
+
+    /**
+     * Indicate that no extra output should be appended to stdout.
+     * <p>
+     * By default Brooklyn appends a message like
+     * "<tt>Executed /tmp/brooklyn-20141010-164855950...sh, result 0</tt>"
+     * to script output.
+     */
+    public ScriptHelper noExtraOutput() {
+        return noExtraOutput(true);
+    }
+
+    /**
+     * @see #noExtraOutput()
+     */
+    private ScriptHelper noExtraOutput(boolean output) {
+        this.noExtraOutput = output;
+        return this;
+    }
+
+    /** The connection should be closed and disconnected once the commands have executed. */
+    public ScriptHelper closeSshConnection() {
+        closeSshConnection = true;
+        return this;
+    }
+    
+    /** Unique ID for the command execution; ensures new SSH connection from the pool. */
+    public ScriptHelper uniqueSshConnection() {
+        setFlag(SshMachineLocation.UNIQUE_ID, Identifiers.makeRandomBase64Id(32));
+        return this;
+    }
+    
+    /** indicates explicitly that the task can be safely forgotten about after it runs; useful for things like
+     * check_running which run repeatedly */
+    public void setTransient() {
+        isTransient = true;
+    }
+    
+    public void setInessential() {
+        isInessential = true;
+    }
+
+    public ScriptHelper inessential() {
+        isInessential = true;
+        return this;
+    }
+
+    /** creates a task which will execute this script; note this can only be run once per instance of this class */
+    public synchronized Task<Integer> newTask() {
+        if (task!=null) throw new IllegalStateException("task can only be generated once");
+        TaskBuilder<Integer> tb = Tasks.<Integer>builder().name("ssh: "+summary).body(
+                new Callable<Integer>() {
+                    public Integer call() throws Exception {
+                        return executeInternal();
+                    }
+                });
+        
+        try {
+            ByteArrayOutputStream stdin = new ByteArrayOutputStream();
+            for (String line: getLines()) {
+                stdin.write(line.getBytes());
+                stdin.write("\n".getBytes());
+            }
+            tb.tag(BrooklynTaskTags.tagForStreamSoft(BrooklynTaskTags.STREAM_STDIN, stdin));
+        } catch (IOException e) {
+            log.warn("Error registering stream "+BrooklynTaskTags.STREAM_STDIN+" on "+tb+": "+e, e);
+        }
+        
+        Map<?,?> env = (Map<?,?>) flags.get("env");
+        if (env!=null) {
+            // if not explicitly set, env will come from getShellEnv in AbstractSoftwareProcessSshDriver.execute,
+            // which will also update this tag appropriately
+            tb.tag(BrooklynTaskTags.tagForEnvStream(BrooklynTaskTags.STREAM_ENV, env));
+        }
+        
+        if (gatherOutput) {
+            stdout = new ByteArrayOutputStream();
+            tb.tag(BrooklynTaskTags.tagForStreamSoft(BrooklynTaskTags.STREAM_STDOUT, stdout));
+            stderr = new ByteArrayOutputStream();
+            tb.tag(BrooklynTaskTags.tagForStreamSoft(BrooklynTaskTags.STREAM_STDERR, stderr));
+        }
+        task = tb.build();
+        if (isTransient) BrooklynTaskTags.setTransient(task);
+        if (isInessential) BrooklynTaskTags.setInessential(task);
+        return task;
+    }
+    
+    /** returns the task, if it has been constructed, or null; use {@link #newTask()} to build 
+     * (if it is null and you need a task) */
+    public Task<Integer> peekTask() {
+        return task;
+    }
+
+    /** queues the task for execution if we are in a {@link TaskQueueingContext} (e.g. EffectorTaskFactory); 
+     * or if we aren't in a queueing context, it will submit the task (assuming there is an {@link ExecutionContext}
+     * _and_ block until completion, throwing on error */
+    @Beta
+    public Task<Integer> queue() {
+        return DynamicTasks.queueIfPossible(newTask()).orSubmitAndBlock().getTask();
+    }
+    
+    public int execute() {
+        if (DynamicTasks.getTaskQueuingContext()!=null) {
+            return queue().getUnchecked();
+        } else {
+            return executeInternal();
+        }
+    }
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    public int executeInternal() {
+        if (!executionCheck.apply(this)) {
+            return 0;
+        }
+
+        List<String> lines = getLines();
+        if (log.isTraceEnabled()) log.trace("executing: {} - {}", summary, lines);
+        
+        int result;
+        try {
+            mutexAcquire.run();
+            Map flags = getFlags();
+            if (closeSshConnection) {
+                flags.put("close", true);
+            }
+            if (gatherOutput) {
+                if (stdout==null) stdout = new ByteArrayOutputStream();
+                if (stderr==null) stderr = new ByteArrayOutputStream();
+                flags.put("out", stdout);
+                flags.put("err", stderr);
+            }
+            flags.put(ShellTool.PROP_NO_EXTRA_OUTPUT.getName(), noExtraOutput);
+            result = runner.execute(flags, lines, summary);
+        } catch (RuntimeInterruptedException e) {
+            throw logWithDetailsAndThrow(format("Execution failed, invocation error for %s: %s", summary, e.getMessage()), e);
+        } catch (Exception e) {
+            throw logWithDetailsAndThrow(format("Execution failed, invocation error for %s: %s", summary, e.getMessage()), e);
+        } finally {
+            mutexRelease.run();
+        }
+        if (log.isTraceEnabled()) log.trace("finished executing: {} - result code {}", summary, result);
+        
+        if (!resultCodeCheck.apply(result)) {
+            throw logWithDetailsAndThrow(format("Execution failed, invalid result %s for %s", result, summary), null);
+        }
+        return result;
+    }
+
+    protected RuntimeException logWithDetailsAndThrow(String message, Throwable optionalCause) {
+        log.warn(message+" (throwing)");
+        Streams.logStreamTail(log, "STDERR of problem in "+Tasks.current(), stderr, 1024);
+        Streams.logStreamTail(log, "STDOUT of problem in "+Tasks.current(), stdout, 1024);
+        Streams.logStreamTail(log, "STDIN of problem in "+Tasks.current(), Streams.byteArrayOfString(Strings.join(getLines(),"\n")), 4096);
+        if (optionalCause!=null) throw new IllegalStateException(message, optionalCause);
+        throw new IllegalStateException(message);
+    }
+
+    @SuppressWarnings("rawtypes")
+    public Map getFlags() {
+        return flags;
+    }
+    
+    @SuppressWarnings("unchecked")
+    public ScriptHelper setFlag(String flag, Object value) {
+        flags.put(flag, value);
+        return this;
+    }
+    
+    public <T> ScriptHelper setFlag(ConfigKey<T> flag, T value) {
+        return setFlag(flag.getName(), value);
+    }
+    
+    /** ensures the script runs with no environment variables; by default they will be inherited */
+    public ScriptHelper environmentVariablesReset() {
+        return environmentVariablesReset(MutableMap.of());
+    }
+    
+    /** overrides the default environment variables to use the given set; by default they will be inherited.
+     * TODO would be nice to have a way to add just a few, but there is no way currently to access the
+     * getShellEnvironment() from the driver which is what gets inherited (at execution time) */
+    public ScriptHelper environmentVariablesReset(Map<?,?> envVarsToSet) {
+        setFlag("env", envVarsToSet);
+        return this;
+    }
+
+    public List<String> getLines() {
+        List<String> result = new LinkedList<String>();
+        result.addAll(header.lines);
+        result.addAll(body.lines);
+        result.addAll(footer.lines);
+        return result;
+    }
+    
+    public String getResultStdout() {
+        if (stdout==null) throw new IllegalStateException("output not available on "+this+"; ensure gatherOutput(true) is set");
+        return stdout.toString();
+    }
+    public String getResultStderr() {
+        if (stderr==null) throw new IllegalStateException("output not available on "+this+"; ensure gatherOutput(true) is set");
+        return stderr.toString();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptPart.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptPart.java b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptPart.java
new file mode 100644
index 0000000..9174122
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/ScriptPart.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.lifecycle;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+
+public class ScriptPart {
+    protected ScriptHelper helper;
+    protected List<String> lines = new LinkedList<String>();
+
+    public ScriptPart(ScriptHelper helper) {
+        this.helper = helper;
+    }
+
+    public ScriptHelper append(CharSequence line) {
+        lines.add(line.toString());
+        return helper;
+    }
+
+    public ScriptHelper append(Collection<? extends CharSequence> lines) {
+        for (CharSequence line : lines) {
+            append(line);
+        }
+        return helper;
+    }
+
+    public ScriptHelper append(CharSequence... lines) {
+        return append(Arrays.asList(lines));
+    }
+
+    public ScriptHelper prepend(CharSequence line) {
+        lines.add(0, line.toString());
+        return helper;
+    }
+
+    public ScriptHelper prepend(Collection<? extends CharSequence> lines) {
+        List<CharSequence> reversedLines = new ArrayList<CharSequence>(lines);
+        Collections.reverse(reversedLines);
+        for (CharSequence line : reversedLines) {
+            prepend(line);
+        }
+        return helper;
+    }
+
+    public ScriptHelper prepend(CharSequence... lines) {
+        return prepend(Arrays.asList(lines));
+    }
+
+    public ScriptHelper reset(CharSequence line) {
+        return reset(Arrays.asList(line));
+    }
+
+    public ScriptHelper reset(List<? extends CharSequence> ll) {
+        lines.clear();
+        return append(ll);
+    }
+
+    public boolean isEmpty() {
+        return lines.isEmpty();
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/system_service/EntityLaunchListener.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/system_service/EntityLaunchListener.java b/software/base/src/main/java/org/apache/brooklyn/entity/system_service/EntityLaunchListener.java
new file mode 100644
index 0000000..9557277
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/system_service/EntityLaunchListener.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.system_service;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.mgmt.ExecutionManager;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.api.sensor.SensorEvent;
+import org.apache.brooklyn.api.sensor.SensorEventListener;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags.EffectorCallTag;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.util.core.task.Tasks;
+
+public class EntityLaunchListener implements Runnable, SensorEventListener<Lifecycle> {
+    private static final String SSH_LAUNCH_TASK_PREFIX = "ssh: launching";
+    private static final String LAUNCH_CHECK_SKIP_TAG = "system-service-update";
+
+    private final AtomicReference<Task<?>> launchTaskRef = new AtomicReference<Task<?>>();
+    private final SystemServiceEnricher enricher;
+
+    public EntityLaunchListener(SystemServiceEnricher enricher) {
+        this.enricher = checkNotNull(enricher, "enricher");
+    }
+
+    @Override
+    public void onEvent(SensorEvent<Lifecycle> event) {
+        if (event.getValue() == Lifecycle.RUNNING) {
+            Task<?>launchTask = getLatestLaunchTask(enricher.getEntity());
+            if (launchTask != null) {
+                launchTaskRef.set(launchTask);
+                if (!launchTask.isDone()) {
+                    launchTask.addListener(this, enricher.getEntityExecutionContext());
+                }
+                if (launchTask.isDone()) {
+                    run();
+                }
+            }
+        }
+    }
+
+    @Override
+    public void run() {
+        Task<?> launchTask = launchTaskRef.getAndSet(null);
+        if (launchTask == null) return;
+        if (launchTask.isError()) return;
+        enricher.onLaunched(launchTask);
+    }
+
+    private Task<?> getLatestLaunchTask(Entity entity) {
+        Task<?> startEffector = null;
+        ExecutionManager executionmgr = enricher.getManagementContext().getExecutionManager();
+        Set<Task<?>> entityTasks = BrooklynTaskTags.getTasksInEntityContext(executionmgr, entity);
+        for (Task<?> t : entityTasks) {
+            if (BrooklynTaskTags.isEffectorTask(t)) {
+                EffectorCallTag effectorTag = BrooklynTaskTags.getEffectorCallTag(t, false);
+                if (SystemServiceEnricher.LAUNCH_EFFECTOR_NAMES.contains(effectorTag.getEffectorName()) &&
+                        !BrooklynTaskTags.hasTag(t, LAUNCH_CHECK_SKIP_TAG)) {
+                    if (startEffector == null || startEffector.getStartTimeUtc() < t.getStartTimeUtc()) {
+                        startEffector = t;
+                    }
+                    BrooklynTaskTags.addTagDynamically(t, LAUNCH_CHECK_SKIP_TAG);
+                }
+            }
+        }
+        if (startEffector != null) {
+            Task<?> launchTask = findSshLaunchChild(startEffector);
+            if (launchTask != null) {
+                return launchTask;
+            }
+        }
+        return null;
+    }
+
+    private Task<?> findSshLaunchChild(Task<?> t) {
+        Iterable<Task<?>> children = Tasks.children(t);
+        for (Task<?> c : children) {
+            if (c.getDisplayName().startsWith(SSH_LAUNCH_TASK_PREFIX)) {
+                return c;
+            }
+        }
+        for (Task<?> c : children) {
+            Task<?> launchTask = findSshLaunchChild(c);
+            if (launchTask != null) {
+                return launchTask;
+            }
+        }
+        return null;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/org/apache/brooklyn/entity/system_service/InitdServiceInstaller.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/org/apache/brooklyn/entity/system_service/InitdServiceInstaller.java b/software/base/src/main/java/org/apache/brooklyn/entity/system_service/InitdServiceInstaller.java
new file mode 100644
index 0000000..a0724f2
--- /dev/null
+++ b/software/base/src/main/java/org/apache/brooklyn/entity/system_service/InitdServiceInstaller.java
@@ -0,0 +1,135 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.system_service;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.io.File;
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.api.objs.HasShortName;
+import org.apache.brooklyn.api.sensor.Enricher;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.effector.core.EffectorTasks;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.cloud.names.AbstractCloudMachineNamer;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.ResourceUtils;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.core.task.ssh.SshPutTaskWrapper;
+import org.apache.brooklyn.util.core.task.ssh.SshTasks;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.apache.brooklyn.util.core.text.TemplateProcessor;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.ssh.BashCommands;
+
+
+public class InitdServiceInstaller implements SystemServiceInstaller {
+    private static final ConfigKey<String> SERVICE_TEMPLATE = ConfigKeys.newStringConfigKey(
+            "service.initd.service_template", "URL of the template to be used as the /etc/init.d service", "classpath:///org/apache/brooklyn/entity/system_service/service.sh");
+
+    private final Entity entity;
+    private final Enricher enricher;
+
+    public InitdServiceInstaller(Entity entity, Enricher enricher) {
+        this.entity = checkNotNull(entity, "entity");
+        this.enricher = checkNotNull(enricher, "enricher");
+    }
+
+    @Override
+    public Task<?> getServiceInstallTask() {
+        ResourceUtils resource = new ResourceUtils(this);
+        String pidFile = entity.getAttribute(SoftwareProcess.PID_FILE);
+        String template = resource.getResourceAsString(enricher.config().get(SERVICE_TEMPLATE));
+        String serviceName = getServiceName();
+        SshMachineLocation sshMachine = EffectorTasks.getSshMachine(entity);
+        Map<String, Object> params = MutableMap.<String, Object>of(
+                "service.launch_script", Os.mergePaths(getRunDir(), getStartScriptName()),
+                "service.name", serviceName,
+                "service.user", sshMachine.getUser(),
+                "service.log_path", getLogLocation());
+        if (pidFile != null) {
+            params.put("service.pid_file", pidFile);
+        }
+        String service = TemplateProcessor.processTemplateContents(template, (EntityInternal)entity, params);
+        String tmpServicePath = Os.mergePaths(getRunDir(), serviceName);
+        String servicePath = "/etc/init.d/" + serviceName;
+        SshPutTaskWrapper putServiceTask = SshTasks.newSshPutTaskFactory(sshMachine, tmpServicePath)
+                .contents(service)
+                .newTask();
+        ProcessTaskWrapper<Integer> installServiceTask = SshTasks.newSshExecTaskFactory(sshMachine,
+                BashCommands.chain(
+                    BashCommands.sudo("mv " + tmpServicePath + " " + servicePath),
+                    BashCommands.sudo("chmod 0755 " + servicePath),
+                    BashCommands.sudo("chkconfig --add " + serviceName),
+                    BashCommands.sudo("chkconfig " + serviceName + " on")))
+            .requiringExitCodeZero()
+            .newTask();
+
+        return Tasks.<Void>builder()
+            .name("install (init.d)")
+            .description("Install init.d service")
+            .add(putServiceTask)
+            .add(installServiceTask)
+            .build();
+    }
+
+    private String getServiceName() {
+        String serviceNameTemplate = enricher.config().get(SystemServiceEnricher.SERVICE_NAME);
+        return serviceNameTemplate
+                .replace("${id}", entity.getId())
+                .replace("${entity_name}", getEntityName());
+    }
+
+    private CharSequence getEntityName() {
+        String name;
+        if (entity instanceof HasShortName) {
+            name = ((HasShortName)entity).getShortName();
+        } else if (entity instanceof Entity) {
+            name = ((Entity)entity).getDisplayName();
+        } else {
+            name = "brooklyn-service";
+        }
+        return AbstractCloudMachineNamer.sanitize(name.toString()).toLowerCase();
+    }
+
+    private String getStartScriptName() {
+        return enricher.config().get(SystemServiceEnricher.LAUNCH_SCRIPT_NAME);
+    }
+
+    private String getRunDir() {
+        return entity.getAttribute(SoftwareProcess.RUN_DIR);
+    }
+
+    private String getLogLocation() {
+        String logFileLocation = entity.getAttribute(Attributes.LOG_FILE_LOCATION);
+        if (logFileLocation != null) {
+            return new File(logFileLocation).getParent();
+        } else {
+            return "/tmp";
+        }
+    }
+
+}


[63/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/XmlMementoSerializer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/XmlMementoSerializer.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/XmlMementoSerializer.java
deleted file mode 100644
index 6133958..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/XmlMementoSerializer.java
+++ /dev/null
@@ -1,505 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.NoSuchElementException;
-import java.util.Stack;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.atomic.AtomicReference;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.api.catalog.CatalogItem;
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.internal.AbstractBrooklynObjectSpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.api.mgmt.classloading.BrooklynClassLoadingContext;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoPersister.LookupContext;
-import org.apache.brooklyn.api.objs.Identifiable;
-import org.apache.brooklyn.api.policy.Policy;
-import org.apache.brooklyn.api.sensor.Enricher;
-import org.apache.brooklyn.api.sensor.Feed;
-import org.apache.brooklyn.core.catalog.internal.CatalogBundleDto;
-import org.apache.brooklyn.core.catalog.internal.CatalogUtils;
-import org.apache.brooklyn.core.config.BasicConfigKey;
-import org.apache.brooklyn.core.mgmt.classloading.BrooklynClassLoadingContextSequential;
-import org.apache.brooklyn.core.mgmt.classloading.ClassLoaderFromBrooklynClassLoadingContext;
-import org.apache.brooklyn.core.mgmt.classloading.JavaBrooklynClassLoadingContext;
-import org.apache.brooklyn.core.mgmt.rebind.dto.BasicCatalogItemMemento;
-import org.apache.brooklyn.core.mgmt.rebind.dto.BasicEnricherMemento;
-import org.apache.brooklyn.core.mgmt.rebind.dto.BasicEntityMemento;
-import org.apache.brooklyn.core.mgmt.rebind.dto.BasicFeedMemento;
-import org.apache.brooklyn.core.mgmt.rebind.dto.BasicLocationMemento;
-import org.apache.brooklyn.core.mgmt.rebind.dto.BasicPolicyMemento;
-import org.apache.brooklyn.core.mgmt.rebind.dto.MutableBrooklynMemento;
-import org.apache.brooklyn.effector.core.BasicParameterType;
-import org.apache.brooklyn.effector.core.EffectorAndBody;
-import org.apache.brooklyn.effector.core.EffectorTasks.EffectorBodyTaskFactory;
-import org.apache.brooklyn.effector.core.EffectorTasks.EffectorTaskFactory;
-import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
-import org.apache.brooklyn.util.core.xstream.XmlSerializer;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.text.Strings;
-
-import com.thoughtworks.xstream.converters.Converter;
-import com.thoughtworks.xstream.converters.MarshallingContext;
-import com.thoughtworks.xstream.converters.SingleValueConverter;
-import com.thoughtworks.xstream.converters.UnmarshallingContext;
-import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;
-import com.thoughtworks.xstream.core.ReferencingMarshallingContext;
-import com.thoughtworks.xstream.core.util.HierarchicalStreams;
-import com.thoughtworks.xstream.io.HierarchicalStreamReader;
-import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
-import com.thoughtworks.xstream.io.path.PathTrackingReader;
-import com.thoughtworks.xstream.mapper.Mapper;
-import com.thoughtworks.xstream.mapper.MapperWrapper;
-
-/* uses xml, cleaned up a bit
- * 
- * there is an early attempt at doing this with JSON in pull request #344 but 
- * it is not nicely deserializable, see comments at http://xstream.codehaus.org/json-tutorial.html */  
-public class XmlMementoSerializer<T> extends XmlSerializer<T> implements MementoSerializer<T> {
-
-    private static final Logger LOG = LoggerFactory.getLogger(XmlMementoSerializer.class);
-
-    private final ClassLoader classLoader;
-    private LookupContext lookupContext;
-
-    public XmlMementoSerializer(ClassLoader classLoader) {
-        this.classLoader = checkNotNull(classLoader, "classLoader");
-        xstream.setClassLoader(this.classLoader);
-        
-        // old (deprecated in 070? or earlier) single-file persistence uses this keyword; TODO remove soon in 080 ?
-        xstream.alias("brooklyn", MutableBrooklynMemento.class);
-        
-        xstream.alias("entity", BasicEntityMemento.class);
-        xstream.alias("location", BasicLocationMemento.class);
-        xstream.alias("policy", BasicPolicyMemento.class);
-        xstream.alias("feed", BasicFeedMemento.class);
-        xstream.alias("enricher", BasicEnricherMemento.class);
-        xstream.alias("configKey", BasicConfigKey.class);
-        xstream.alias("catalogItem", BasicCatalogItemMemento.class);
-        xstream.alias("bundle", CatalogBundleDto.class);
-        xstream.alias("attributeSensor", BasicAttributeSensor.class);
-
-        xstream.alias("effector", Effector.class);
-        xstream.addDefaultImplementation(EffectorAndBody.class, Effector.class);
-        xstream.alias("parameter", BasicParameterType.class);
-        xstream.addDefaultImplementation(EffectorBodyTaskFactory.class, EffectorTaskFactory.class);
-        
-        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 FeedConverter());
-        xstream.registerConverter(new CatalogItemConverter());
-        xstream.registerConverter(new SpecConverter());
-
-        xstream.registerConverter(new ManagementContextConverter());
-        xstream.registerConverter(new TaskConverter(xstream.getMapper()));
-    
-        //For compatibility with existing persistence stores content.
-        xstream.aliasField("registeredTypeName", BasicCatalogItemMemento.class, "symbolicName");
-        xstream.registerLocalConverter(BasicCatalogItemMemento.class, "libraries", new CatalogItemLibrariesConverter());
-    }
-    
-    // Warning: this is called in the super-class constuctor, so before this constructor!
-    @Override
-    protected MapperWrapper wrapMapper(MapperWrapper next) {
-        MapperWrapper mapper = super.wrapMapper(next);
-        mapper = new CustomMapper(mapper, Entity.class, "entityProxy");
-        mapper = new CustomMapper(mapper, Location.class, "locationProxy");
-        return mapper;
-    }
-
-    @Override
-    public void serialize(Object object, Writer writer) {
-        super.serialize(object, writer);
-        try {
-            writer.append("\n");
-        } catch (IOException e) {
-            throw Exceptions.propagate(e);
-        }
-    }
-
-    @Override
-    public void setLookupContext(LookupContext lookupContext) {
-        this.lookupContext = checkNotNull(lookupContext, "lookupContext");
-    }
-
-    @Override
-    public void unsetLookupContext() {
-        this.lookupContext = null;
-    }
-    
-    /**
-     * For changing the tag used for anything that implements/extends the given type.
-     * Necessary for using EntityRef rather than the default "dynamic-proxy" tag.
-     * 
-     * @author aled
-     */
-    public class CustomMapper extends MapperWrapper {
-        private final Class<?> clazz;
-        private final String alias;
-
-        public CustomMapper(Mapper wrapped, Class<?> clazz, String alias) {
-            super(wrapped);
-            this.clazz = checkNotNull(clazz, "clazz");
-            this.alias = checkNotNull(alias, "alias");
-        }
-
-        public String getAlias() {
-            return alias;
-        }
-
-        @Override
-        public String serializedClass(@SuppressWarnings("rawtypes") Class type) {
-            if (type != null && clazz.isAssignableFrom(type)) {
-                return alias;
-            } else {
-                return super.serializedClass(type);
-            }
-        }
-
-        @Override
-        public Class<?> realClass(String elementName) {
-            if (elementName.equals(alias)) {
-                return clazz;
-            } else {
-                return super.realClass(elementName);
-            }
-        }
-    }
-
-    public abstract class IdentifiableConverter<IT extends Identifiable> implements SingleValueConverter {
-        private final Class<IT> clazz;
-        
-        IdentifiableConverter(Class<IT> clazz) {
-            this.clazz = clazz;
-        }
-        @Override
-        public boolean canConvert(@SuppressWarnings("rawtypes") Class type) {
-            boolean result = clazz.isAssignableFrom(type);
-            return result;
-        }
-
-        @Override
-        public String toString(Object obj) {
-            return obj == null ? null : ((Identifiable)obj).getId();
-        }
-        @Override
-        public Object fromString(String str) {
-            if (lookupContext == null) {
-                LOG.warn("Cannot unmarshal from persisted xml {} {}; no lookup context supplied!", clazz.getSimpleName(), str);
-                return null;
-            } else {
-                return lookup(str);
-            }
-        }
-        
-        protected abstract IT lookup(String id);
-    }
-
-    public class LocationConverter extends IdentifiableConverter<Location> {
-        LocationConverter() {
-            super(Location.class);
-        }
-        @Override
-        protected Location lookup(String id) {
-            return lookupContext.lookupLocation(id);
-        }
-    }
-
-    public class PolicyConverter extends IdentifiableConverter<Policy> {
-        PolicyConverter() {
-            super(Policy.class);
-        }
-        @Override
-        protected Policy lookup(String id) {
-            return lookupContext.lookupPolicy(id);
-        }
-    }
-
-    public class EnricherConverter extends IdentifiableConverter<Enricher> {
-        EnricherConverter() {
-            super(Enricher.class);
-        }
-        @Override
-        protected Enricher lookup(String id) {
-            return lookupContext.lookupEnricher(id);
-        }
-    }
-    
-    public class FeedConverter extends IdentifiableConverter<Feed> {
-        FeedConverter() {
-            super(Feed.class);
-        }
-        @Override
-        protected Feed lookup(String id) {
-            return lookupContext.lookupFeed(id);
-        }
-    }
-    
-    public class EntityConverter extends IdentifiableConverter<Entity> {
-        EntityConverter() {
-            super(Entity.class);
-        }
-        @Override
-        protected Entity lookup(String id) {
-            return lookupContext.lookupEntity(id);
-        }
-    }
-
-    @SuppressWarnings("rawtypes")
-    public class CatalogItemConverter extends IdentifiableConverter<CatalogItem> {
-        CatalogItemConverter() {
-            super(CatalogItem.class);
-        }
-        @Override
-        protected CatalogItem<?,?> lookup(String id) {
-            return lookupContext.lookupCatalogItem(id);
-        }
-    }
-
-
-    static boolean loggedTaskWarning = false;
-    public class TaskConverter implements Converter {
-        private final Mapper mapper;
-        
-        TaskConverter(Mapper mapper) {
-            this.mapper = mapper;
-        }
-        @Override
-        public boolean canConvert(@SuppressWarnings("rawtypes") Class type) {
-            return Task.class.isAssignableFrom(type);
-        }
-        @SuppressWarnings("deprecation")
-        @Override
-        public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
-            if (source == null) return;
-            if (((Task<?>)source).isDone() && !((Task<?>)source).isError()) {
-                try {
-                    context.convertAnother(((Task<?>)source).get());
-                } catch (InterruptedException e) {
-                    throw Exceptions.propagate(e);
-                } catch (ExecutionException e) {
-                    LOG.warn("Unexpected exception getting done (and non-error) task result for "+source+"; continuing: "+e, e);
-                }
-            } else {
-                // TODO How to log sensibly, without it logging this every second?!
-                // jun 2014, have added a "log once" which is not ideal but better than the log never behaviour
-                if (!loggedTaskWarning) {
-                    LOG.warn("Intercepting and skipping request to serialize a Task"
-                        + (context instanceof ReferencingMarshallingContext ? " at "+((ReferencingMarshallingContext)context).currentPath() : "")+
-                        " (only logging this once): "+source);
-                    loggedTaskWarning = true;
-                }
-                
-                return;
-            }
-        }
-        @Override
-        public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
-            if (reader.hasMoreChildren()) {
-                Class<?> type = HierarchicalStreams.readClassType(reader, mapper);
-                reader.moveDown();
-                Object result = context.convertAnother(null, type);
-                reader.moveUp();
-                return result;
-            } else {
-                return null;
-            }
-        }
-    }
-    
-    public class ManagementContextConverter implements Converter {
-        @Override
-        public boolean canConvert(@SuppressWarnings("rawtypes") Class type) {
-            return ManagementContext.class.isAssignableFrom(type);
-        }
-        @Override
-        public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
-            // write nothing, and always insert the current mgmt context
-        }
-        @Override
-        public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
-            return lookupContext.lookupManagementContext();
-        }
-    }
-
-    /** When reading/writing specs, it checks whether there is a catalog item id set and uses it to load */
-    public class SpecConverter extends ReflectionConverter {
-        SpecConverter() {
-            super(xstream.getMapper(), xstream.getReflectionProvider());
-        }
-        @Override
-        public boolean canConvert(@SuppressWarnings("rawtypes") Class type) {
-            return AbstractBrooklynObjectSpec.class.isAssignableFrom(type);
-        }
-        @Override
-        public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
-            if (source == null) return;
-            AbstractBrooklynObjectSpec<?, ?> spec = (AbstractBrooklynObjectSpec<?, ?>) source;
-            String catalogItemId = spec.getCatalogItemId();
-            if (Strings.isNonBlank(catalogItemId)) {
-                // write this field first, so we can peek at it when we read
-                writer.startNode("catalogItemId");
-                writer.setValue(catalogItemId);
-                writer.endNode();
-                
-                // we're going to write the catalogItemId field twice :( but that's okay.
-                // better solution would be to have mark/reset on reader so we can peek for such a field;
-                // see comment below
-                super.marshal(source, writer, context);
-            } else {
-                super.marshal(source, writer, context);
-            }
-        }
-        @Override
-        public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
-            String catalogItemId = null;
-            instantiateNewInstanceSettingCache(reader, context);
-            
-            if (reader instanceof PathTrackingReader) {
-                // have to assume this is first; there is no mark/reset support on these readers
-                // (if there were then it would be easier, we could just look for that child anywhere,
-                // and not need a custom writer!)
-                if ("catalogItemId".equals( ((PathTrackingReader)reader).peekNextChild() )) {
-                    // cache the instance
-                    
-                    reader.moveDown();
-                    catalogItemId = reader.getValue();
-                    reader.moveUp();
-                }
-            }
-            boolean customLoaderSet = false;
-            try {
-                if (Strings.isNonBlank(catalogItemId)) {
-                    if (lookupContext==null) throw new NullPointerException("lookupContext required to load catalog item "+catalogItemId);
-                    CatalogItem<?, ?> cat = CatalogUtils.getCatalogItemOptionalVersion(lookupContext.lookupManagementContext(), catalogItemId);
-                    if (cat==null) throw new NoSuchElementException("catalog item: "+catalogItemId);
-                    BrooklynClassLoadingContext clcNew = CatalogUtils.newClassLoadingContext(lookupContext.lookupManagementContext(), cat);
-                    pushXstreamCustomClassLoader(clcNew);
-                    customLoaderSet = true;
-                }
-                
-                AbstractBrooklynObjectSpec<?, ?> result = (AbstractBrooklynObjectSpec<?, ?>) super.unmarshal(reader, context);
-                // we wrote it twice so this shouldn't be necessary; but if we fix it so we only write once, we'd need this
-                result.catalogItemId(catalogItemId);
-                return result;
-            } finally {
-                instance = null;
-                if (customLoaderSet) {
-                    popXstreamCustomClassLoader();
-                }
-            }
-        }
-
-        Object instance;
-        
-        @Override
-        protected Object instantiateNewInstance(HierarchicalStreamReader reader, UnmarshallingContext context) {
-            // the super calls getAttribute which requires that we have not yet done moveDown,
-            // so we do this earlier and cache it for when we call super.unmarshal
-            if (instance==null)
-                throw new IllegalStateException("Instance should be created and cached");
-            return instance;
-        }
-        protected void instantiateNewInstanceSettingCache(HierarchicalStreamReader reader, UnmarshallingContext context) {
-            instance = super.instantiateNewInstance(reader, context);
-        }
-    }
-    
-    Stack<BrooklynClassLoadingContext> contexts = new Stack<BrooklynClassLoadingContext>();
-    Stack<ClassLoader> cls = new Stack<ClassLoader>();
-    AtomicReference<Thread> xstreamLockOwner = new AtomicReference<Thread>();
-    int lockCount;
-    
-    /** Must be accompanied by a corresponding {@link #popXstreamCustomClassLoader()} when finished. */
-    @SuppressWarnings("deprecation")
-    protected void pushXstreamCustomClassLoader(BrooklynClassLoadingContext clcNew) {
-        acquireXstreamLock();
-        BrooklynClassLoadingContext oldClc;
-        if (!contexts.isEmpty()) {
-            oldClc = contexts.peek();
-        } else {
-            // TODO XmlMementoSerializer should take a BCLC instead of a CL
-            oldClc = JavaBrooklynClassLoadingContext.create(lookupContext.lookupManagementContext(), xstream.getClassLoader());
-        }
-        BrooklynClassLoadingContextSequential clcMerged = new BrooklynClassLoadingContextSequential(lookupContext.lookupManagementContext(),
-            oldClc, clcNew);
-        contexts.push(clcMerged);
-        cls.push(xstream.getClassLoader());
-        ClassLoader newCL = ClassLoaderFromBrooklynClassLoadingContext.of(clcMerged);
-        xstream.setClassLoader(newCL);
-    }
-
-    protected void popXstreamCustomClassLoader() {
-        synchronized (xstreamLockOwner) {
-            releaseXstreamLock();
-            xstream.setClassLoader(cls.pop());
-            contexts.pop();
-        }
-    }
-    
-    protected void acquireXstreamLock() {
-        synchronized (xstreamLockOwner) {
-            while (true) {
-                if (xstreamLockOwner.compareAndSet(null, Thread.currentThread()) || 
-                    Thread.currentThread().equals( xstreamLockOwner.get() )) {
-                    break;
-                }
-                try {
-                    xstreamLockOwner.wait(1000);
-                } catch (InterruptedException e) {
-                    throw Exceptions.propagate(e);
-                }
-            }
-            lockCount++;
-        }
-    }
-
-    protected void releaseXstreamLock() {
-        synchronized (xstreamLockOwner) {
-            if (lockCount<=0) {
-                throw new IllegalStateException("xstream not locked");
-            }
-            if (--lockCount == 0) {
-                if (!xstreamLockOwner.compareAndSet(Thread.currentThread(), null)) {
-                    Thread oldOwner = xstreamLockOwner.getAndSet(null);
-                    throw new IllegalStateException("xstream was locked by "+oldOwner+" but unlock attempt by "+Thread.currentThread());
-                }
-                xstreamLockOwner.notifyAll();
-            }
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/plane/dto/BasicManagementNodeSyncRecord.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/plane/dto/BasicManagementNodeSyncRecord.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/plane/dto/BasicManagementNodeSyncRecord.java
deleted file mode 100644
index d492260..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/plane/dto/BasicManagementNodeSyncRecord.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.plane.dto;
-
-import java.io.Serializable;
-import java.net.URI;
-
-import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
-import org.apache.brooklyn.api.mgmt.ha.ManagementNodeSyncRecord;
-import org.apache.brooklyn.core.BrooklynVersion;
-import org.apache.brooklyn.util.time.Time;
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-
-import com.google.common.base.Objects;
-
-/**
- * Represents the state of a management node within the Brooklyn management plane
- * (DTO class).
- * 
- * @author aled
- */
-@JsonAutoDetect(fieldVisibility=Visibility.ANY, getterVisibility=Visibility.NONE)
-public class BasicManagementNodeSyncRecord implements ManagementNodeSyncRecord, Serializable {
-
-    private static final long serialVersionUID = 4918161834047884244L;
-
-    public static Builder builder() {
-        return new Builder();
-    }
-
-    public static class Builder {
-        private String brooklynVersion = BrooklynVersion.get();
-        protected String nodeId;
-        protected URI uri;
-        protected ManagementNodeState status;
-        protected Long priority;
-        protected long localTimestamp;
-        protected Long remoteTimestamp;
-
-        protected Builder self() {
-            return (Builder) this;
-        }
-        public Builder brooklynVersion(String val) {
-            brooklynVersion = val; return self();
-        }
-        public Builder nodeId(String val) {
-            nodeId = val; return self();
-        }
-        public Builder uri(URI val) {
-            uri = val; return self();
-        }
-        public Builder status(ManagementNodeState val) {
-            status = val; return self();
-        }
-        public Builder priority(Long val) {
-            priority = val; return self();
-        }
-        public Builder localTimestamp(long val) {
-            localTimestamp = val; return self();
-        }
-        public Builder remoteTimestamp(Long val) {
-            remoteTimestamp = val; return self();
-        }
-        public Builder from(ManagementNodeSyncRecord other) {
-            return from(other, false);
-        }
-        public Builder from(ManagementNodeSyncRecord other, boolean ignoreNulls) {
-            if (ignoreNulls && other==null) return this;
-            if (other.getBrooklynVersion()!=null) brooklynVersion = other.getBrooklynVersion();
-            if (other.getNodeId()!=null) nodeId = other.getNodeId();
-            if (other.getUri()!=null) uri = other.getUri();
-            if (other.getStatus()!=null) status = other.getStatus();
-            if (other.getPriority()!=null) priority = other.getPriority();
-            if (other.getLocalTimestamp()>0) localTimestamp = other.getLocalTimestamp();
-            if (other.getRemoteTimestamp()!=null) remoteTimestamp = other.getRemoteTimestamp();
-            return this;
-        }
-        public ManagementNodeSyncRecord build() {
-            return new BasicManagementNodeSyncRecord(this);
-        }
-    }
-    
-    private String brooklynVersion;
-    private String nodeId;
-    private URI uri;
-    private ManagementNodeState status;
-    private Long priority;
-    private Long localTimestamp;
-    private Long remoteTimestamp;
-    
-    /** @deprecated since 0.7.0, use {@link #localTimestamp} or {@link #remoteTimestamp},
-     * but kept (or rather added back in) to support deserializing previous instances */
-    @Deprecated
-    private Long timestampUtc;
-
-
-    // for de-serialization
-    @SuppressWarnings("unused")
-    private BasicManagementNodeSyncRecord() {
-    }
-
-    // Trusts the builder to not mess around with mutability concurrently with build().
-    protected BasicManagementNodeSyncRecord(Builder builder) {
-        brooklynVersion = builder.brooklynVersion;
-        nodeId = builder.nodeId;
-        uri = builder.uri;
-        status = builder.status;
-        priority = builder.priority;
-        localTimestamp = builder.localTimestamp;
-        remoteTimestamp = builder.remoteTimestamp;
-    }
-
-    @Override
-    public String getBrooklynVersion() {
-        return brooklynVersion;
-    }
-    
-    @Override
-    public String getNodeId() {
-        return nodeId;
-    }
-    
-    @Override
-    public URI getUri() {
-        return uri;
-    }
-    
-    @Override
-    public ManagementNodeState getStatus() {
-        return status;
-    }
-    
-    @Override
-    public Long getPriority() {
-        return priority;
-    }
-    
-    @Override
-    public long getLocalTimestamp() {
-        if (localTimestamp!=null) return localTimestamp;
-        if (timestampUtc!=null) return timestampUtc;
-        throw new NullPointerException("localTimestamp not known for "+getNodeId());
-    }
-    
-    @Override
-    public Long getRemoteTimestamp() {
-        return remoteTimestamp;
-    }
-    
-    @Override
-    public String toString() {
-        return Objects.toStringHelper(this)
-                .add("nodeId", getNodeId())
-                .add("status", getStatus()).toString();
-    }
-    
-    @Override
-    public String toVerboseString() {
-        return Objects.toStringHelper(this)
-                .omitNullValues()
-                .add("brooklynVersion", getBrooklynVersion())
-                .add("nodeId", getNodeId())
-                .add("uri", getUri())
-                .add("status", getStatus())
-                .add("priority", getPriority())
-                .add("localTimestamp", getLocalTimestamp()+"="+Time.makeDateString(getLocalTimestamp()))
-                .add("remoteTimestamp", getRemoteTimestamp()+(getRemoteTimestamp()==null ? "" : 
-                    "="+Time.makeDateString(getRemoteTimestamp())))
-                .toString();
-    }
-
-    /** used here for store to inject remote timestamp */
-    public void setRemoteTimestamp(Long remoteTimestamp) {
-        this.remoteTimestamp = remoteTimestamp;
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/plane/dto/ManagementPlaneSyncRecordImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/plane/dto/ManagementPlaneSyncRecordImpl.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/plane/dto/ManagementPlaneSyncRecordImpl.java
deleted file mode 100644
index fc09365..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/plane/dto/ManagementPlaneSyncRecordImpl.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.plane.dto;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import static com.google.common.base.Preconditions.checkState;
-
-import java.io.Serializable;
-import java.util.Map;
-
-import org.apache.brooklyn.api.mgmt.ha.ManagementNodeSyncRecord;
-import org.apache.brooklyn.api.mgmt.ha.ManagementPlaneSyncRecord;
-import org.apache.brooklyn.util.collections.MutableMap;
-
-import com.google.common.base.Objects;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Maps;
-
-public class ManagementPlaneSyncRecordImpl implements ManagementPlaneSyncRecord, Serializable {
-
-    private static final long serialVersionUID = -4207907303446336973L;
-
-    public static Builder builder() {
-        return new Builder();
-    }
-    
-    public static class Builder {
-        protected String masterNodeId;
-        protected final Map<String,ManagementNodeSyncRecord> nodes = MutableMap.of();
-        
-        public Builder masterNodeId(String val) {
-            masterNodeId = val; return this;
-        }
-        public Builder nodes(Iterable<ManagementNodeSyncRecord> vals) {
-            checkState(!Iterables.contains(checkNotNull(vals, "nodes must not be null"), null),  "nodes must not contain null: %s", vals);
-            for (ManagementNodeSyncRecord val: vals) nodes.put(val.getNodeId(), val);
-            return this;
-        }
-        public Builder node(ManagementNodeSyncRecord val) {
-            checkNotNull(val, "node must not be null"); 
-            nodes.put(val.getNodeId(), val);
-            return this;
-        }
-        public ManagementPlaneSyncRecord build() {
-            return new ManagementPlaneSyncRecordImpl(this);
-        }
-    }
-
-    private String masterNodeId;
-    private Map<String, ManagementNodeSyncRecord> managementNodes;
-    
-    private ManagementPlaneSyncRecordImpl(Builder builder) {
-        masterNodeId = builder.masterNodeId;
-        managementNodes = Maps.newLinkedHashMap();
-        for (ManagementNodeSyncRecord node : builder.nodes.values()) {
-            checkState(!managementNodes.containsKey(node.getNodeId()), "duplicate nodeId %s", node.getNodeId());
-            managementNodes.put(node.getNodeId(), node);
-        }
-    }
-
-    @Override
-    public String getMasterNodeId() {
-        return masterNodeId;
-    }
-    
-    @Override
-    public Map<String, ManagementNodeSyncRecord> getManagementNodes() {
-        return managementNodes;
-    }
-
-    @Override
-    public String toString() {
-        return Objects.toStringHelper(this)
-                .add("masterNodeId", masterNodeId)
-                .add("nodes", managementNodes.keySet())
-                .toString();
-    }
-
-    @Override
-    public String toVerboseString() {
-        return toString();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/CompoundTransformer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/CompoundTransformer.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/CompoundTransformer.java
index 1e547ee..74b1375 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/CompoundTransformer.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/CompoundTransformer.java
@@ -26,7 +26,7 @@ import java.util.Map;
 import org.apache.brooklyn.api.mgmt.rebind.RebindExceptionHandler;
 import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
 import org.apache.brooklyn.api.objs.BrooklynObjectType;
-import org.apache.brooklyn.core.mgmt.rebind.persister.BrooklynMementoPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
 import org.apache.brooklyn.core.mgmt.rebind.transformer.impl.XsltTransformer;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.ResourceUtils;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/objs/proxy/InternalLocationFactory.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/objs/proxy/InternalLocationFactory.java b/core/src/main/java/org/apache/brooklyn/core/objs/proxy/InternalLocationFactory.java
index 02d058e..e66c8b3 100644
--- a/core/src/main/java/org/apache/brooklyn/core/objs/proxy/InternalLocationFactory.java
+++ b/core/src/main/java/org/apache/brooklyn/core/objs/proxy/InternalLocationFactory.java
@@ -28,8 +28,8 @@ import org.apache.brooklyn.api.mgmt.ManagementContext;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.mgmt.internal.LocalLocationManager;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.location.basic.AbstractLocation;
-import org.apache.brooklyn.location.basic.LocationInternal;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 import org.apache.brooklyn.util.core.flags.FlagUtils;
 import org.apache.brooklyn.util.exceptions.Exceptions;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/effector/core/EffectorTasks.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/effector/core/EffectorTasks.java b/core/src/main/java/org/apache/brooklyn/effector/core/EffectorTasks.java
index 7a0881d..4f1b8d5 100644
--- a/core/src/main/java/org/apache/brooklyn/effector/core/EffectorTasks.java
+++ b/core/src/main/java/org/apache/brooklyn/effector/core/EffectorTasks.java
@@ -33,9 +33,9 @@ import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
 import org.apache.brooklyn.core.mgmt.internal.EffectorUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.Machines;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.location.basic.WinRmMachineLocation;
+import org.apache.brooklyn.location.core.Machines;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.location.winrm.WinRmMachineLocation;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 import org.apache.brooklyn.util.core.task.DynamicSequentialTask;
 import org.apache.brooklyn.util.core.task.DynamicTasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/entity/core/AbstractEntity.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/entity/core/AbstractEntity.java b/core/src/main/java/org/apache/brooklyn/entity/core/AbstractEntity.java
index a4447af..2814f32 100644
--- a/core/src/main/java/org/apache/brooklyn/entity/core/AbstractEntity.java
+++ b/core/src/main/java/org/apache/brooklyn/entity/core/AbstractEntity.java
@@ -75,7 +75,7 @@ import org.apache.brooklyn.entity.core.internal.EntityConfigMap;
 import org.apache.brooklyn.entity.lifecycle.PolicyDescriptor;
 import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
 import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic.ServiceNotUpLogic;
-import org.apache.brooklyn.location.basic.Locations;
+import org.apache.brooklyn.location.core.Locations;
 import org.apache.brooklyn.policy.core.AbstractPolicy;
 import org.apache.brooklyn.sensor.core.AttributeMap;
 import org.apache.brooklyn.sensor.core.AttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/entity/core/Entities.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/entity/core/Entities.java b/core/src/main/java/org/apache/brooklyn/entity/core/Entities.java
index b9ea275..4e479f5 100644
--- a/core/src/main/java/org/apache/brooklyn/entity/core/Entities.java
+++ b/core/src/main/java/org/apache/brooklyn/entity/core/Entities.java
@@ -75,8 +75,8 @@ import org.apache.brooklyn.core.objs.proxy.EntityProxyImpl;
 import org.apache.brooklyn.effector.core.Effectors;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.entity.trait.StartableMethods;
-import org.apache.brooklyn.location.basic.LocationInternal;
-import org.apache.brooklyn.location.basic.Locations;
+import org.apache.brooklyn.location.core.Locations;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.ResourceUtils;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/entity/core/EntitySuppliers.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/entity/core/EntitySuppliers.java b/core/src/main/java/org/apache/brooklyn/entity/core/EntitySuppliers.java
index 3c6ebea..7d5640c 100644
--- a/core/src/main/java/org/apache/brooklyn/entity/core/EntitySuppliers.java
+++ b/core/src/main/java/org/apache/brooklyn/entity/core/EntitySuppliers.java
@@ -19,8 +19,8 @@
 package org.apache.brooklyn.entity.core;
 
 import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.location.basic.Machines;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.core.Machines;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Supplier;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/entity/drivers/ReflectiveEntityDriverFactory.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/entity/drivers/ReflectiveEntityDriverFactory.java b/core/src/main/java/org/apache/brooklyn/entity/drivers/ReflectiveEntityDriverFactory.java
index b0791b2..0e54806 100644
--- a/core/src/main/java/org/apache/brooklyn/entity/drivers/ReflectiveEntityDriverFactory.java
+++ b/core/src/main/java/org/apache/brooklyn/entity/drivers/ReflectiveEntityDriverFactory.java
@@ -28,9 +28,9 @@ import org.apache.brooklyn.api.entity.drivers.EntityDriver;
 import org.apache.brooklyn.api.location.Location;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.location.paas.PaasLocation;
-import org.apache.brooklyn.location.basic.WinRmMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.location.winrm.WinRmMachineLocation;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.exceptions.Exceptions;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/entity/group/DynamicClusterImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/entity/group/DynamicClusterImpl.java b/core/src/main/java/org/apache/brooklyn/entity/group/DynamicClusterImpl.java
index 69f3744..a348489 100644
--- a/core/src/main/java/org/apache/brooklyn/entity/group/DynamicClusterImpl.java
+++ b/core/src/main/java/org/apache/brooklyn/entity/group/DynamicClusterImpl.java
@@ -52,8 +52,8 @@ import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.entity.trait.StartableMethods;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.Locations;
 import org.apache.brooklyn.location.cloud.AvailabilityZoneExtension;
+import org.apache.brooklyn.location.core.Locations;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.flags.TypeCoercions;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/entity/stock/BasicStartable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/entity/stock/BasicStartable.java b/core/src/main/java/org/apache/brooklyn/entity/stock/BasicStartable.java
index 0d6c62e..432e045 100644
--- a/core/src/main/java/org/apache/brooklyn/entity/stock/BasicStartable.java
+++ b/core/src/main/java/org/apache/brooklyn/entity/stock/BasicStartable.java
@@ -26,7 +26,7 @@ import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.location.basic.Locations;
+import org.apache.brooklyn.location.core.Locations;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/entity/stock/BasicStartableImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/entity/stock/BasicStartableImpl.java b/core/src/main/java/org/apache/brooklyn/entity/stock/BasicStartableImpl.java
index 3ff4b21..1818262 100644
--- a/core/src/main/java/org/apache/brooklyn/entity/stock/BasicStartableImpl.java
+++ b/core/src/main/java/org/apache/brooklyn/entity/stock/BasicStartableImpl.java
@@ -33,7 +33,7 @@ import org.apache.brooklyn.entity.lifecycle.Lifecycle;
 import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.entity.trait.StartableMethods;
-import org.apache.brooklyn.location.basic.Locations;
+import org.apache.brooklyn.location.core.Locations;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/access/BrooklynAccessUtils.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/access/BrooklynAccessUtils.java b/core/src/main/java/org/apache/brooklyn/location/access/BrooklynAccessUtils.java
index 38e9fdd..941f557 100644
--- a/core/src/main/java/org/apache/brooklyn/location/access/BrooklynAccessUtils.java
+++ b/core/src/main/java/org/apache/brooklyn/location/access/BrooklynAccessUtils.java
@@ -28,9 +28,9 @@ import org.apache.brooklyn.core.config.BasicConfigKey;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.Machines;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.location.basic.SupportsPortForwarding;
+import org.apache.brooklyn.location.core.Machines;
+import org.apache.brooklyn.location.core.SupportsPortForwarding;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.task.DynamicTasks;
 import org.apache.brooklyn.util.core.task.Tasks;
 import org.apache.brooklyn.util.core.task.ssh.SshTasks;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/access/PortForwardManagerImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/access/PortForwardManagerImpl.java b/core/src/main/java/org/apache/brooklyn/location/access/PortForwardManagerImpl.java
index 62b5c29..83be7f0 100644
--- a/core/src/main/java/org/apache/brooklyn/location/access/PortForwardManagerImpl.java
+++ b/core/src/main/java/org/apache/brooklyn/location/access/PortForwardManagerImpl.java
@@ -34,7 +34,7 @@ import org.apache.brooklyn.api.mgmt.rebind.RebindContext;
 import org.apache.brooklyn.api.mgmt.rebind.RebindSupport;
 import org.apache.brooklyn.api.mgmt.rebind.mementos.LocationMemento;
 import org.apache.brooklyn.core.mgmt.rebind.BasicLocationRebindSupport;
-import org.apache.brooklyn.location.basic.AbstractLocation;
+import org.apache.brooklyn.location.core.AbstractLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.slf4j.Logger;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/access/PortForwardManagerLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/access/PortForwardManagerLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/access/PortForwardManagerLocationResolver.java
index 1cc5318..525631c 100644
--- a/core/src/main/java/org/apache/brooklyn/location/access/PortForwardManagerLocationResolver.java
+++ b/core/src/main/java/org/apache/brooklyn/location/access/PortForwardManagerLocationResolver.java
@@ -23,12 +23,12 @@ import java.util.Map;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.api.location.LocationRegistry;
 import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.location.basic.LocationConfigUtils;
-import org.apache.brooklyn.location.basic.LocationInternal;
-import org.apache.brooklyn.location.basic.LocationPredicates;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.AbstractLocationResolver;
+import org.apache.brooklyn.location.core.AbstractLocationResolver;
+import org.apache.brooklyn.location.core.LocationConfigUtils;
+import org.apache.brooklyn.location.core.LocationPredicates;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 
 import com.google.common.base.Optional;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/AbstractLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/AbstractLocation.java b/core/src/main/java/org/apache/brooklyn/location/basic/AbstractLocation.java
deleted file mode 100644
index bab336a..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/AbstractLocation.java
+++ /dev/null
@@ -1,707 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static com.google.common.base.Preconditions.checkNotNull;
-import static org.apache.brooklyn.util.GroovyJavaMethods.elvis;
-import static org.apache.brooklyn.util.JavaGroovyEquivalents.groovyTruth;
-
-import java.io.Closeable;
-import java.util.Collection;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.api.mgmt.rebind.RebindSupport;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.LocationMemento;
-import org.apache.brooklyn.api.objs.Configurable;
-import org.apache.brooklyn.config.ConfigInheritance;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.config.ConfigKey.HasConfigKey;
-import org.apache.brooklyn.core.config.BasicConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.internal.BrooklynFeatureEnablement;
-import org.apache.brooklyn.core.internal.storage.BrooklynStorage;
-import org.apache.brooklyn.core.internal.storage.Reference;
-import org.apache.brooklyn.core.internal.storage.impl.BasicReference;
-import org.apache.brooklyn.core.mgmt.internal.LocalLocationManager;
-import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.core.mgmt.rebind.BasicLocationRebindSupport;
-import org.apache.brooklyn.core.objs.AbstractBrooklynObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.geo.HasHostGeoInfo;
-import org.apache.brooklyn.location.geo.HostGeoInfo;
-import org.apache.brooklyn.util.collections.SetFromLiveMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.flags.FlagUtils;
-import org.apache.brooklyn.util.core.flags.TypeCoercions;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.stream.Streams;
-
-import com.google.common.base.Objects;
-import com.google.common.base.Objects.ToStringHelper;
-import com.google.common.base.Splitter;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-import com.google.common.reflect.TypeToken;
-
-/**
- * A basic implementation of the {@link Location} interface.
- *
- * This provides an implementation which works according to the requirements of
- * the interface documentation, and is ready to be extended to make more specialized locations.
- * 
- * Override {@link #configure(Map)} to add special initialization logic.
- */
-public abstract class AbstractLocation extends AbstractBrooklynObject implements LocationInternal, HasHostGeoInfo, Configurable {
-    
-    private static final long serialVersionUID = -7495805474138619830L;
-
-    /** @deprecated since 0.7.0 shouldn't be public */
-    @Deprecated
-    public static final Logger LOG = LoggerFactory.getLogger(AbstractLocation.class);
-
-    public static final ConfigKey<Location> PARENT_LOCATION = new BasicConfigKey<Location>(Location.class, "parentLocation");
-
-    public static final ConfigKey<Boolean> TEMPORARY_LOCATION = ConfigKeys.newBooleanConfigKey("temporaryLocation",
-            "Indicates that the location is a temporary location that has been created to test connectivity, and that" +
-            "the location's events should not be recorded by usage listeners", false);
-
-    private final AtomicBoolean configured = new AtomicBoolean();
-    
-    private Reference<Long> creationTimeUtc = new BasicReference<Long>(System.currentTimeMillis());
-    
-    // _not_ set from flag; configured explicitly in configure, because we also need to update the parent's list of children
-    private Reference<Location> parent = new BasicReference<Location>();
-    
-    // NB: all accesses should be synchronized
-    private Set<Location> children = Sets.newLinkedHashSet();
-
-    private Reference<String> name = new BasicReference<String>();
-    private boolean displayNameAutoGenerated = true;
-
-    private Reference<HostGeoInfo> hostGeoInfo = new BasicReference<HostGeoInfo>();
-
-    private BasicConfigurationSupport config = new BasicConfigurationSupport();
-    
-    private ConfigBag configBag = new ConfigBag();
-
-    private volatile boolean managed;
-
-    private boolean inConstruction;
-
-    private Reference<Map<Class<?>, Object>> extensions = new BasicReference<Map<Class<?>, Object>>(Maps.<Class<?>, Object>newConcurrentMap());
-
-    private final LocationDynamicType locationType;
-
-    /**
-     * Construct a new instance of an AbstractLocation.
-     */
-    public AbstractLocation() {
-        this(Maps.newLinkedHashMap());
-    }
-    
-    /**
-     * Construct a new instance of an AbstractLocation.
-     *
-     * The properties map recognizes the following keys:
-     * <ul>
-     * <li>name - a name for the location
-     * <li>parentLocation - the parent {@link Location}
-     * </ul>
-     * 
-     * Other common properties (retrieved via get/findLocationProperty) include:
-     * <ul>
-     * <li>latitude
-     * <li>longitude
-     * <li>displayName
-     * <li>iso3166 - list of iso3166-2 code strings
-     * <li>timeZone
-     * <li>abbreviatedName
-     * </ul>
-     */
-    public AbstractLocation(Map<?,?> properties) {
-        super(properties);
-        inConstruction = true;
-        
-        // When one calls getConfig(key), we want to use the default value specified on *this* location
-        // if it overrides the default config, by using the type object 
-        locationType = new LocationDynamicType(this);
-        
-        if (isLegacyConstruction()) {
-            AbstractBrooklynObject checkWeGetThis = configure(properties);
-            assert this.equals(checkWeGetThis) : this+" configure method does not return itself; returns "+checkWeGetThis+" instead of "+this;
-
-            boolean deferConstructionChecks = (properties.containsKey("deferConstructionChecks") && TypeCoercions.coerce(properties.get("deferConstructionChecks"), Boolean.class));
-            if (!deferConstructionChecks) {
-                FlagUtils.checkRequiredFields(this);
-            }
-        }
-        
-        inConstruction = false;
-    }
-
-    protected void assertNotYetManaged() {
-        if (!inConstruction && Locations.isManaged(this)) {
-            LOG.warn("Configuration being made to {} after deployment; may not be supported in future versions", this);
-        }
-        //throw new IllegalStateException("Cannot set configuration "+key+" on active location "+this)
-    }
-
-    public void setManagementContext(ManagementContextInternal managementContext) {
-        super.setManagementContext(managementContext);
-        if (displayNameAutoGenerated && getId() != null) name.set(getClass().getSimpleName()+":"+getId().substring(0, Math.min(getId().length(),4)));
-
-        if (BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_USE_BROOKLYN_LIVE_OBJECTS_DATAGRID_STORAGE)) {
-            Location oldParent = parent.get();
-            Set<Location> oldChildren = children;
-            Map<String, Object> oldConfig = configBag.getAllConfig();
-            Long oldCreationTimeUtc = creationTimeUtc.get();
-            String oldDisplayName = name.get();
-            HostGeoInfo oldHostGeoInfo = hostGeoInfo.get();
-
-            parent = managementContext.getStorage().getReference(getId()+"-parent");
-            children = SetFromLiveMap.create(managementContext.getStorage().<Location,Boolean>getMap(getId()+"-children"));
-            creationTimeUtc = managementContext.getStorage().getReference(getId()+"-creationTime");
-            hostGeoInfo = managementContext.getStorage().getReference(getId()+"-hostGeoInfo");
-            name = managementContext.getStorage().getReference(getId()+"-displayName");
-
-            // Only override stored defaults if we have actual values. We might be in setManagementContext
-            // because we are reconstituting an existing entity in a new brooklyn management-node (in which
-            // case believe what is already in the storage), or we might be in the middle of creating a new 
-            // entity. Normally for a new entity (using EntitySpec creation approach), this will get called
-            // before setting the parent etc. However, for backwards compatibility we still support some
-            // things calling the entity's constructor directly.
-            if (oldParent != null) parent.set(oldParent);
-            if (oldChildren.size() > 0) children.addAll(oldChildren);
-            if (creationTimeUtc.isNull()) creationTimeUtc.set(oldCreationTimeUtc);
-            if (hostGeoInfo.isNull()) hostGeoInfo.set(oldHostGeoInfo);
-            if (name.isNull()) {
-                name.set(oldDisplayName);
-            } else {
-                displayNameAutoGenerated = false;
-            }
-
-            configBag = ConfigBag.newLiveInstance(managementContext.getStorage().<String,Object>getMap(getId()+"-config"));
-            if (oldConfig.size() > 0) {
-                configBag.putAll(oldConfig);
-            }
-        }
-    }
-
-    /**
-     * @deprecated since 0.7.0; only used for legacy brooklyn types where constructor is called directly;
-     * see overridden method for more info
-     */
-    @SuppressWarnings("serial")
-    @Override
-    @Deprecated
-    public AbstractLocation configure(Map<?,?> properties) {
-        assertNotYetManaged();
-        
-        boolean firstTime = !configured.getAndSet(true);
-            
-        configBag.putAll(properties);
-        
-        if (properties.containsKey(PARENT_LOCATION.getName())) {
-            // need to ensure parent's list of children is also updated
-            setParent(configBag.get(PARENT_LOCATION));
-            
-            // don't include parentLocation in configBag, as breaks rebind
-            configBag.remove(PARENT_LOCATION);
-        }
-
-        // NB: flag-setting done here must also be done in BasicLocationRebindSupport 
-        FlagUtils.setFieldsFromFlagsWithBag(this, properties, configBag, firstTime);
-        FlagUtils.setAllConfigKeys(this, configBag, false);
-
-        if (properties.containsKey("displayName")) {
-            name.set((String) removeIfPossible(properties, "displayName"));
-            displayNameAutoGenerated = false;
-        } else if (properties.containsKey("name")) {
-            name.set((String) removeIfPossible(properties, "name"));
-            displayNameAutoGenerated = false;
-        } else if (isLegacyConstruction()) {
-            name.set(getClass().getSimpleName()+":"+getId().substring(0, Math.min(getId().length(),4)));
-            displayNameAutoGenerated = true;
-        }
-
-        // TODO Explicitly dealing with iso3166 here because want custom splitter rule comma-separated string.
-        // Is there a better way to do it (e.g. more similar to latitude, where configKey+TypeCoercion is enough)?
-        if (groovyTruth(properties.get("iso3166"))) {
-            Object rawCodes = removeIfPossible(properties, "iso3166");
-            Set<String> codes;
-            if (rawCodes instanceof CharSequence) {
-                codes = ImmutableSet.copyOf(Splitter.on(",").trimResults().split((CharSequence)rawCodes));
-            } else {
-                codes = TypeCoercions.coerce(rawCodes, new TypeToken<Set<String>>() {});
-            }
-            configBag.put(LocationConfigKeys.ISO_3166, codes);
-        }
-        
-        return this;
-    }
-
-    // TODO ensure no callers rely on 'remove' semantics, and don't remove;
-    // or perhaps better use a config bag so we know what is used v unused
-    private static Object removeIfPossible(Map<?,?> map, Object key) {
-        try {
-            return map.remove(key);
-        } catch (Exception e) {
-            return map.get(key);
-        }
-    }
-    
-    public boolean isManaged() {
-        return getManagementContext() != null && managed;
-    }
-
-    public void onManagementStarted() {
-        if (displayNameAutoGenerated) name.set(getClass().getSimpleName()+":"+getId().substring(0, Math.min(getId().length(),4)));
-        this.managed = true;
-    }
-    
-    public void onManagementStopped() {
-        this.managed = false;
-        if (getManagementContext().isRunning()) {
-            BrooklynStorage storage = ((ManagementContextInternal)getManagementContext()).getStorage();
-            storage.remove(getId()+"-parent");
-            storage.remove(getId()+"-children");
-            storage.remove(getId()+"-creationTime");
-            storage.remove(getId()+"-hostGeoInfo");
-            storage.remove(getId()+"-displayName");
-            storage.remove(getId()+"-config");
-        }
-    }
-    
-    @Override
-    public String getDisplayName() {
-        return name.get();
-    }
-    
-    protected boolean isDisplayNameAutoGenerated() {
-        return displayNameAutoGenerated;
-    }
-    
-    @Override
-    public Location getParent() {
-        return parent.get();
-    }
-    
-    @Override
-    public Collection<Location> getChildren() {
-        synchronized (children) {
-            return ImmutableList.copyOf(children);
-        }
-    }
-
-    @Override
-    public void setParent(Location newParent) {
-        setParent(newParent, true);
-    }
-    
-    public void setParent(Location newParent, boolean updateChildListParents) {
-        if (newParent == this) {
-            throw new IllegalArgumentException("Location cannot be its own parent: "+this);
-        }
-        if (newParent == parent.get()) {
-            return; // no-op; already have desired parent
-        }
-        
-        if (parent.get() != null) {
-            Location oldParent = parent.get();
-            parent.set(null);
-            if (updateChildListParents)
-                ((AbstractLocation)oldParent).removeChild(this);
-        }
-        // TODO Should we support a location changing parent? The resulting unmanage/manage might cause problems.
-        // The code above suggests we do, but maybe we should warn or throw error, or at least test it!
-        
-        parent.set(newParent);
-        if (newParent != null) {
-            if (updateChildListParents)
-                ((AbstractLocation)newParent).addChild(this);
-        }
-        
-        onChanged();
-    }
-
-    @Override
-    public ConfigurationSupportInternal config() {
-        return config ;
-    }
-
-    private class BasicConfigurationSupport implements ConfigurationSupportInternal {
-
-        @Override
-        public <T> T get(ConfigKey<T> key) {
-            if (hasConfig(key, false)) return getLocalBag().get(key);
-            if (getParent() != null && isInherited(key)) {
-                return getParent().getConfig(key);
-            }
-            
-            // In case this entity class has overridden the given key (e.g. to set default), then retrieve this entity's key
-            // TODO when locations become entities, the duplication of this compared to EntityConfigMap.getConfig will disappear.
-            @SuppressWarnings("unchecked")
-            ConfigKey<T> ownKey = (ConfigKey<T>) elvis(locationType.getConfigKey(key.getName()), key);
-
-            return ownKey.getDefaultValue();
-        }
-
-        @Override
-        public <T> T get(HasConfigKey<T> key) {
-            return get(key.getConfigKey());
-        }
-
-        @Override
-        public <T> T set(ConfigKey<T> key, T val) {
-            T result = configBag.put(key, val);
-            onChanged();
-            return result;
-        }
-
-        @Override
-        public <T> T set(HasConfigKey<T> key, T val) {
-            return set(key.getConfigKey(), val);
-        }
-
-        @Override
-        public <T> T set(ConfigKey<T> key, Task<T> val) {
-            // TODO Support for locations
-            throw new UnsupportedOperationException();
-        }
-
-        @Override
-        public <T> T set(HasConfigKey<T> key, Task<T> val) {
-            // TODO Support for locations
-            throw new UnsupportedOperationException();
-        }
-
-        @Override
-        public ConfigBag getBag() {
-            ConfigBag result = ConfigBag.newInstanceExtending(configBag, ImmutableMap.of());
-            Location p = getParent();
-            if (p!=null) result.putIfAbsent(((LocationInternal)p).config().getBag());
-            return result;
-        }
-
-        @Override
-        public ConfigBag getLocalBag() {
-            return configBag;
-        }
-
-        @Override
-        public Maybe<Object> getRaw(ConfigKey<?> key) {
-            if (hasConfig(key, false)) return Maybe.of(getLocalBag().getStringKey(key.getName()));
-            if (getParent() != null && isInherited(key)) return ((LocationInternal)getParent()).config().getRaw(key);
-            return Maybe.absent();
-        }
-
-        @Override
-        public Maybe<Object> getRaw(HasConfigKey<?> key) {
-            return getRaw(key.getConfigKey());
-        }
-
-        @Override
-        public Maybe<Object> getLocalRaw(ConfigKey<?> key) {
-            if (hasConfig(key, false)) return Maybe.of(getLocalBag().getStringKey(key.getName()));
-            return Maybe.absent();
-        }
-
-        @Override
-        public Maybe<Object> getLocalRaw(HasConfigKey<?> key) {
-            return getLocalRaw(key.getConfigKey());
-        }
-
-        @Override
-        public void addToLocalBag(Map<String, ?> vals) {
-            configBag.putAll(vals);
-        }
-
-        @Override
-        public void removeFromLocalBag(String key) {
-            configBag.remove(key);
-        }
-
-        @Override
-        public void refreshInheritedConfig() {
-            // no-op for location
-        }
-        
-        @Override
-        public void refreshInheritedConfigOfChildren() {
-            // no-op for location
-        }
-        
-        private boolean hasConfig(ConfigKey<?> key, boolean includeInherited) {
-            if (includeInherited && isInherited(key)) {
-                return getBag().containsKey(key);
-            } else {
-                return getLocalBag().containsKey(key);
-            }
-        }
-        
-        private boolean isInherited(ConfigKey<?> key) {
-            ConfigInheritance inheritance = key.getInheritance();
-            if (inheritance==null) inheritance = getDefaultInheritance();
-            return inheritance.isInherited(key, getParent(), AbstractLocation.this);
-        }
-
-        private ConfigInheritance getDefaultInheritance() {
-            return ConfigInheritance.ALWAYS;
-        }
-    }
-    
-    @Override
-    public <T> T getConfig(HasConfigKey<T> key) {
-        return config().get(key);
-    }
-
-    @Override
-    public <T> T getConfig(ConfigKey<T> key) {
-        return config().get(key);
-    }
-
-    @Override
-    @Deprecated
-    public boolean hasConfig(ConfigKey<?> key, boolean includeInherited) {
-        return config.hasConfig(key, includeInherited);
-    }
-
-    @Override
-    @Deprecated
-    public Map<String,Object> getAllConfig(boolean includeInherited) {
-        // TODO Have no information about what to include/exclude inheritance wise.
-        // however few things use getAllConfigBag()
-        ConfigBag bag = (includeInherited ? config().getBag() : config().getLocalBag());
-        return bag.getAllConfig();
-    }
-    
-    @Override
-    @Deprecated
-    public ConfigBag getAllConfigBag() {
-        // TODO see comments in EntityConfigMap and on interface methods. 
-        // here ConfigBag is used exclusively so
-        // we have no information about what to include/exclude inheritance wise.
-        // however few things use getAllConfigBag()
-        return config().getBag();
-    }
-    
-    @Override
-    public ConfigBag getLocalConfigBag() {
-        return config().getLocalBag();
-    }
-
-    /** 
-     * @deprecated since 0.7; use {@link #getLocalConfigBag()}
-     * @since 0.6
-     */
-    @Deprecated
-    public ConfigBag getRawLocalConfigBag() {
-        return config().getLocalBag();
-    }
-    
-    @Override
-    @Deprecated
-    public <T> T setConfig(ConfigKey<T> key, T value) {
-        return config().set(key, value);
-    }
-
-    /**
-     * @since 0.6.0 (?) - use getDisplayName
-     * @deprecated since 0.7.0; use {@link #getDisplayName()}
-     */
-    @Deprecated
-    public void setName(String newName) {
-        setDisplayName(newName);
-    }
-
-    public void setDisplayName(String newName) {
-        name.set(newName);
-        displayNameAutoGenerated = false;
-        onChanged();
-    }
-
-    @Override
-    public boolean equals(Object o) {
-        if (! (o instanceof Location)) {
-            return false;
-        }
-
-        Location l = (Location) o;
-        return getId().equals(l.getId());
-    }
-
-    @Override
-    public int hashCode() {
-        return getId().hashCode();
-    }
-
-    @Override
-    public boolean containsLocation(Location potentialDescendent) {
-        Location loc = potentialDescendent;
-        while (loc != null) {
-            if (this == loc) return true;
-            loc = loc.getParent();
-        }
-        return false;
-    }
-
-    protected <T extends Location> T addChild(LocationSpec<T> spec) {
-        T child = getManagementContext().getLocationManager().createLocation(spec);
-        addChild(child);
-        return child;
-    }
-    
-    @SuppressWarnings("deprecation")
-    public void addChild(Location child) {
-        // Previously, setParent delegated to addChildLocation and we sometimes ended up with
-        // duplicate entries here. Instead this now uses a similar scheme to 
-        // AbstractLocation.setParent/addChild (with any weaknesses for distribution that such a 
-        // scheme might have...).
-        // 
-        // We continue to use a list to allow identical-looking locations, but they must be different 
-        // instances.
-        
-        synchronized (children) {
-            for (Location contender : children) {
-                if (contender == child) {
-                    // don't re-add; no-op
-                    return;
-                }
-            }
-
-            children.add(child);
-        }
-        
-        if (isManaged()) {
-            if (!getManagementContext().getLocationManager().isManaged(child)) {
-                Locations.manage(child, getManagementContext());
-            }
-        } else if (getManagementContext() != null) {
-            if (((LocalLocationManager)getManagementContext().getLocationManager()).getLocationEvenIfPreManaged(child.getId()) == null) {
-                ((ManagementContextInternal)getManagementContext()).prePreManage(child);
-            }
-        }
-
-        children.add(child);
-        child.setParent(this);
-        
-        onChanged();
-    }
-    
-    public boolean removeChild(Location child) {
-        boolean removed;
-        synchronized (children) {
-            removed = children.remove(child);
-        }
-        if (removed) {
-            if (child instanceof Closeable) {
-                Streams.closeQuietly((Closeable)child);
-            }
-            child.setParent(null);
-            
-            if (isManaged()) {
-                getManagementContext().getLocationManager().unmanage(child);
-            }
-        }
-        onChanged();
-        return removed;
-    }
-
-    protected void onChanged() {
-        // currently changes simply trigger re-persistence; there is no intermediate listener as we do for EntityChangeListener
-        if (isManaged()) {
-            getManagementContext().getRebindManager().getChangeListener().onChanged(this);
-        }
-    }
-
-    /** Default String representation is simplified name of class, together with selected fields. */
-    @Override
-    public String toString() {
-        return string().toString();
-    }
-    
-    @Override
-    public String toVerboseString() {
-        return toString();
-    }
-
-    /** override this, adding to the returned value, to supply additional fields to include in the toString */
-    protected ToStringHelper string() {
-        return Objects.toStringHelper(getClass()).add("id", getId()).add("name", name);
-    }
-    
-    @Override
-    public HostGeoInfo getHostGeoInfo() { return hostGeoInfo.get(); }
-    
-    public void setHostGeoInfo(HostGeoInfo hostGeoInfo) {
-        if (hostGeoInfo!=null) { 
-            this.hostGeoInfo.set(hostGeoInfo);
-            setConfig(LocationConfigKeys.LATITUDE, hostGeoInfo.latitude); 
-            setConfig(LocationConfigKeys.LONGITUDE, hostGeoInfo.longitude); 
-        } 
-    }
-
-    @Override
-    public RebindSupport<LocationMemento> getRebindSupport() {
-        return new BasicLocationRebindSupport(this);
-    }
-    
-    @Override
-    public boolean hasExtension(Class<?> extensionType) {
-        return extensions.get().containsKey(checkNotNull(extensionType, "extensionType"));
-    }
-
-    @Override
-    @SuppressWarnings("unchecked")
-    public <T> T getExtension(Class<T> extensionType) {
-        Object extension = extensions.get().get(checkNotNull(extensionType, "extensionType"));
-        if (extension == null) {
-            throw new IllegalArgumentException("No extension of type "+extensionType+" registered for location "+this);
-        }
-        return (T) extension;
-    }
-    
-    @Override
-    public <T> void addExtension(Class<T> extensionType, T extension) {
-        checkNotNull(extensionType, "extensionType");
-        checkNotNull(extension, "extension");
-        checkArgument(extensionType.isInstance(extension), "extension %s does not implement %s", extension, extensionType);
-        extensions.get().put(extensionType, extension);
-    }
-
-    @Override
-    public Map<String, String> toMetadataRecord() {
-        ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
-        if (getDisplayName() != null) builder.put("displayName", getDisplayName());
-        if (getParent() != null && getParent().getDisplayName() != null) {
-            builder.put("parentDisplayName", getParent().getDisplayName());
-        }
-        return builder.build();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/AbstractLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/AbstractLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/basic/AbstractLocationResolver.java
deleted file mode 100644
index 90a1861..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/AbstractLocationResolver.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationRegistry;
-import org.apache.brooklyn.api.location.LocationResolver;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.AbstractLocationResolver.SpecParser.ParsedSpec;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.text.KeyValueParser;
-
-import com.google.common.collect.ImmutableList;
-
-/**
- * Examples of valid specs:
- *   <ul>
- *     <li>byon(hosts=myhost)
- *     <li>byon(hosts=myhost,myhost2)
- *     <li>byon(hosts="myhost, myhost2")
- *     <li>byon(hosts=myhost,myhost2, name=abc)
- *     <li>byon(hosts="myhost, myhost2", name="my location name")
- *   </ul>
- * 
- * @author aled
- */
-@SuppressWarnings({"unchecked","rawtypes"})
-public abstract class AbstractLocationResolver implements LocationResolver {
-
-    public static final Logger log = LoggerFactory.getLogger(AbstractLocationResolver.class);
-    
-    protected volatile ManagementContext managementContext;
-
-    protected volatile SpecParser specParser;
-
-    protected abstract Class<? extends Location> getLocationType();
-    
-    protected abstract SpecParser getSpecParser();
-    
-    @Override
-    public void init(ManagementContext managementContext) {
-        this.managementContext = checkNotNull(managementContext, "managementContext");
-        this.specParser = getSpecParser();
-    }
-    
-    @Override
-    public boolean accepts(String spec, LocationRegistry registry) {
-        return BasicLocationRegistry.isResolverPrefixForSpec(this, spec, true);
-    }
-
-    @Override
-    public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
-        ConfigBag config = extractConfig(locationFlags, spec, registry);
-        Map globalProperties = registry.getProperties();
-        String namedLocation = (String) locationFlags.get(LocationInternal.NAMED_SPEC_NAME.getName());
-        
-        if (registry != null) {
-            LocationPropertiesFromBrooklynProperties.setLocalTempDir(globalProperties, config);
-        }
-
-        return managementContext.getLocationManager().createLocation(LocationSpec.create(getLocationType())
-            .configure(config.getAllConfig())
-            .configure(LocationConfigUtils.finalAndOriginalSpecs(spec, locationFlags, globalProperties, namedLocation)));
-    }
-
-    protected ConfigBag extractConfig(Map<?,?> locationFlags, String spec, LocationRegistry registry) {
-        Map globalProperties = registry.getProperties();
-        ParsedSpec parsedSpec = specParser.parse(spec);
-        String namedLocation = (String) locationFlags.get(LocationInternal.NAMED_SPEC_NAME.getName());
-        
-        // prefer args map over location flags
-        Map<String, Object> filteredProperties = getFilteredLocationProperties(getPrefix(), namedLocation, globalProperties);
-        ConfigBag flags = ConfigBag.newInstance(parsedSpec.argsMap).putIfAbsent(locationFlags).putIfAbsent(filteredProperties);
-
-        return flags;
-    }
-    
-    protected Map<String, Object> getFilteredLocationProperties(String provider, String namedLocation, Map<String, ?> globalProperties) {
-        return new LocationPropertiesFromBrooklynProperties().getLocationProperties(getPrefix(), namedLocation, globalProperties);
-    }
-    
-    /**
-     * Parses a spec, by default of the general form "prefix:parts1:part2(arg1=val1,arg2=val2)"
-     */
-    protected static class SpecParser {
-        
-        protected static class ParsedSpec {
-            public final String spec;
-            public final List<String> partsList;
-            public final Map<String,String> argsMap;
-            
-            ParsedSpec(String spec, List<String> partsList, Map<String,String> argsMap) {
-                this.spec = spec;
-                this.partsList = ImmutableList.copyOf(partsList);
-                this.argsMap = Collections.unmodifiableMap(MutableMap.copyOf(argsMap));
-            }
-        }
-        
-        protected final String prefix;
-        protected final Pattern pattern;
-        private String exampleUsage;
-        
-        public SpecParser(String prefix) {
-            this.prefix = prefix;
-            pattern = Pattern.compile("("+prefix+"|"+prefix.toLowerCase()+"|"+prefix.toUpperCase()+")" + "(:)?" + "(\\((.*)\\))?$");
-        }
-        
-        public SpecParser(String prefix, Pattern pattern) {
-            this.prefix = prefix;
-            this.pattern = pattern;
-        }
-        
-        public SpecParser setExampleUsage(String exampleUsage) {
-            this.exampleUsage = exampleUsage;
-            return this;
-        }
-
-        protected String getUsage(String spec) {
-            if (exampleUsage == null) {
-                return "Spec should be in the form "+pattern;
-            } else {
-                return "for example, "+exampleUsage;
-            }
-        }
-        
-        protected void checkParsedSpec(ParsedSpec parsedSpec) {
-            // If someone tries "byon:(),byon:()" as a single spec, we get weird key-values!
-            for (String key : parsedSpec.argsMap.keySet()) {
-                if (key.contains(":") || key.contains("{") || key.contains("}") || key.contains("(") || key.contains(")")) {
-                    throw new IllegalArgumentException("Invalid byon spec: "+parsedSpec.spec+" (key="+key+")");
-                }
-            }
-            String name = parsedSpec.argsMap.get("name");
-            if (parsedSpec.argsMap.containsKey("name") && (name == null || name.isEmpty())) {
-                throw new IllegalArgumentException("Invalid location '"+parsedSpec.spec+"'; if name supplied then value must be non-empty");
-            }
-            String displayName = parsedSpec.argsMap.get("displayName");
-            if (parsedSpec.argsMap.containsKey("displayName") && (displayName == null || displayName.isEmpty())) {
-                throw new IllegalArgumentException("Invalid location '"+parsedSpec.spec+"'; if displayName supplied then value must be non-empty");
-            }
-        }
-        
-        public ParsedSpec parse(String spec) {
-            Matcher matcher = pattern.matcher(spec);
-            if (!matcher.matches()) {
-                throw new IllegalArgumentException("Invalid location '"+spec+"'; "+getUsage(spec));
-            }
-            
-            String argsPart = matcher.group(3);
-            if (argsPart != null && argsPart.startsWith("(") && argsPart.endsWith(")")) {
-                // TODO Hacky; hosts("1.1.1.1") returns argsPart=("1.1.1.1")
-                argsPart = argsPart.substring(1, argsPart.length()-1);
-            }
-            Map<String, String> argsMap = KeyValueParser.parseMap(argsPart);
-            ParsedSpec result = new ParsedSpec(spec, ImmutableList.<String>of(), argsMap);
-            checkParsedSpec(result);
-            return result;
-        }
-    }
-}


[58/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/byon/FixedListMachineProvisioningLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/byon/FixedListMachineProvisioningLocation.java b/core/src/main/java/org/apache/brooklyn/location/byon/FixedListMachineProvisioningLocation.java
new file mode 100644
index 0000000..14e43e5
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/byon/FixedListMachineProvisioningLocation.java
@@ -0,0 +1,476 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.byon;
+
+import static org.apache.brooklyn.util.GroovyJavaMethods.truth;
+
+import java.io.Closeable;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.MachineLocationCustomizer;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.api.mgmt.LocationManager;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Function;
+import com.google.common.base.Objects;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import com.google.common.reflect.TypeToken;
+
+import org.apache.brooklyn.location.cloud.CloudLocationConfig;
+import org.apache.brooklyn.location.core.AbstractLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.util.collections.CollectionFunctionals;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.collections.MutableSet;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+import org.apache.brooklyn.util.stream.Streams;
+import org.apache.brooklyn.util.text.WildcardGlobs;
+import org.apache.brooklyn.util.text.WildcardGlobs.PhraseTreatment;
+
+/**
+ * A provisioner of {@link MachineLocation}s which takes a list of machines it can connect to.
+ * The collection of initial machines should be supplied in the 'machines' flag in the constructor,
+ * for example a list of machines which can be SSH'd to. 
+ * 
+ * This can be extended to have a mechanism to make more machines to be available
+ * (override provisionMore and canProvisionMore).
+ */
+public class FixedListMachineProvisioningLocation<T extends MachineLocation> extends AbstractLocation 
+implements MachineProvisioningLocation<T>, Closeable {
+
+    // TODO Synchronization looks very wrong for accessing machines/inUse 
+    // e.g. removeChild doesn't synchronize when doing machines.remove(...),
+    // and getMachines() returns the real sets risking 
+    // ConcurrentModificationException in the caller if it iterates over them etc.
+    
+    private static final Logger log = LoggerFactory.getLogger(FixedListMachineProvisioningLocation.class);
+    
+    public static final ConfigKey<Function<Iterable<? extends MachineLocation>, MachineLocation>> MACHINE_CHOOSER =
+            ConfigKeys.newConfigKey(
+                    new TypeToken<Function<Iterable<? extends MachineLocation>, MachineLocation>>() {}, 
+                    "byon.machineChooser",
+                    "For choosing which of the possible machines is chosen and returned by obtain()",
+                    CollectionFunctionals.<MachineLocation>firstElement());
+
+    public static final ConfigKey<Collection<MachineLocationCustomizer>> MACHINE_LOCATION_CUSTOMIZERS = CloudLocationConfig.MACHINE_LOCATION_CUSTOMIZERS;
+    
+    private final Object lock = new Object();
+    
+    @SetFromFlag
+    protected Set<T> machines;
+    
+    @SetFromFlag
+    protected Set<T> inUse;
+
+    @SetFromFlag
+    protected Set<T> pendingRemoval;
+    
+    @SetFromFlag
+    protected Map<T, Map<String, Object>> origConfigs;
+
+    public FixedListMachineProvisioningLocation() {
+        this(Maps.newLinkedHashMap());
+    }
+    public FixedListMachineProvisioningLocation(Map properties) {
+        super(properties);
+
+        if (isLegacyConstruction()) {
+            init();
+        }
+    }
+
+    @Override
+    public void init() {
+        super.init();
+        
+        Set<T> machinesCopy = MutableSet.of();
+        for (T location: machines) {
+            if (location==null) {
+                log.warn(""+this+" initialized with null location, removing (may be due to rebind with reference to an unmanaged location)");
+            } else {
+                Location parent = location.getParent();
+                if (parent == null) {
+                    addChild(location);
+                }
+                machinesCopy.add(location);
+            }
+        }
+        if (!machinesCopy.equals(machines)) {
+            machines = machinesCopy;
+        }
+    }
+    
+    @Override
+    public String toVerboseString() {
+        return Objects.toStringHelper(this).omitNullValues()
+                .add("id", getId()).add("name", getDisplayName())
+                .add("machinesAvailable", getAvailable()).add("machinesInUse", getInUse())
+                .toString();
+    }
+
+    @Override
+    public AbstractLocation configure(Map<?,?> properties) {
+        if (machines == null) machines = Sets.newLinkedHashSet();
+        if (inUse == null) inUse = Sets.newLinkedHashSet();
+        if (pendingRemoval == null) pendingRemoval = Sets.newLinkedHashSet();
+        if (origConfigs == null) origConfigs = Maps.newLinkedHashMap();
+        return super.configure(properties);
+    }
+    
+    @SuppressWarnings("unchecked")
+    public FixedListMachineProvisioningLocation<T> newSubLocation(Map<?,?> newFlags) {
+        // TODO shouldn't have to copy config bag as it should be inherited (but currently it is not used inherited everywhere; just most places)
+        return getManagementContext().getLocationManager().createLocation(LocationSpec.create(getClass())
+                .parent(this)
+                .configure(config().getLocalBag().getAllConfig())  // FIXME Should this just be inherited?
+                .configure(newFlags));
+    }
+
+    @Override
+    public void close() {
+        for (T machine : machines) {
+            if (machine instanceof Closeable) Streams.closeQuietly((Closeable)machine);
+        }
+    }
+    
+    public void addMachine(T machine) {
+        synchronized (lock) {
+            if (machines.contains(machine)) {
+                throw new IllegalArgumentException("Cannot add "+machine+" to "+toString()+", because already contained");
+            }
+            
+            Location existingParent = ((Location)machine).getParent();
+            if (existingParent == null) {
+                addChild(machine);
+            }
+            
+            machines.add(machine);
+        }
+    }
+    
+    public void removeMachine(T machine) {
+        synchronized (lock) {
+            if (inUse.contains(machine)) {
+                pendingRemoval.add(machine);
+            } else {
+                machines.remove(machine);
+                pendingRemoval.remove(machine);
+                if (this.equals(machine.getParent())) {
+                    removeChild((Location)machine);
+                }
+            }
+        }
+    }
+    
+    protected Set<T> getMachines() {
+        return machines;
+    }
+    
+    public Set<T> getAvailable() {
+        Set<T> a = Sets.newLinkedHashSet(machines);
+        a.removeAll(inUse);
+        return a;
+    }   
+     
+    public Set<T> getInUse() {
+        return Sets.newLinkedHashSet(inUse);
+    }   
+     
+    public Set<T> getAllMachines() {
+        return ImmutableSet.copyOf(machines);
+    }   
+     
+    @Override
+    public void addChild(Location child) {
+        super.addChild(child);
+        machines.add((T)child);
+    }
+
+    @Override
+    public boolean removeChild(Location child) {
+        if (inUse.contains(child)) {
+            throw new IllegalStateException("Child location "+child+" is in use; cannot remove from "+this);
+        }
+        machines.remove(child);
+        return super.removeChild(child);
+    }
+
+    protected boolean canProvisionMore() {
+        return false;
+    }
+    
+    protected void provisionMore(int size) {
+        provisionMore(size, ImmutableMap.of());
+    }
+
+    protected void provisionMore(int size, Map<?,?> flags) {
+        throw new IllegalStateException("more not permitted");
+    }
+
+    public T obtain() throws NoMachinesAvailableException {
+        return obtain(Maps.<String,Object>newLinkedHashMap());
+    }
+    
+    @Override
+    public T obtain(Map<?,?> flags) throws NoMachinesAvailableException {
+        T machine;
+        T desiredMachine = (T) flags.get("desiredMachine");
+        ConfigBag allflags = ConfigBag.newInstanceExtending(config().getBag()).putAll(flags);
+        Function<Iterable<? extends MachineLocation>, MachineLocation> chooser = allflags.get(MACHINE_CHOOSER);
+        
+        synchronized (lock) {
+            Set<T> a = getAvailable();
+            if (a.isEmpty()) {
+                if (canProvisionMore()) {
+                    provisionMore(1, allflags.getAllConfig());
+                    a = getAvailable();
+                }
+                if (a.isEmpty())
+                    throw new NoMachinesAvailableException("No machines available in "+toString());
+            }
+            if (desiredMachine != null) {
+                if (a.contains(desiredMachine)) {
+                    machine = desiredMachine;
+                } else {
+                    throw new IllegalStateException("Desired machine "+desiredMachine+" not available in "+toString()+"; "+
+                            (inUse.contains(desiredMachine) ? "machine in use" : "machine unknown"));
+                }
+            } else {
+                machine = (T) chooser.apply(a);
+                if (!a.contains(machine)) {
+                    throw new IllegalStateException("Machine chooser attempted to choose '"+machine+"' from outside the available set, in "+this);
+                }
+            }
+            inUse.add(machine);
+            updateMachineConfig(machine, flags);
+        }
+        
+        for (MachineLocationCustomizer customizer : getMachineCustomizers(allflags)) {
+            customizer.customize(machine);
+        }
+        
+        return machine;
+    }
+
+    @Override
+    public void release(T machine) {
+        ConfigBag machineConfig = ((ConfigurationSupportInternal)machine.config()).getBag();
+        for (MachineLocationCustomizer customizer : getMachineCustomizers(machineConfig)) {
+            customizer.preRelease(machine);
+        }
+
+        synchronized (lock) {
+            if (inUse.contains(machine) == false)
+                throw new IllegalStateException("Request to release machine "+machine+", but this machine is not currently allocated");
+            restoreMachineConfig(machine);
+            inUse.remove(machine);
+            
+            if (pendingRemoval.contains(machine)) {
+                removeMachine(machine);
+            }
+        }
+    }
+
+    @Override
+    public Map<String,Object> getProvisioningFlags(Collection<String> tags) {
+        return Maps.<String,Object>newLinkedHashMap();
+    }
+    
+    protected void updateMachineConfig(T machine, Map<?, ?> flags) {
+        if (origConfigs == null) {
+            // For backwards compatibility, where peristed state did not have this.
+            origConfigs = Maps.newLinkedHashMap();
+        }
+        Map<String, Object> strFlags = ConfigBag.newInstance(flags).getAllConfig();
+        Map<String, Object> origConfig = ((ConfigurationSupportInternal)machine.config()).getLocalBag().getAllConfig();
+        origConfigs.put(machine, origConfig);
+        requestPersist();
+        
+        ((ConfigurationSupportInternal)machine.config()).addToLocalBag(strFlags);
+    }
+    
+    protected void restoreMachineConfig(MachineLocation machine) {
+        if (origConfigs == null) {
+            // For backwards compatibility, where peristed state did not have this.
+            origConfigs = Maps.newLinkedHashMap();
+        }
+        Map<String, Object> origConfig = origConfigs.remove(machine);
+        if (origConfig == null) return;
+        requestPersist();
+        
+        Set<String> currentKeys = ((ConfigurationSupportInternal)machine.config()).getLocalBag().getAllConfig().keySet();
+        Set<String> newKeys = Sets.difference(currentKeys, origConfig.entrySet());
+        for (String key : newKeys) {
+            ((ConfigurationSupportInternal)machine.config()).removeFromLocalBag(key);
+        }
+        ((ConfigurationSupportInternal)machine.config()).addToLocalBag(origConfig);
+    }
+    
+    @SuppressWarnings("unchecked")
+    private <K> K getConfigPreferringOverridden(ConfigKey<K> key, Map<?,?> overrides) {
+        K result = (K) overrides.get(key);
+        if (result == null) result = (K) overrides.get(key.getName());
+        if (result == null) result = getConfig(key);
+        return result;
+    }
+
+    protected Collection<MachineLocationCustomizer> getMachineCustomizers(ConfigBag setup) {
+        Collection<MachineLocationCustomizer> customizers = setup.get(MACHINE_LOCATION_CUSTOMIZERS);
+        return (customizers == null ? ImmutableList.<MachineLocationCustomizer>of() : customizers);
+    }
+
+    /**
+     * Facilitates fluent/programmatic style for constructing a fixed pool of machines.
+     * <pre>
+     * {@code
+     *   new FixedListMachineProvisioningLocation.Builder()
+     *           .user("alex")
+     *           .keyFile("/Users/alex/.ssh/id_rsa")
+     *           .addAddress("10.0.0.1")
+     *           .addAddress("10.0.0.2")
+     *           .addAddress("10.0.0.3")
+     *           .addAddressMultipleTimes("me@127.0.0.1", 5)
+     *           .build();
+     * }
+     * </pre>
+     */
+    public static class Builder {
+        LocationManager lm;
+        String user;
+        String privateKeyPassphrase;
+        String privateKeyFile;
+        String privateKeyData;
+        File localTempDir;
+        List machines = Lists.newArrayList();
+
+        public Builder(LocationManager lm) {
+            this.lm = lm;
+        }
+        public Builder user(String user) {
+            this.user = user;
+            return this;
+        }
+        public Builder keyPassphrase(String keyPassphrase) {
+            this.privateKeyPassphrase = keyPassphrase;
+            return this; 
+        }
+        public Builder keyFile(String keyFile) {
+            this.privateKeyFile = keyFile;
+            return this; 
+        }
+        public Builder keyData(String keyData) {
+            this.privateKeyData = keyData;
+            return this;
+        }
+        public Builder localTempDir(File val) {
+            this.localTempDir = val;
+            return this;
+        }
+        /** adds the locations; user and keyfile set in the builder are _not_ applied to the machine
+         * (use add(String address) for that)
+         */
+        public Builder add(SshMachineLocation location) {
+            machines.add(location);
+            return this;
+        }
+        public Builder addAddress(String address) {
+            return addAddresses(address);
+        }
+        public Builder addAddressMultipleTimes(String address, int n) {
+            for (int i=0; i<n; i++)
+                addAddresses(address);
+            return this;
+        }
+        public Builder addAddresses(String address1, String ...others) {
+            List<String> addrs = new ArrayList<String>();
+            addrs.addAll(WildcardGlobs.getGlobsAfterBraceExpansion("{"+address1+"}",
+                    true /* numeric */, /* no quote support though */ PhraseTreatment.NOT_A_SPECIAL_CHAR, PhraseTreatment.NOT_A_SPECIAL_CHAR));
+            for (String address: others) 
+                addrs.addAll(WildcardGlobs.getGlobsAfterBraceExpansion("{"+address+"}",
+                        true /* numeric */, /* no quote support though */ PhraseTreatment.NOT_A_SPECIAL_CHAR, PhraseTreatment.NOT_A_SPECIAL_CHAR));
+            for (String addr: addrs)
+                add(createMachine(addr)); 
+            return this;
+        }
+        protected SshMachineLocation createMachine(String addr) {
+            if (lm==null)
+                return new SshMachineLocation(makeConfig(addr));
+            else
+                return lm.createLocation(makeConfig(addr), SshMachineLocation.class);
+        }
+        private Map makeConfig(String address) {
+            String user = this.user;
+            if (address.contains("@")) {
+                user = address.substring(0, address.indexOf("@"));
+                address = address.substring(address.indexOf("@")+1);
+            }
+            Map config = MutableMap.of("address", address);
+            if (truth(user)) {
+                config.put("user", user);
+                config.put("sshconfig.user", user);
+            }
+            if (truth(privateKeyPassphrase)) config.put("sshconfig.privateKeyPassphrase", privateKeyPassphrase);
+            if (truth(privateKeyFile)) config.put("sshconfig.privateKeyFile", privateKeyFile);
+            if (truth(privateKeyData)) config.put("sshconfig.privateKey", privateKeyData);
+            if (truth(localTempDir)) config.put("localTempDir", localTempDir);
+            return config;
+        }
+        @SuppressWarnings("unchecked")
+        public FixedListMachineProvisioningLocation<SshMachineLocation> build() {
+            if (lm==null)
+                return new FixedListMachineProvisioningLocation<SshMachineLocation>(MutableMap.builder()
+                    .putIfNotNull("machines", machines)
+                    .putIfNotNull("user", user)
+                    .putIfNotNull("privateKeyPassphrase", privateKeyPassphrase)
+                    .putIfNotNull("privateKeyFile", privateKeyFile)
+                    .putIfNotNull("privateKeyData", privateKeyData)
+                    .putIfNotNull("localTempDir", localTempDir)
+                    .build());
+            else
+                return lm.createLocation(MutableMap.builder()
+                    .putIfNotNull("machines", machines)
+                    .putIfNotNull("user", user)
+                    .putIfNotNull("privateKeyPassphrase", privateKeyPassphrase)
+                    .putIfNotNull("privateKeyFile", privateKeyFile)
+                    .putIfNotNull("privateKeyData", privateKeyData)
+                    .putIfNotNull("localTempDir", localTempDir)
+                    .build(), 
+                FixedListMachineProvisioningLocation.class);
+        }        
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/byon/HostLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/byon/HostLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/byon/HostLocationResolver.java
new file mode 100644
index 0000000..55263e2
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/byon/HostLocationResolver.java
@@ -0,0 +1,93 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.byon;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationRegistry;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.location.core.AbstractLocationResolver;
+import org.apache.brooklyn.location.core.LocationConfigUtils;
+import org.apache.brooklyn.location.core.LocationPropertiesFromBrooklynProperties;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.guava.Maybe;
+import org.apache.brooklyn.util.guava.Maybe.Absent;
+import org.apache.brooklyn.util.text.KeyValueParser;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+
+public class HostLocationResolver extends AbstractLocationResolver {
+    
+    private static final String HOST = "host";
+    
+    @SuppressWarnings("rawtypes")
+    @Override
+    public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
+        // Extract args from spec
+        ParsedSpec parsedSpec = specParser.parse(spec);
+        Map<String, String> argsMap = parsedSpec.argsMap;
+        if (argsMap.isEmpty()) {
+            throw new IllegalArgumentException("Invalid host spec (no host supplied): "+spec);
+        } else if (argsMap.size() == 1 && Iterables.get(argsMap.values(), 0) == null) {
+            // only given ip or hostname
+            argsMap = ImmutableMap.of("hosts", Iterables.get(argsMap.keySet(), 0));
+        } else if (!(argsMap.containsKey("host") || argsMap.containsKey("hosts"))) {
+            throw new IllegalArgumentException("Invalid host spec (no host supplied): "+spec);
+        }
+
+        // Find generic applicable properties
+        Map globalProperties = registry.getProperties();
+        String namedLocation = (String) locationFlags.get(LocationInternal.NAMED_SPEC_NAME.getName());
+        Map<String, Object> filteredProperties = new LocationPropertiesFromBrooklynProperties().getLocationProperties(null, namedLocation, globalProperties);
+        ConfigBag flags = ConfigBag.newInstance(locationFlags).putIfAbsent(filteredProperties);
+        flags.remove(LocationInternal.NAMED_SPEC_NAME);
+
+        // Generate target spec
+        String target = "byon("+KeyValueParser.toLine(argsMap)+")";
+        Maybe<Location> testResolve = managementContext.getLocationRegistry().resolve(target, false, null);
+        if (!testResolve.isPresent()) {
+            throw new IllegalArgumentException("Invalid target location '" + target + "' for location '"+HOST+"': "+
+                Exceptions.collapseText( ((Absent<?>)testResolve).getException() ), ((Absent<?>)testResolve).getException());
+        }
+        
+        return managementContext.getLocationManager().createLocation(LocationSpec.create(SingleMachineProvisioningLocation.class)
+                .configure("location", target)
+                .configure("locationFlags", flags.getAllConfig())
+                .configure(LocationConfigUtils.finalAndOriginalSpecs(spec, locationFlags, globalProperties, namedLocation)));
+    }
+    
+    @Override
+    public String getPrefix() {
+        return HOST;
+    }
+    
+    @Override
+    protected Class<? extends Location> getLocationType() {
+        return SingleMachineProvisioningLocation.class;
+    }
+
+    @Override
+    protected SpecParser getSpecParser() {
+        return new SpecParser(getPrefix()).setExampleUsage("\"host(1.1.1.1)\" or \"host(host=1.1.1.1,name=myname)\"");
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/byon/SingleMachineLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/byon/SingleMachineLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/byon/SingleMachineLocationResolver.java
new file mode 100644
index 0000000..6265f5c
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/byon/SingleMachineLocationResolver.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.byon;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationRegistry;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.location.core.AbstractLocationResolver;
+import org.apache.brooklyn.location.core.LocationConfigUtils;
+import org.apache.brooklyn.location.core.LocationPropertiesFromBrooklynProperties;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.guava.Maybe;
+import org.apache.brooklyn.util.guava.Maybe.Absent;
+
+public class SingleMachineLocationResolver extends AbstractLocationResolver {
+    
+    private static final String SINGLE = "single";
+    
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @Override
+    public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
+        ConfigBag config = extractConfig(locationFlags, spec, registry);
+        Map globalProperties = registry.getProperties();
+        String namedLocation = (String) locationFlags.get(LocationInternal.NAMED_SPEC_NAME.getName());
+        
+        if (registry != null) {
+            LocationPropertiesFromBrooklynProperties.setLocalTempDir(globalProperties, config);
+        }
+
+        if (config.getStringKey("target") == null) {
+            throw new IllegalArgumentException("target must be specified in single-machine spec");
+        }
+        String target = config.getStringKey("target").toString();
+        config.remove("target");
+        Maybe<Location> testResolve = managementContext.getLocationRegistry().resolve(target, false, null);
+        if (!testResolve.isPresent()) {
+            throw new IllegalArgumentException("Invalid target location '" + target + "' for location '"+SINGLE+"': "+
+                Exceptions.collapseText( ((Absent<?>)testResolve).getException() ));
+        }
+        
+        return managementContext.getLocationManager().createLocation(LocationSpec.create(SingleMachineProvisioningLocation.class)
+                .configure("location", target)
+                .configure("locationFlags", config.getAllConfig())
+                .configure(LocationConfigUtils.finalAndOriginalSpecs(spec, locationFlags, globalProperties, namedLocation)));
+    }
+    
+    @Override
+    public String getPrefix() {
+        return SINGLE;
+    }
+    
+    @Override
+    protected Class<? extends Location> getLocationType() {
+        return SingleMachineProvisioningLocation.class;
+    }
+
+    @Override
+    protected SpecParser getSpecParser() {
+        return new SpecParser(getPrefix()).setExampleUsage("\"single(target=jclouds:aws-ec2:us-east-1)\"");
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/byon/SingleMachineProvisioningLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/byon/SingleMachineProvisioningLocation.java b/core/src/main/java/org/apache/brooklyn/location/byon/SingleMachineProvisioningLocation.java
new file mode 100644
index 0000000..3338da5
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/byon/SingleMachineProvisioningLocation.java
@@ -0,0 +1,91 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.byon;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.ImmutableMap;
+
+public class SingleMachineProvisioningLocation<T extends MachineLocation> extends FixedListMachineProvisioningLocation<T> {
+    private static final long serialVersionUID = -4216528515792151062L;
+
+    private static final Logger log = LoggerFactory.getLogger(SingleMachineProvisioningLocation.class);
+    
+    @SetFromFlag(nullable=false)
+    private String location;
+    
+    @SetFromFlag(nullable=false)
+    private Map<?,?> locationFlags;
+    
+    private T singleLocation;
+    private int referenceCount;
+    private MachineProvisioningLocation<T> provisioningLocation;
+
+
+    public SingleMachineProvisioningLocation() {
+    }
+
+    @SuppressWarnings("rawtypes")
+    public SingleMachineProvisioningLocation(String location, Map locationFlags) {
+        this.locationFlags = locationFlags;
+        this.location = location;
+    }
+
+    @SuppressWarnings("rawtypes")
+    @Override
+    public synchronized T obtain(Map flags) throws NoMachinesAvailableException {
+        log.info("Flags {} passed to newLocationFromString will be ignored, using {}", flags, locationFlags);
+        return obtain();
+    }
+
+    @Override
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public synchronized T obtain() throws NoMachinesAvailableException {
+        if (singleLocation == null) {
+            if (provisioningLocation == null) {
+                provisioningLocation = (MachineProvisioningLocation) getManagementContext().getLocationRegistry().resolve(
+                    location, locationFlags);
+            }
+            singleLocation = provisioningLocation.obtain(ImmutableMap.of());
+            inUse.add(singleLocation);
+        }
+        referenceCount++;
+        return singleLocation;
+    }
+
+    @Override
+    public synchronized void release(T machine) {
+        if (!machine.equals(singleLocation)) {
+            throw new IllegalArgumentException("Invalid machine " + machine + " passed to release, expecting: " + singleLocation);
+        }
+        if (--referenceCount == 0) {
+            provisioningLocation.release(machine);
+            singleLocation = null;
+        }
+        inUse.remove(machine);
+    };
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/cloud/AbstractCloudMachineProvisioningLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/cloud/AbstractCloudMachineProvisioningLocation.java b/core/src/main/java/org/apache/brooklyn/location/cloud/AbstractCloudMachineProvisioningLocation.java
index d09cadc..6a7dc73 100644
--- a/core/src/main/java/org/apache/brooklyn/location/cloud/AbstractCloudMachineProvisioningLocation.java
+++ b/core/src/main/java/org/apache/brooklyn/location/cloud/AbstractCloudMachineProvisioningLocation.java
@@ -24,7 +24,7 @@ import java.util.Map;
 import org.apache.brooklyn.api.location.LocationSpec;
 import org.apache.brooklyn.api.location.MachineLocation;
 import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.AbstractLocation;
+import org.apache.brooklyn.location.core.AbstractLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 import org.apache.brooklyn.util.core.internal.ssh.SshTool;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/cloud/AvailabilityZoneExtension.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/cloud/AvailabilityZoneExtension.java b/core/src/main/java/org/apache/brooklyn/location/cloud/AvailabilityZoneExtension.java
index 312cb83..c0143ae 100644
--- a/core/src/main/java/org/apache/brooklyn/location/cloud/AvailabilityZoneExtension.java
+++ b/core/src/main/java/org/apache/brooklyn/location/cloud/AvailabilityZoneExtension.java
@@ -22,7 +22,7 @@ import java.util.List;
 
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.entity.group.DynamicCluster;
-import org.apache.brooklyn.location.basic.MultiLocation;
+import org.apache.brooklyn.location.core.MultiLocation;
 
 import com.google.common.annotations.Beta;
 import com.google.common.base.Predicate;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/cloud/CloudLocationConfig.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/cloud/CloudLocationConfig.java b/core/src/main/java/org/apache/brooklyn/location/cloud/CloudLocationConfig.java
index 2bb2d7e..935a96c 100644
--- a/core/src/main/java/org/apache/brooklyn/location/cloud/CloudLocationConfig.java
+++ b/core/src/main/java/org/apache/brooklyn/location/cloud/CloudLocationConfig.java
@@ -27,7 +27,7 @@ import org.apache.brooklyn.api.location.MachineLocationCustomizer;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.BasicConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
 public interface CloudLocationConfig {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/AbstractLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/AbstractLocation.java b/core/src/main/java/org/apache/brooklyn/location/core/AbstractLocation.java
new file mode 100644
index 0000000..026cf87
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/AbstractLocation.java
@@ -0,0 +1,709 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.apache.brooklyn.util.GroovyJavaMethods.elvis;
+import static org.apache.brooklyn.util.JavaGroovyEquivalents.groovyTruth;
+
+import java.io.Closeable;
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.api.mgmt.rebind.RebindSupport;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.LocationMemento;
+import org.apache.brooklyn.api.objs.Configurable;
+import org.apache.brooklyn.config.ConfigInheritance;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.config.ConfigKey.HasConfigKey;
+import org.apache.brooklyn.core.config.BasicConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.internal.BrooklynFeatureEnablement;
+import org.apache.brooklyn.core.internal.storage.BrooklynStorage;
+import org.apache.brooklyn.core.internal.storage.Reference;
+import org.apache.brooklyn.core.internal.storage.impl.BasicReference;
+import org.apache.brooklyn.core.mgmt.internal.LocalLocationManager;
+import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.mgmt.rebind.BasicLocationRebindSupport;
+import org.apache.brooklyn.core.objs.AbstractBrooklynObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.location.core.internal.LocationDynamicType;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
+import org.apache.brooklyn.location.geo.HasHostGeoInfo;
+import org.apache.brooklyn.location.geo.HostGeoInfo;
+import org.apache.brooklyn.util.collections.SetFromLiveMap;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.flags.FlagUtils;
+import org.apache.brooklyn.util.core.flags.TypeCoercions;
+import org.apache.brooklyn.util.guava.Maybe;
+import org.apache.brooklyn.util.stream.Streams;
+
+import com.google.common.base.Objects;
+import com.google.common.base.Objects.ToStringHelper;
+import com.google.common.base.Splitter;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import com.google.common.reflect.TypeToken;
+
+/**
+ * A basic implementation of the {@link Location} interface.
+ *
+ * This provides an implementation which works according to the requirements of
+ * the interface documentation, and is ready to be extended to make more specialized locations.
+ * 
+ * Override {@link #configure(Map)} to add special initialization logic.
+ */
+public abstract class AbstractLocation extends AbstractBrooklynObject implements LocationInternal, HasHostGeoInfo, Configurable {
+    
+    private static final long serialVersionUID = -7495805474138619830L;
+
+    /** @deprecated since 0.7.0 shouldn't be public */
+    @Deprecated
+    public static final Logger LOG = LoggerFactory.getLogger(AbstractLocation.class);
+
+    public static final ConfigKey<Location> PARENT_LOCATION = new BasicConfigKey<Location>(Location.class, "parentLocation");
+
+    public static final ConfigKey<Boolean> TEMPORARY_LOCATION = ConfigKeys.newBooleanConfigKey("temporaryLocation",
+            "Indicates that the location is a temporary location that has been created to test connectivity, and that" +
+            "the location's events should not be recorded by usage listeners", false);
+
+    private final AtomicBoolean configured = new AtomicBoolean();
+    
+    private Reference<Long> creationTimeUtc = new BasicReference<Long>(System.currentTimeMillis());
+    
+    // _not_ set from flag; configured explicitly in configure, because we also need to update the parent's list of children
+    private Reference<Location> parent = new BasicReference<Location>();
+    
+    // NB: all accesses should be synchronized
+    private Set<Location> children = Sets.newLinkedHashSet();
+
+    private Reference<String> name = new BasicReference<String>();
+    private boolean displayNameAutoGenerated = true;
+
+    private Reference<HostGeoInfo> hostGeoInfo = new BasicReference<HostGeoInfo>();
+
+    private BasicConfigurationSupport config = new BasicConfigurationSupport();
+    
+    private ConfigBag configBag = new ConfigBag();
+
+    private volatile boolean managed;
+
+    private boolean inConstruction;
+
+    private Reference<Map<Class<?>, Object>> extensions = new BasicReference<Map<Class<?>, Object>>(Maps.<Class<?>, Object>newConcurrentMap());
+
+    private final LocationDynamicType locationType;
+
+    /**
+     * Construct a new instance of an AbstractLocation.
+     */
+    public AbstractLocation() {
+        this(Maps.newLinkedHashMap());
+    }
+    
+    /**
+     * Construct a new instance of an AbstractLocation.
+     *
+     * The properties map recognizes the following keys:
+     * <ul>
+     * <li>name - a name for the location
+     * <li>parentLocation - the parent {@link Location}
+     * </ul>
+     * 
+     * Other common properties (retrieved via get/findLocationProperty) include:
+     * <ul>
+     * <li>latitude
+     * <li>longitude
+     * <li>displayName
+     * <li>iso3166 - list of iso3166-2 code strings
+     * <li>timeZone
+     * <li>abbreviatedName
+     * </ul>
+     */
+    public AbstractLocation(Map<?,?> properties) {
+        super(properties);
+        inConstruction = true;
+        
+        // When one calls getConfig(key), we want to use the default value specified on *this* location
+        // if it overrides the default config, by using the type object 
+        locationType = new LocationDynamicType(this);
+        
+        if (isLegacyConstruction()) {
+            AbstractBrooklynObject checkWeGetThis = configure(properties);
+            assert this.equals(checkWeGetThis) : this+" configure method does not return itself; returns "+checkWeGetThis+" instead of "+this;
+
+            boolean deferConstructionChecks = (properties.containsKey("deferConstructionChecks") && TypeCoercions.coerce(properties.get("deferConstructionChecks"), Boolean.class));
+            if (!deferConstructionChecks) {
+                FlagUtils.checkRequiredFields(this);
+            }
+        }
+        
+        inConstruction = false;
+    }
+
+    protected void assertNotYetManaged() {
+        if (!inConstruction && Locations.isManaged(this)) {
+            LOG.warn("Configuration being made to {} after deployment; may not be supported in future versions", this);
+        }
+        //throw new IllegalStateException("Cannot set configuration "+key+" on active location "+this)
+    }
+
+    public void setManagementContext(ManagementContextInternal managementContext) {
+        super.setManagementContext(managementContext);
+        if (displayNameAutoGenerated && getId() != null) name.set(getClass().getSimpleName()+":"+getId().substring(0, Math.min(getId().length(),4)));
+
+        if (BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_USE_BROOKLYN_LIVE_OBJECTS_DATAGRID_STORAGE)) {
+            Location oldParent = parent.get();
+            Set<Location> oldChildren = children;
+            Map<String, Object> oldConfig = configBag.getAllConfig();
+            Long oldCreationTimeUtc = creationTimeUtc.get();
+            String oldDisplayName = name.get();
+            HostGeoInfo oldHostGeoInfo = hostGeoInfo.get();
+
+            parent = managementContext.getStorage().getReference(getId()+"-parent");
+            children = SetFromLiveMap.create(managementContext.getStorage().<Location,Boolean>getMap(getId()+"-children"));
+            creationTimeUtc = managementContext.getStorage().getReference(getId()+"-creationTime");
+            hostGeoInfo = managementContext.getStorage().getReference(getId()+"-hostGeoInfo");
+            name = managementContext.getStorage().getReference(getId()+"-displayName");
+
+            // Only override stored defaults if we have actual values. We might be in setManagementContext
+            // because we are reconstituting an existing entity in a new brooklyn management-node (in which
+            // case believe what is already in the storage), or we might be in the middle of creating a new 
+            // entity. Normally for a new entity (using EntitySpec creation approach), this will get called
+            // before setting the parent etc. However, for backwards compatibility we still support some
+            // things calling the entity's constructor directly.
+            if (oldParent != null) parent.set(oldParent);
+            if (oldChildren.size() > 0) children.addAll(oldChildren);
+            if (creationTimeUtc.isNull()) creationTimeUtc.set(oldCreationTimeUtc);
+            if (hostGeoInfo.isNull()) hostGeoInfo.set(oldHostGeoInfo);
+            if (name.isNull()) {
+                name.set(oldDisplayName);
+            } else {
+                displayNameAutoGenerated = false;
+            }
+
+            configBag = ConfigBag.newLiveInstance(managementContext.getStorage().<String,Object>getMap(getId()+"-config"));
+            if (oldConfig.size() > 0) {
+                configBag.putAll(oldConfig);
+            }
+        }
+    }
+
+    /**
+     * @deprecated since 0.7.0; only used for legacy brooklyn types where constructor is called directly;
+     * see overridden method for more info
+     */
+    @SuppressWarnings("serial")
+    @Override
+    @Deprecated
+    public AbstractLocation configure(Map<?,?> properties) {
+        assertNotYetManaged();
+        
+        boolean firstTime = !configured.getAndSet(true);
+            
+        configBag.putAll(properties);
+        
+        if (properties.containsKey(PARENT_LOCATION.getName())) {
+            // need to ensure parent's list of children is also updated
+            setParent(configBag.get(PARENT_LOCATION));
+            
+            // don't include parentLocation in configBag, as breaks rebind
+            configBag.remove(PARENT_LOCATION);
+        }
+
+        // NB: flag-setting done here must also be done in BasicLocationRebindSupport 
+        FlagUtils.setFieldsFromFlagsWithBag(this, properties, configBag, firstTime);
+        FlagUtils.setAllConfigKeys(this, configBag, false);
+
+        if (properties.containsKey("displayName")) {
+            name.set((String) removeIfPossible(properties, "displayName"));
+            displayNameAutoGenerated = false;
+        } else if (properties.containsKey("name")) {
+            name.set((String) removeIfPossible(properties, "name"));
+            displayNameAutoGenerated = false;
+        } else if (isLegacyConstruction()) {
+            name.set(getClass().getSimpleName()+":"+getId().substring(0, Math.min(getId().length(),4)));
+            displayNameAutoGenerated = true;
+        }
+
+        // TODO Explicitly dealing with iso3166 here because want custom splitter rule comma-separated string.
+        // Is there a better way to do it (e.g. more similar to latitude, where configKey+TypeCoercion is enough)?
+        if (groovyTruth(properties.get("iso3166"))) {
+            Object rawCodes = removeIfPossible(properties, "iso3166");
+            Set<String> codes;
+            if (rawCodes instanceof CharSequence) {
+                codes = ImmutableSet.copyOf(Splitter.on(",").trimResults().split((CharSequence)rawCodes));
+            } else {
+                codes = TypeCoercions.coerce(rawCodes, new TypeToken<Set<String>>() {});
+            }
+            configBag.put(LocationConfigKeys.ISO_3166, codes);
+        }
+        
+        return this;
+    }
+
+    // TODO ensure no callers rely on 'remove' semantics, and don't remove;
+    // or perhaps better use a config bag so we know what is used v unused
+    private static Object removeIfPossible(Map<?,?> map, Object key) {
+        try {
+            return map.remove(key);
+        } catch (Exception e) {
+            return map.get(key);
+        }
+    }
+    
+    public boolean isManaged() {
+        return getManagementContext() != null && managed;
+    }
+
+    public void onManagementStarted() {
+        if (displayNameAutoGenerated) name.set(getClass().getSimpleName()+":"+getId().substring(0, Math.min(getId().length(),4)));
+        this.managed = true;
+    }
+    
+    public void onManagementStopped() {
+        this.managed = false;
+        if (getManagementContext().isRunning()) {
+            BrooklynStorage storage = ((ManagementContextInternal)getManagementContext()).getStorage();
+            storage.remove(getId()+"-parent");
+            storage.remove(getId()+"-children");
+            storage.remove(getId()+"-creationTime");
+            storage.remove(getId()+"-hostGeoInfo");
+            storage.remove(getId()+"-displayName");
+            storage.remove(getId()+"-config");
+        }
+    }
+    
+    @Override
+    public String getDisplayName() {
+        return name.get();
+    }
+    
+    protected boolean isDisplayNameAutoGenerated() {
+        return displayNameAutoGenerated;
+    }
+    
+    @Override
+    public Location getParent() {
+        return parent.get();
+    }
+    
+    @Override
+    public Collection<Location> getChildren() {
+        synchronized (children) {
+            return ImmutableList.copyOf(children);
+        }
+    }
+
+    @Override
+    public void setParent(Location newParent) {
+        setParent(newParent, true);
+    }
+    
+    public void setParent(Location newParent, boolean updateChildListParents) {
+        if (newParent == this) {
+            throw new IllegalArgumentException("Location cannot be its own parent: "+this);
+        }
+        if (newParent == parent.get()) {
+            return; // no-op; already have desired parent
+        }
+        
+        if (parent.get() != null) {
+            Location oldParent = parent.get();
+            parent.set(null);
+            if (updateChildListParents)
+                ((AbstractLocation)oldParent).removeChild(this);
+        }
+        // TODO Should we support a location changing parent? The resulting unmanage/manage might cause problems.
+        // The code above suggests we do, but maybe we should warn or throw error, or at least test it!
+        
+        parent.set(newParent);
+        if (newParent != null) {
+            if (updateChildListParents)
+                ((AbstractLocation)newParent).addChild(this);
+        }
+        
+        onChanged();
+    }
+
+    @Override
+    public ConfigurationSupportInternal config() {
+        return config ;
+    }
+
+    private class BasicConfigurationSupport implements ConfigurationSupportInternal {
+
+        @Override
+        public <T> T get(ConfigKey<T> key) {
+            if (hasConfig(key, false)) return getLocalBag().get(key);
+            if (getParent() != null && isInherited(key)) {
+                return getParent().getConfig(key);
+            }
+            
+            // In case this entity class has overridden the given key (e.g. to set default), then retrieve this entity's key
+            // TODO when locations become entities, the duplication of this compared to EntityConfigMap.getConfig will disappear.
+            @SuppressWarnings("unchecked")
+            ConfigKey<T> ownKey = (ConfigKey<T>) elvis(locationType.getConfigKey(key.getName()), key);
+
+            return ownKey.getDefaultValue();
+        }
+
+        @Override
+        public <T> T get(HasConfigKey<T> key) {
+            return get(key.getConfigKey());
+        }
+
+        @Override
+        public <T> T set(ConfigKey<T> key, T val) {
+            T result = configBag.put(key, val);
+            onChanged();
+            return result;
+        }
+
+        @Override
+        public <T> T set(HasConfigKey<T> key, T val) {
+            return set(key.getConfigKey(), val);
+        }
+
+        @Override
+        public <T> T set(ConfigKey<T> key, Task<T> val) {
+            // TODO Support for locations
+            throw new UnsupportedOperationException();
+        }
+
+        @Override
+        public <T> T set(HasConfigKey<T> key, Task<T> val) {
+            // TODO Support for locations
+            throw new UnsupportedOperationException();
+        }
+
+        @Override
+        public ConfigBag getBag() {
+            ConfigBag result = ConfigBag.newInstanceExtending(configBag, ImmutableMap.of());
+            Location p = getParent();
+            if (p!=null) result.putIfAbsent(((LocationInternal)p).config().getBag());
+            return result;
+        }
+
+        @Override
+        public ConfigBag getLocalBag() {
+            return configBag;
+        }
+
+        @Override
+        public Maybe<Object> getRaw(ConfigKey<?> key) {
+            if (hasConfig(key, false)) return Maybe.of(getLocalBag().getStringKey(key.getName()));
+            if (getParent() != null && isInherited(key)) return ((LocationInternal)getParent()).config().getRaw(key);
+            return Maybe.absent();
+        }
+
+        @Override
+        public Maybe<Object> getRaw(HasConfigKey<?> key) {
+            return getRaw(key.getConfigKey());
+        }
+
+        @Override
+        public Maybe<Object> getLocalRaw(ConfigKey<?> key) {
+            if (hasConfig(key, false)) return Maybe.of(getLocalBag().getStringKey(key.getName()));
+            return Maybe.absent();
+        }
+
+        @Override
+        public Maybe<Object> getLocalRaw(HasConfigKey<?> key) {
+            return getLocalRaw(key.getConfigKey());
+        }
+
+        @Override
+        public void addToLocalBag(Map<String, ?> vals) {
+            configBag.putAll(vals);
+        }
+
+        @Override
+        public void removeFromLocalBag(String key) {
+            configBag.remove(key);
+        }
+
+        @Override
+        public void refreshInheritedConfig() {
+            // no-op for location
+        }
+        
+        @Override
+        public void refreshInheritedConfigOfChildren() {
+            // no-op for location
+        }
+        
+        private boolean hasConfig(ConfigKey<?> key, boolean includeInherited) {
+            if (includeInherited && isInherited(key)) {
+                return getBag().containsKey(key);
+            } else {
+                return getLocalBag().containsKey(key);
+            }
+        }
+        
+        private boolean isInherited(ConfigKey<?> key) {
+            ConfigInheritance inheritance = key.getInheritance();
+            if (inheritance==null) inheritance = getDefaultInheritance();
+            return inheritance.isInherited(key, getParent(), AbstractLocation.this);
+        }
+
+        private ConfigInheritance getDefaultInheritance() {
+            return ConfigInheritance.ALWAYS;
+        }
+    }
+    
+    @Override
+    public <T> T getConfig(HasConfigKey<T> key) {
+        return config().get(key);
+    }
+
+    @Override
+    public <T> T getConfig(ConfigKey<T> key) {
+        return config().get(key);
+    }
+
+    @Override
+    @Deprecated
+    public boolean hasConfig(ConfigKey<?> key, boolean includeInherited) {
+        return config.hasConfig(key, includeInherited);
+    }
+
+    @Override
+    @Deprecated
+    public Map<String,Object> getAllConfig(boolean includeInherited) {
+        // TODO Have no information about what to include/exclude inheritance wise.
+        // however few things use getAllConfigBag()
+        ConfigBag bag = (includeInherited ? config().getBag() : config().getLocalBag());
+        return bag.getAllConfig();
+    }
+    
+    @Override
+    @Deprecated
+    public ConfigBag getAllConfigBag() {
+        // TODO see comments in EntityConfigMap and on interface methods. 
+        // here ConfigBag is used exclusively so
+        // we have no information about what to include/exclude inheritance wise.
+        // however few things use getAllConfigBag()
+        return config().getBag();
+    }
+    
+    @Override
+    public ConfigBag getLocalConfigBag() {
+        return config().getLocalBag();
+    }
+
+    /** 
+     * @deprecated since 0.7; use {@link #getLocalConfigBag()}
+     * @since 0.6
+     */
+    @Deprecated
+    public ConfigBag getRawLocalConfigBag() {
+        return config().getLocalBag();
+    }
+    
+    @Override
+    @Deprecated
+    public <T> T setConfig(ConfigKey<T> key, T value) {
+        return config().set(key, value);
+    }
+
+    /**
+     * @since 0.6.0 (?) - use getDisplayName
+     * @deprecated since 0.7.0; use {@link #getDisplayName()}
+     */
+    @Deprecated
+    public void setName(String newName) {
+        setDisplayName(newName);
+    }
+
+    public void setDisplayName(String newName) {
+        name.set(newName);
+        displayNameAutoGenerated = false;
+        onChanged();
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (! (o instanceof Location)) {
+            return false;
+        }
+
+        Location l = (Location) o;
+        return getId().equals(l.getId());
+    }
+
+    @Override
+    public int hashCode() {
+        return getId().hashCode();
+    }
+
+    @Override
+    public boolean containsLocation(Location potentialDescendent) {
+        Location loc = potentialDescendent;
+        while (loc != null) {
+            if (this == loc) return true;
+            loc = loc.getParent();
+        }
+        return false;
+    }
+
+    protected <T extends Location> T addChild(LocationSpec<T> spec) {
+        T child = getManagementContext().getLocationManager().createLocation(spec);
+        addChild(child);
+        return child;
+    }
+    
+    @SuppressWarnings("deprecation")
+    public void addChild(Location child) {
+        // Previously, setParent delegated to addChildLocation and we sometimes ended up with
+        // duplicate entries here. Instead this now uses a similar scheme to 
+        // AbstractLocation.setParent/addChild (with any weaknesses for distribution that such a 
+        // scheme might have...).
+        // 
+        // We continue to use a list to allow identical-looking locations, but they must be different 
+        // instances.
+        
+        synchronized (children) {
+            for (Location contender : children) {
+                if (contender == child) {
+                    // don't re-add; no-op
+                    return;
+                }
+            }
+
+            children.add(child);
+        }
+        
+        if (isManaged()) {
+            if (!getManagementContext().getLocationManager().isManaged(child)) {
+                Locations.manage(child, getManagementContext());
+            }
+        } else if (getManagementContext() != null) {
+            if (((LocalLocationManager)getManagementContext().getLocationManager()).getLocationEvenIfPreManaged(child.getId()) == null) {
+                ((ManagementContextInternal)getManagementContext()).prePreManage(child);
+            }
+        }
+
+        children.add(child);
+        child.setParent(this);
+        
+        onChanged();
+    }
+    
+    public boolean removeChild(Location child) {
+        boolean removed;
+        synchronized (children) {
+            removed = children.remove(child);
+        }
+        if (removed) {
+            if (child instanceof Closeable) {
+                Streams.closeQuietly((Closeable)child);
+            }
+            child.setParent(null);
+            
+            if (isManaged()) {
+                getManagementContext().getLocationManager().unmanage(child);
+            }
+        }
+        onChanged();
+        return removed;
+    }
+
+    protected void onChanged() {
+        // currently changes simply trigger re-persistence; there is no intermediate listener as we do for EntityChangeListener
+        if (isManaged()) {
+            getManagementContext().getRebindManager().getChangeListener().onChanged(this);
+        }
+    }
+
+    /** Default String representation is simplified name of class, together with selected fields. */
+    @Override
+    public String toString() {
+        return string().toString();
+    }
+    
+    @Override
+    public String toVerboseString() {
+        return toString();
+    }
+
+    /** override this, adding to the returned value, to supply additional fields to include in the toString */
+    protected ToStringHelper string() {
+        return Objects.toStringHelper(getClass()).add("id", getId()).add("name", name);
+    }
+    
+    @Override
+    public HostGeoInfo getHostGeoInfo() { return hostGeoInfo.get(); }
+    
+    public void setHostGeoInfo(HostGeoInfo hostGeoInfo) {
+        if (hostGeoInfo!=null) { 
+            this.hostGeoInfo.set(hostGeoInfo);
+            setConfig(LocationConfigKeys.LATITUDE, hostGeoInfo.latitude); 
+            setConfig(LocationConfigKeys.LONGITUDE, hostGeoInfo.longitude); 
+        } 
+    }
+
+    @Override
+    public RebindSupport<LocationMemento> getRebindSupport() {
+        return new BasicLocationRebindSupport(this);
+    }
+    
+    @Override
+    public boolean hasExtension(Class<?> extensionType) {
+        return extensions.get().containsKey(checkNotNull(extensionType, "extensionType"));
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public <T> T getExtension(Class<T> extensionType) {
+        Object extension = extensions.get().get(checkNotNull(extensionType, "extensionType"));
+        if (extension == null) {
+            throw new IllegalArgumentException("No extension of type "+extensionType+" registered for location "+this);
+        }
+        return (T) extension;
+    }
+    
+    @Override
+    public <T> void addExtension(Class<T> extensionType, T extension) {
+        checkNotNull(extensionType, "extensionType");
+        checkNotNull(extension, "extension");
+        checkArgument(extensionType.isInstance(extension), "extension %s does not implement %s", extension, extensionType);
+        extensions.get().put(extensionType, extension);
+    }
+
+    @Override
+    public Map<String, String> toMetadataRecord() {
+        ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
+        if (getDisplayName() != null) builder.put("displayName", getDisplayName());
+        if (getParent() != null && getParent().getDisplayName() != null) {
+            builder.put("parentDisplayName", getParent().getDisplayName());
+        }
+        return builder.build();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/AbstractLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/AbstractLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/core/AbstractLocationResolver.java
new file mode 100644
index 0000000..c7e80bc
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/AbstractLocationResolver.java
@@ -0,0 +1,188 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationRegistry;
+import org.apache.brooklyn.api.location.LocationResolver;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.text.KeyValueParser;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.ImmutableList;
+
+/**
+ * Examples of valid specs:
+ *   <ul>
+ *     <li>byon(hosts=myhost)
+ *     <li>byon(hosts=myhost,myhost2)
+ *     <li>byon(hosts="myhost, myhost2")
+ *     <li>byon(hosts=myhost,myhost2, name=abc)
+ *     <li>byon(hosts="myhost, myhost2", name="my location name")
+ *   </ul>
+ * 
+ * @author aled
+ */
+@SuppressWarnings({"unchecked","rawtypes"})
+public abstract class AbstractLocationResolver implements LocationResolver {
+
+    public static final Logger log = LoggerFactory.getLogger(AbstractLocationResolver.class);
+    
+    protected volatile ManagementContext managementContext;
+
+    protected volatile SpecParser specParser;
+
+    protected abstract Class<? extends Location> getLocationType();
+    
+    protected abstract SpecParser getSpecParser();
+    
+    @Override
+    public void init(ManagementContext managementContext) {
+        this.managementContext = checkNotNull(managementContext, "managementContext");
+        this.specParser = getSpecParser();
+    }
+    
+    @Override
+    public boolean accepts(String spec, LocationRegistry registry) {
+        return BasicLocationRegistry.isResolverPrefixForSpec(this, spec, true);
+    }
+
+    @Override
+    public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
+        ConfigBag config = extractConfig(locationFlags, spec, registry);
+        Map globalProperties = registry.getProperties();
+        String namedLocation = (String) locationFlags.get(LocationInternal.NAMED_SPEC_NAME.getName());
+        
+        if (registry != null) {
+            LocationPropertiesFromBrooklynProperties.setLocalTempDir(globalProperties, config);
+        }
+
+        return managementContext.getLocationManager().createLocation(LocationSpec.create(getLocationType())
+            .configure(config.getAllConfig())
+            .configure(LocationConfigUtils.finalAndOriginalSpecs(spec, locationFlags, globalProperties, namedLocation)));
+    }
+
+    protected ConfigBag extractConfig(Map<?,?> locationFlags, String spec, LocationRegistry registry) {
+        Map globalProperties = registry.getProperties();
+        ParsedSpec parsedSpec = specParser.parse(spec);
+        String namedLocation = (String) locationFlags.get(LocationInternal.NAMED_SPEC_NAME.getName());
+        
+        // prefer args map over location flags
+        Map<String, Object> filteredProperties = getFilteredLocationProperties(getPrefix(), namedLocation, globalProperties);
+        ConfigBag flags = ConfigBag.newInstance(parsedSpec.argsMap).putIfAbsent(locationFlags).putIfAbsent(filteredProperties);
+
+        return flags;
+    }
+    
+    protected Map<String, Object> getFilteredLocationProperties(String provider, String namedLocation, Map<String, ?> globalProperties) {
+        return new LocationPropertiesFromBrooklynProperties().getLocationProperties(getPrefix(), namedLocation, globalProperties);
+    }
+    
+    protected static class ParsedSpec {
+        public final String spec;
+        public final List<String> partsList;
+        public final Map<String,String> argsMap;
+        
+        ParsedSpec(String spec, List<String> partsList, Map<String,String> argsMap) {
+            this.spec = spec;
+            this.partsList = ImmutableList.copyOf(partsList);
+            this.argsMap = Collections.unmodifiableMap(MutableMap.copyOf(argsMap));
+        }
+    }
+    
+    /**
+     * Parses a spec, by default of the general form "prefix:parts1:part2(arg1=val1,arg2=val2)"
+     */
+    protected static class SpecParser {
+        
+        protected final String prefix;
+        protected final Pattern pattern;
+        private String exampleUsage;
+        
+        public SpecParser(String prefix) {
+            this.prefix = prefix;
+            pattern = Pattern.compile("("+prefix+"|"+prefix.toLowerCase()+"|"+prefix.toUpperCase()+")" + "(:)?" + "(\\((.*)\\))?$");
+        }
+        
+        public SpecParser(String prefix, Pattern pattern) {
+            this.prefix = prefix;
+            this.pattern = pattern;
+        }
+        
+        public SpecParser setExampleUsage(String exampleUsage) {
+            this.exampleUsage = exampleUsage;
+            return this;
+        }
+
+        protected String getUsage(String spec) {
+            if (exampleUsage == null) {
+                return "Spec should be in the form "+pattern;
+            } else {
+                return "for example, "+exampleUsage;
+            }
+        }
+        
+        protected void checkParsedSpec(ParsedSpec parsedSpec) {
+            // If someone tries "byon:(),byon:()" as a single spec, we get weird key-values!
+            for (String key : parsedSpec.argsMap.keySet()) {
+                if (key.contains(":") || key.contains("{") || key.contains("}") || key.contains("(") || key.contains(")")) {
+                    throw new IllegalArgumentException("Invalid byon spec: "+parsedSpec.spec+" (key="+key+")");
+                }
+            }
+            String name = parsedSpec.argsMap.get("name");
+            if (parsedSpec.argsMap.containsKey("name") && (name == null || name.isEmpty())) {
+                throw new IllegalArgumentException("Invalid location '"+parsedSpec.spec+"'; if name supplied then value must be non-empty");
+            }
+            String displayName = parsedSpec.argsMap.get("displayName");
+            if (parsedSpec.argsMap.containsKey("displayName") && (displayName == null || displayName.isEmpty())) {
+                throw new IllegalArgumentException("Invalid location '"+parsedSpec.spec+"'; if displayName supplied then value must be non-empty");
+            }
+        }
+        
+        public ParsedSpec parse(String spec) {
+            Matcher matcher = pattern.matcher(spec);
+            if (!matcher.matches()) {
+                throw new IllegalArgumentException("Invalid location '"+spec+"'; "+getUsage(spec));
+            }
+            
+            String argsPart = matcher.group(3);
+            if (argsPart != null && argsPart.startsWith("(") && argsPart.endsWith(")")) {
+                // TODO Hacky; hosts("1.1.1.1") returns argsPart=("1.1.1.1")
+                argsPart = argsPart.substring(1, argsPart.length()-1);
+            }
+            Map<String, String> argsMap = KeyValueParser.parseMap(argsPart);
+            ParsedSpec result = new ParsedSpec(spec, ImmutableList.<String>of(), argsMap);
+            checkParsedSpec(result);
+            return result;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/AggregatingMachineProvisioningLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/AggregatingMachineProvisioningLocation.java b/core/src/main/java/org/apache/brooklyn/location/core/AggregatingMachineProvisioningLocation.java
new file mode 100644
index 0000000..6ea9ec9
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/AggregatingMachineProvisioningLocation.java
@@ -0,0 +1,141 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static com.google.common.base.Preconditions.checkState;
+
+import java.io.Closeable;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.api.location.NoMachinesAvailableException;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+import org.apache.brooklyn.util.stream.Streams;
+
+import com.google.common.base.Objects;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+
+/**
+ * Takes a list of other provisioners, and round-robins across them when obtaining a machine.
+ */
+public class AggregatingMachineProvisioningLocation<T extends MachineLocation> extends AbstractLocation 
+        implements MachineProvisioningLocation<T>, Closeable {
+
+    private static final long serialVersionUID = -8818006672883481775L;
+
+    private Object lock;
+    
+    @SetFromFlag
+    protected List<MachineProvisioningLocation<T>> provisioners;
+    
+    @SetFromFlag
+    protected Map<T, MachineProvisioningLocation<T>> inUse;
+
+    protected final AtomicInteger obtainCounter = new AtomicInteger();
+    
+    public AggregatingMachineProvisioningLocation() {
+        this(Maps.newLinkedHashMap());
+    }
+    
+    public AggregatingMachineProvisioningLocation(Map properties) {
+        super(properties);
+
+        if (isLegacyConstruction()) {
+            init();
+        }
+    }
+
+    @Override
+    public void init() {
+        super.init();
+    }
+    
+    @Override
+    public String toVerboseString() {
+        return Objects.toStringHelper(this).omitNullValues()
+                .add("id", getId()).add("name", getDisplayName())
+                .add("provisioners", provisioners)
+                .toString();
+    }
+
+    @Override
+    public AbstractLocation configure(Map<?,?> properties) {
+        if (lock == null) {
+            lock = new Object();
+            provisioners = Lists.<MachineProvisioningLocation<T>>newArrayList();
+            inUse = Maps.<T, MachineProvisioningLocation<T>>newLinkedHashMap();
+        }
+        return super.configure(properties);
+    }
+    
+    @Override
+    public AggregatingMachineProvisioningLocation<T> newSubLocation(Map<?,?> newFlags) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void close() {
+        for (MachineProvisioningLocation<?> provisioner : provisioners) {
+            if (provisioner instanceof Closeable) {
+                Streams.closeQuietly((Closeable)provisioner);
+            }
+        }
+    }
+    
+    public T obtain() throws NoMachinesAvailableException {
+        return obtain(Maps.<String,Object>newLinkedHashMap());
+    }
+    
+    @Override
+    public T obtain(Map<?,?> flags) throws NoMachinesAvailableException {
+        checkState(provisioners.size() > 0, "no provisioners!");
+        int index = obtainCounter.getAndIncrement();
+        for (int i = 0; i < provisioners.size(); i++) {
+            MachineProvisioningLocation<T> provisioner = provisioners.get(index++ % provisioners.size());
+            try {
+                T machine = provisioner.obtain(flags);
+                inUse.put(machine, provisioner);
+                return machine;
+            } catch (NoMachinesAvailableException e) {
+                // move on; try next
+            }
+        }
+        throw new NoMachinesAvailableException("No machines available in "+toString());
+    }
+
+    @Override
+    public void release(T machine) {
+        MachineProvisioningLocation<T> provisioner = inUse.remove(machine);
+        if (provisioner != null) {
+            provisioner.release(machine);
+        } else {
+            throw new IllegalStateException("Request to release machine "+machine+", but this machine is not currently allocated");
+        }
+    }
+
+    @Override
+    public Map<String,Object> getProvisioningFlags(Collection<String> tags) {
+        return Maps.<String,Object>newLinkedHashMap();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/BasicHardwareDetails.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/BasicHardwareDetails.java b/core/src/main/java/org/apache/brooklyn/location/core/BasicHardwareDetails.java
new file mode 100644
index 0000000..09059ec
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/BasicHardwareDetails.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import javax.annotation.concurrent.Immutable;
+
+import com.google.common.base.Objects;
+
+import org.apache.brooklyn.api.location.HardwareDetails;
+
+@Immutable
+public class BasicHardwareDetails implements HardwareDetails {
+
+    private final Integer cpuCount;
+    private final Integer ram;
+
+    public BasicHardwareDetails(Integer cpuCount, Integer ram) {
+        this.cpuCount = cpuCount;
+        this.ram = ram;
+    }
+
+    @Override
+    public Integer getCpuCount() {
+        return cpuCount;
+    }
+
+    @Override
+    public Integer getRam() {
+        return ram;
+    }
+
+    @Override
+    public String toString() {
+        return Objects.toStringHelper(HardwareDetails.class)
+                .omitNullValues()
+                .add("cpuCount", cpuCount)
+                .add("ram", ram)
+                .toString();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/BasicLocationDefinition.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/BasicLocationDefinition.java b/core/src/main/java/org/apache/brooklyn/location/core/BasicLocationDefinition.java
new file mode 100644
index 0000000..df9c641
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/BasicLocationDefinition.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.location.LocationDefinition;
+import org.apache.brooklyn.util.text.Identifiers;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+
+public class BasicLocationDefinition implements LocationDefinition {
+
+    private final String id;
+    private final String name;
+    private final String spec;
+    private final Map<String,Object> config;
+
+    public BasicLocationDefinition(String name, String spec, Map<String,? extends Object> config) {
+        this(Identifiers.makeRandomId(8), name, spec, config);
+    }
+    
+    public BasicLocationDefinition(String id, String name, String spec, Map<String,? extends Object> config) {      
+        this.id = Preconditions.checkNotNull(id);
+        this.name = name;
+        this.spec = Preconditions.checkNotNull(spec);
+        this.config = config==null ? ImmutableMap.<String, Object>of() : ImmutableMap.<String, Object>copyOf(config);
+    }
+
+    public String getId() {
+        return id;
+    }
+
+    public String getName() {
+        return name;
+    }
+    
+    public String getSpec() {
+        return spec;
+    }
+    
+    @Override
+    public Map<String, Object> getConfig() {
+        return config;
+    }
+    
+    @Override
+    public boolean equals(Object o) {
+        if (this==o) return true;
+        if ((o instanceof LocationDefinition) && id.equals(((LocationDefinition)o).getId())) return true;
+        return false;
+    }
+
+    @Override
+    public int hashCode() {
+        return id.hashCode();
+    }
+
+    @Override
+    public String toString() {
+        return "LocationDefinition{" +
+                "id='" + getId() + '\'' +
+                ", name='" + getName() + '\'' +
+                ", spec='" + getSpec() + '\'' +
+                ", config=" + getConfig() +
+                '}';
+    }
+}


[33/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/BrooklynNodeUpgradeEffectorBody.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/BrooklynNodeUpgradeEffectorBody.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/BrooklynNodeUpgradeEffectorBody.java
deleted file mode 100644
index 9483eee..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/BrooklynNodeUpgradeEffectorBody.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode.effector;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.entity.drivers.DriverDependentEntity;
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.config.MapConfigKey;
-import org.apache.brooklyn.effector.core.EffectorBody;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.apache.brooklyn.entity.core.EntityTasks;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.brooklyn.util.text.Identifiers;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.time.Duration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.basic.SoftwareProcess.StopSoftwareParameters;
-import brooklyn.entity.basic.SoftwareProcess.StopSoftwareParameters.StopMode;
-import brooklyn.entity.brooklynnode.BrooklynCluster;
-import brooklyn.entity.brooklynnode.BrooklynNode;
-import brooklyn.entity.brooklynnode.BrooklynNodeDriver;
-import brooklyn.entity.software.SshEffectorTasks;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Predicates;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.reflect.TypeToken;
-
-@SuppressWarnings("serial")
-/** Upgrades a brooklyn node in-place on the box, 
- * by creating a child brooklyn node and ensuring it can rebind in HOT_STANDBY
- * <p>
- * Requires the target node to have persistence enabled. 
- */
-public class BrooklynNodeUpgradeEffectorBody extends EffectorBody<Void> {
-
-    private static final Logger log = LoggerFactory.getLogger(BrooklynNodeUpgradeEffectorBody.class);
-    
-    public static final ConfigKey<String> DOWNLOAD_URL = BrooklynNode.DOWNLOAD_URL.getConfigKey();
-    public static final ConfigKey<Boolean> DO_DRY_RUN_FIRST = ConfigKeys.newBooleanConfigKey(
-            "doDryRunFirst", "Test rebinding with a temporary instance before stopping the entity for upgrade.", true);
-    public static final ConfigKey<Map<String,Object>> EXTRA_CONFIG = MapConfigKey.builder(new TypeToken<Map<String,Object>>() {})
-        .name("extraConfig")
-        .description("Additional new config to set on the BrooklynNode as part of upgrading")
-        .build();
-
-    public static final Effector<Void> UPGRADE = Effectors.effector(Void.class, "upgrade")
-        .description("Changes the Brooklyn build used to run this node, "
-            + "by spawning a dry-run node then copying the installed files across. "
-            + "This node must be running for persistence for in-place upgrading to work.")
-        .parameter(BrooklynNode.SUGGESTED_VERSION)
-        .parameter(DOWNLOAD_URL)
-        .parameter(DO_DRY_RUN_FIRST)
-        .parameter(EXTRA_CONFIG)
-        .impl(new BrooklynNodeUpgradeEffectorBody()).build();
-    
-    @Override
-    public Void call(ConfigBag parametersO) {
-        if (!isPersistenceModeEnabled(entity())) {
-            // would could try a `forcePersistNow`, but that's sloppy; 
-            // for now, require HA/persistence for upgrading
-            DynamicTasks.queue( Tasks.warning("Check persistence", 
-                new IllegalStateException("Persistence does not appear to be enabled at this cluster. "
-                + "In-place node upgrade will not succeed unless a custom launch script enables it.")) );
-        }
-
-        final ConfigBag parameters = ConfigBag.newInstanceCopying(parametersO);
-
-        /*
-         * all parameters are passed to children, apart from EXTRA_CONFIG
-         * whose value (as a map) is so passed; it provides an easy way to set extra config in the gui.
-         * (IOW a key-value mapping can be passed either inside EXTRA_CONFIG or as a sibling to EXTRA_CONFIG)  
-         */
-        if (parameters.containsKey(EXTRA_CONFIG)) {
-            Map<String, Object> extra = parameters.get(EXTRA_CONFIG);
-            parameters.remove(EXTRA_CONFIG);
-            parameters.putAll(extra);
-        }
-        log.debug(this+" upgrading, using "+parameters);
-        
-        final String bkName;
-        boolean doDryRunFirst = parameters.get(DO_DRY_RUN_FIRST);
-        if(doDryRunFirst) {
-            bkName = dryRunUpdate(parameters);
-        } else {
-            bkName = "direct-"+Identifiers.makeRandomId(4);
-        }
-        
-        // Stop running instance
-        DynamicTasks.queue(Tasks.builder().name("shutdown node")
-                .add(Effectors.invocation(entity(), BrooklynNode.STOP_NODE_BUT_LEAVE_APPS, ImmutableMap.of(StopSoftwareParameters.STOP_MACHINE_MODE, StopMode.NEVER)))
-                .build());
-
-        // backup old files
-        DynamicTasks.queue(Tasks.builder().name("backup old version").body(new Runnable() {
-            @Override
-            public void run() {
-                String runDir = entity().getAttribute(SoftwareProcess.RUN_DIR);
-                String bkDir = Urls.mergePaths(runDir, "..", Urls.getBasename(runDir)+"-backups", bkName);
-                log.debug(this+" storing backup of previous version in "+bkDir);
-                DynamicTasks.queue(SshEffectorTasks.ssh(
-                    "cd "+runDir,
-                    "mkdir -p "+bkDir,
-                    "mv * "+bkDir
-                    // By removing the run dir of the entity we force it to go through
-                    // the customize step again on start and re-generate local-brooklyn.properties.
-                    ).summary("move files"));
-            }
-        }).build());
-        
-        // Reconfigure entity
-        DynamicTasks.queue(Tasks.builder().name("reconfigure").body(new Runnable() {
-            @Override
-            public void run() {
-                DynamicTasks.waitForLast();
-                ((EntityInternal)entity()).setAttribute(SoftwareProcess.INSTALL_DIR, (String)null);
-                entity().setConfig(SoftwareProcess.INSTALL_UNIQUE_LABEL, (String)null);
-                entity().getConfigMap().addToLocalBag(parameters.getAllConfig());
-                entity().setAttribute(BrooklynNode.DOWNLOAD_URL, entity().getConfig(DOWNLOAD_URL));
-
-                // Setting SUGGESTED_VERSION will result in an new empty INSTALL_FOLDER, but clear it
-                // just in case the user specified already installed version.
-                ((BrooklynNodeDriver)((DriverDependentEntity<?>)entity()).getDriver()).clearInstallDir();
-            }
-        }).build());
-        
-        // Start this entity, running the new version.
-        // This will download and install the new dist (if not already done by the dry run node).
-        DynamicTasks.queue(Effectors.invocation(entity(), BrooklynNode.START, ConfigBag.EMPTY));
-
-        return null;
-    }
-
-    private String dryRunUpdate(ConfigBag parameters) {
-        // TODO require entity() node state master or hot standby AND require persistence enabled, or a new 'force_attempt_upgrade' parameter to be applied
-        // TODO could have a 'skip_dry_run_upgrade' parameter
-        // TODO could support 'dry_run_only' parameter, with optional resumption tasks (eg new dynamic effector)
-
-        // 1 add new brooklyn version entity as child (so uses same machine), with same config apart from things in parameters
-        final Entity dryRunChild = entity().addChild(createDryRunSpec()
-            .displayName("Upgraded Version Dry-Run Node")
-            // install dir and label are recomputed because they are not inherited, and download_url will normally be different
-            .configure(parameters.getAllConfig()));
-
-        //force this to start as hot-standby
-        // TODO alternatively could use REST API as in BrooklynClusterUpgradeEffectorBody
-        String launchParameters = dryRunChild.getConfig(BrooklynNode.EXTRA_LAUNCH_PARAMETERS);
-        if (Strings.isBlank(launchParameters)) launchParameters = "";
-        else launchParameters += " ";
-        launchParameters += "--highAvailability "+HighAvailabilityMode.HOT_STANDBY;
-        ((EntityInternal)dryRunChild).setConfig(BrooklynNode.EXTRA_LAUNCH_PARAMETERS, launchParameters);
-
-        Entities.manage(dryRunChild);
-        final String dryRunNodeUid = dryRunChild.getId();
-        ((EntityInternal)dryRunChild).setDisplayName("Dry-Run Upgraded Brooklyn Node ("+dryRunNodeUid+")");
-
-        DynamicTasks.queue(Effectors.invocation(dryRunChild, BrooklynNode.START, ConfigBag.EMPTY));
-
-        // 2 confirm hot standby status
-        DynamicTasks.queue(EntityTasks.requiringAttributeEventually(dryRunChild, BrooklynNode.MANAGEMENT_NODE_STATE, 
-            Predicates.equalTo(ManagementNodeState.HOT_STANDBY), Duration.FIVE_MINUTES));
-
-        // 3 stop new version
-        DynamicTasks.queue(Tasks.builder().name("shutdown transient node")
-            .add(Effectors.invocation(dryRunChild, BrooklynNode.STOP_NODE_BUT_LEAVE_APPS, ImmutableMap.of(StopSoftwareParameters.STOP_MACHINE_MODE, StopMode.NEVER)))
-            .build());
-
-        DynamicTasks.queue(Tasks.<Void>builder().name("remove transient node").body(
-            new Runnable() {
-                @Override
-                public void run() {
-                    Entities.unmanage(dryRunChild);
-                }
-            }
-        ).build());
-
-        return dryRunChild.getId();
-    }
-
-    protected EntitySpec<? extends BrooklynNode> createDryRunSpec() {
-        return EntitySpec.create(BrooklynNode.class);
-    }
-
-    @Beta
-    static boolean isPersistenceModeEnabled(Entity entity) {
-        // TODO when there are PERSIST* options in BrooklynNode, look at them here!
-        // or, even better, make a REST call to check persistence
-        String params = null;
-        if (entity instanceof BrooklynCluster) {
-            EntitySpec<?> spec = entity.getConfig(BrooklynCluster.MEMBER_SPEC);
-            params = Strings.toString( spec.getConfig().get(BrooklynNode.EXTRA_LAUNCH_PARAMETERS) );
-        }
-        if (params==null) params = entity.getConfig(BrooklynNode.EXTRA_LAUNCH_PARAMETERS);
-        if (params==null) return false;
-        if (params.indexOf("persist")==0) return false;
-        return true;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/SelectMasterEffectorBody.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/SelectMasterEffectorBody.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/SelectMasterEffectorBody.java
deleted file mode 100644
index 92b46b2..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/SelectMasterEffectorBody.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode.effector;
-
-import java.util.NoSuchElementException;
-import java.util.concurrent.Callable;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.Group;
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
-import org.apache.brooklyn.effector.core.EffectorBody;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.entity.core.EntityPredicates;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.repeat.Repeater;
-import org.apache.brooklyn.util.time.Duration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.brooklynnode.BrooklynCluster;
-import brooklyn.entity.brooklynnode.BrooklynCluster.SelectMasterEffector;
-import brooklyn.entity.brooklynnode.BrooklynNode;
-import brooklyn.entity.brooklynnode.BrooklynNode.SetHighAvailabilityModeEffector;
-import brooklyn.entity.brooklynnode.BrooklynNode.SetHighAvailabilityPriorityEffector;
-
-import com.google.common.base.Preconditions;
-import com.google.common.base.Objects;
-import com.google.common.collect.Iterables;
-
-public class SelectMasterEffectorBody extends EffectorBody<Void> implements SelectMasterEffector {
-    public static final Effector<Void> SELECT_MASTER = Effectors.effector(SelectMasterEffector.SELECT_MASTER).impl(new SelectMasterEffectorBody()).build();
-    
-    private static final Logger LOG = LoggerFactory.getLogger(SelectMasterEffectorBody.class);
-
-    private static final int HA_STANDBY_PRIORITY = 0;
-    private static final int HA_MASTER_PRIORITY = 1;
-
-    private AtomicBoolean selectMasterInProgress = new AtomicBoolean();
-
-    @Override
-    public Void call(ConfigBag parameters) {
-        if (!selectMasterInProgress.compareAndSet(false, true)) {
-            throw new IllegalStateException("A master change is already in progress.");
-        }
-
-        try {
-            selectMaster(parameters);
-        } finally {
-            selectMasterInProgress.set(false);
-        }
-        return null;
-    }
-
-    private void selectMaster(ConfigBag parameters) {
-        String newMasterId = parameters.get(NEW_MASTER_ID);
-        Preconditions.checkNotNull(newMasterId, NEW_MASTER_ID.getName() + " parameter is required");
-
-        final Entity oldMaster = entity().getAttribute(BrooklynCluster.MASTER_NODE);
-        if (oldMaster != null && oldMaster.getId().equals(newMasterId)) {
-            LOG.info(newMasterId + " is already the current master, no change needed.");
-            return;
-        }
-
-        final Entity newMaster = getMember(newMasterId);
-
-        //1. Increase the priority of the node we wish to become master
-        toggleNodePriority(newMaster, HA_MASTER_PRIORITY);
-
-        //2. Demote the existing master so a new election takes place
-        try {
-            // this allows the finally block to run even on failure
-            DynamicTasks.swallowChildrenFailures();
-            
-            if (oldMaster != null) {
-                demoteOldMaster(oldMaster, HighAvailabilityMode.HOT_STANDBY);
-            }
-
-            waitMasterHandover(oldMaster, newMaster);
-        } finally { 
-            //3. Revert the priority of the node once it has become master
-            toggleNodePriority(newMaster, HA_STANDBY_PRIORITY);
-        }
-
-        checkMasterSelected(newMaster);
-    }
-
-    private void waitMasterHandover(final Entity oldMaster, final Entity newMaster) {
-        boolean masterChanged = Repeater.create()
-            .backoff(Repeater.DEFAULT_REAL_QUICK_PERIOD, 1.5, Duration.FIVE_SECONDS)
-            .limitTimeTo(Duration.ONE_MINUTE)
-            .until(new Callable<Boolean>() {
-                @Override
-                public Boolean call() throws Exception {
-                    Entity master = getMasterNode();
-                    return !Objects.equal(master, oldMaster) && master != null;
-                }
-            })
-            .run();
-        if (!masterChanged) {
-            LOG.warn("Timeout waiting for node to become master: " + newMaster + ".");
-        }
-    }
-
-    private void demoteOldMaster(Entity oldMaster, HighAvailabilityMode mode) {
-        ManagementNodeState oldState = DynamicTasks.queue(
-                Effectors.invocation(
-                        oldMaster,
-                        BrooklynNode.SET_HIGH_AVAILABILITY_MODE,
-                        MutableMap.of(SetHighAvailabilityModeEffector.MODE, mode))
-            ).asTask().getUnchecked();
-
-        if (oldState != ManagementNodeState.MASTER) {
-            LOG.warn("The previous HA state on node " + oldMaster.getId() + " was " + oldState +
-                    ", while the expected value is " + ManagementNodeState.MASTER + ".");
-        }
-    }
-
-    private void toggleNodePriority(Entity node, int newPriority) {
-        Integer oldPriority = DynamicTasks.queue(
-                Effectors.invocation(
-                    node,
-                    BrooklynNode.SET_HIGH_AVAILABILITY_PRIORITY,
-                    MutableMap.of(SetHighAvailabilityPriorityEffector.PRIORITY, newPriority))
-            ).asTask().getUnchecked();
-
-        Integer expectedPriority = (newPriority == HA_MASTER_PRIORITY ? HA_STANDBY_PRIORITY : HA_MASTER_PRIORITY);
-        if (oldPriority != expectedPriority) {
-            LOG.warn("The previous HA priority on node " + node.getId() + " was " + oldPriority +
-                    ", while the expected value is " + expectedPriority + " (while setting priority " +
-                    newPriority + ").");
-        }
-    }
-
-    private void checkMasterSelected(Entity newMaster) {
-        Entity actualMaster = getMasterNode();
-        if (actualMaster != newMaster) {
-            throw new IllegalStateException("Expected node " + newMaster + " to be master, but found that " +
-                    "master is " + actualMaster + " instead.");
-        }
-    }
-
-    private Entity getMember(String memberId) {
-        Group cluster = (Group)entity();
-        try {
-            return Iterables.find(cluster.getMembers(), EntityPredicates.idEqualTo(memberId));
-        } catch (NoSuchElementException e) {
-            throw new IllegalStateException(memberId + " is not an ID of brooklyn node in this cluster");
-        }
-    }
-
-    private Entity getMasterNode() {
-        return entity().getAttribute(BrooklynCluster.MASTER_NODE);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/SetHighAvailabilityModeEffectorBody.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/SetHighAvailabilityModeEffectorBody.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/SetHighAvailabilityModeEffectorBody.java
deleted file mode 100644
index 00d9a7a..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/SetHighAvailabilityModeEffectorBody.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode.effector;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
-import org.apache.brooklyn.effector.core.EffectorBody;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.sensor.feed.http.HttpValueFunctions;
-import org.apache.brooklyn.sensor.feed.http.JsonFunctions;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.http.HttpToolResponse;
-import org.apache.brooklyn.util.guava.Functionals;
-import org.apache.brooklyn.util.javalang.Enums;
-import org.apache.http.HttpStatus;
-
-import brooklyn.entity.brooklynnode.BrooklynNode;
-import brooklyn.entity.brooklynnode.BrooklynNode.SetHighAvailabilityModeEffector;
-import brooklyn.entity.brooklynnode.EntityHttpClient;
-
-import com.google.common.base.Preconditions;
-import com.google.common.base.Function;
-import com.google.common.collect.ImmutableMap;
-
-public class SetHighAvailabilityModeEffectorBody extends EffectorBody<ManagementNodeState> implements SetHighAvailabilityModeEffector {
-    public static final Effector<ManagementNodeState> SET_HIGH_AVAILABILITY_MODE = Effectors.effector(SetHighAvailabilityModeEffector.SET_HIGH_AVAILABILITY_MODE).impl(new SetHighAvailabilityModeEffectorBody()).build();
-
-    @Override
-    public ManagementNodeState call(ConfigBag parameters) {
-        HighAvailabilityMode mode = parameters.get(MODE);
-        Preconditions.checkNotNull(mode, MODE.getName() + " parameter is required");
-
-        EntityHttpClient httpClient = ((BrooklynNode)entity()).http();
-        HttpToolResponse resp = httpClient.post("/v1/server/ha/state", 
-                ImmutableMap.of("Brooklyn-Allow-Non-Master-Access", "true"),
-                ImmutableMap.of("mode", mode.toString()));
-
-        if (resp.getResponseCode() == HttpStatus.SC_OK) {
-            Function<HttpToolResponse, ManagementNodeState> parseRespone = Functionals.chain(
-                    Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.cast(String.class)),
-                    Enums.fromStringFunction(ManagementNodeState.class));
-            return parseRespone.apply(resp);
-        } else {
-            throw new IllegalStateException("Unexpected response code: " + resp.getResponseCode() + "\n" + resp.getContentAsString());
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/SetHighAvailabilityPriorityEffectorBody.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/SetHighAvailabilityPriorityEffectorBody.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/SetHighAvailabilityPriorityEffectorBody.java
deleted file mode 100644
index 73639e5..0000000
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/effector/SetHighAvailabilityPriorityEffectorBody.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.brooklynnode.effector;
-
-import org.apache.brooklyn.api.effector.Effector;
-import org.apache.brooklyn.effector.core.EffectorBody;
-import org.apache.brooklyn.effector.core.Effectors;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.http.HttpToolResponse;
-import org.apache.http.HttpStatus;
-
-import brooklyn.entity.brooklynnode.BrooklynNode;
-import brooklyn.entity.brooklynnode.BrooklynNode.SetHighAvailabilityPriorityEffector;
-import brooklyn.entity.brooklynnode.EntityHttpClient;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableMap;
-
-public class SetHighAvailabilityPriorityEffectorBody extends EffectorBody<Integer> implements SetHighAvailabilityPriorityEffector {
-    public static final Effector<Integer> SET_HIGH_AVAILABILITY_PRIORITY = Effectors.effector(SetHighAvailabilityPriorityEffector.SET_HIGH_AVAILABILITY_PRIORITY).impl(new SetHighAvailabilityPriorityEffectorBody()).build();
-
-    @Override
-    public Integer call(ConfigBag parameters) {
-        Integer priority = parameters.get(PRIORITY);
-        Preconditions.checkNotNull(priority, PRIORITY.getName() + " parameter is required");
-
-        EntityHttpClient httpClient = ((BrooklynNode)entity()).http();
-        HttpToolResponse resp = httpClient.post("/v1/server/ha/priority",
-            ImmutableMap.of("Brooklyn-Allow-Non-Master-Access", "true"),
-            ImmutableMap.of("priority", priority.toString()));
-
-        if (resp.getResponseCode() == HttpStatus.SC_OK) {
-            return Integer.valueOf(resp.getContentAsString());
-        } else {
-            throw new IllegalStateException("Unexpected response code: " + resp.getResponseCode() + "\n" + resp.getContentAsString());
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/chef/ChefAttributeFeed.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/chef/ChefAttributeFeed.java b/software/base/src/main/java/brooklyn/entity/chef/ChefAttributeFeed.java
deleted file mode 100644
index 00c5c20..0000000
--- a/software/base/src/main/java/brooklyn/entity/chef/ChefAttributeFeed.java
+++ /dev/null
@@ -1,410 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.mgmt.ExecutionContext;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.apache.brooklyn.sensor.feed.AbstractFeed;
-import org.apache.brooklyn.sensor.feed.PollHandler;
-import org.apache.brooklyn.sensor.feed.Poller;
-import org.apache.brooklyn.sensor.feed.ssh.SshPollValue;
-import org.apache.brooklyn.util.core.flags.TypeCoercions;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.apache.brooklyn.util.time.Duration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Joiner;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Splitter;
-import com.google.common.base.Strings;
-import com.google.common.base.Throwables;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-import com.google.common.reflect.TypeToken;
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-
-/**
- * A sensor feed that retrieves attributes from Chef server and converts selected attributes to sensors.
- *
- * <p>To use this feed, you must provide the entity, the name of the node as it is known to Chef, and a collection of attribute
- * sensors. The attribute sensors must follow the naming convention of starting with the string <tt>chef.attribute.</tt>
- * followed by a period-separated path through the Chef attribute hierarchy. For example, an attribute sensor named
- * <tt>chef.attribute.sql_server.instance_name</tt> would cause the feed to search for a Chef attribute called
- * <tt>sql_server</tt>, and within that an attribute <tt>instance_name</tt>, and set the sensor to the value of this
- * attribute.</p>
- *
- * <p>This feed uses the <tt>knife</tt> tool to query all the attributes on a named node. It then iterates over the configured
- * list of attribute sensors, using the sensor name to locate an equivalent Chef attribute. The sensor is then set to the value
- * of the Chef attribute.</p>
- *
- * <p>Example:</p>
- *
- * {@code
- * @Override
- * protected void connectSensors() {
- *     nodeAttributesFeed = ChefAttributeFeed.newFeed(this, nodeName, new AttributeSensor[]{
- *             SqlServerNode.CHEF_ATTRIBUTE_NODE_NAME,
- *             SqlServerNode.CHEF_ATTRIBUTE_SQL_SERVER_INSTANCE_NAME,
- *             SqlServerNode.CHEF_ATTRIBUTE_SQL_SERVER_PORT,
- *             SqlServerNode.CHEF_ATTRIBUTE_SQL_SERVER_SA_PASSWORD
- *     });
- * }
- * }
- *
- * @since 0.6.0
- * @author richardcloudsoft
- */
-public class ChefAttributeFeed extends AbstractFeed {
-
-    private static final Logger log = LoggerFactory.getLogger(ChefAttributeFeed.class);
-
-    /**
-     * Prefix for attribute sensor names.
-     */
-    public static final String CHEF_ATTRIBUTE_PREFIX = "chef.attribute.";
-
-    @SuppressWarnings("serial")
-    public static final ConfigKey<Set<ChefAttributePollConfig<?>>> POLLS = ConfigKeys.newConfigKey(
-            new TypeToken<Set<ChefAttributePollConfig<?>>>() {},
-            "polls");
-
-    public static final ConfigKey<String> NODE_NAME = ConfigKeys.newStringConfigKey("nodeName");
-    
-    public static Builder builder() {
-        return new Builder();
-    }
-
-    @SuppressWarnings("rawtypes")
-    public static class Builder {
-        private EntityLocal entity;
-        private boolean onlyIfServiceUp = false;
-        private String nodeName;
-        private Set<ChefAttributePollConfig> polls = Sets.newLinkedHashSet();
-        private Duration period = Duration.of(30, TimeUnit.SECONDS);
-        private String uniqueTag;
-        private volatile boolean built;
-
-        public Builder entity(EntityLocal val) {
-            this.entity = checkNotNull(val, "entity");
-            return this;
-        }
-        public Builder onlyIfServiceUp() { return onlyIfServiceUp(true); }
-        public Builder onlyIfServiceUp(boolean onlyIfServiceUp) { 
-            this.onlyIfServiceUp = onlyIfServiceUp; 
-            return this; 
-        }
-        public Builder nodeName(String nodeName) {
-            this.nodeName = checkNotNull(nodeName, "nodeName");
-            return this;
-        }
-        public Builder addSensor(ChefAttributePollConfig config) {
-            polls.add(config);
-            return this;
-        }
-        @SuppressWarnings("unchecked")
-        public Builder addSensor(String chefAttributePath, AttributeSensor sensor) {
-            return addSensor(new ChefAttributePollConfig(sensor).chefAttributePath(chefAttributePath));
-        }
-        public Builder addSensors(Map<String, AttributeSensor> sensors) {
-            for (Map.Entry<String, AttributeSensor> entry : sensors.entrySet()) {
-                addSensor(entry.getKey(), entry.getValue());
-            }
-            return this;
-        }
-        public Builder addSensors(AttributeSensor[] sensors) {
-            return addSensors(Arrays.asList(checkNotNull(sensors, "sensors")));
-        }
-        public Builder addSensors(Iterable<AttributeSensor> sensors) {
-            for(AttributeSensor sensor : checkNotNull(sensors, "sensors")) {
-                checkNotNull(sensor, "sensors collection contains a null value");
-                checkArgument(sensor.getName().startsWith(CHEF_ATTRIBUTE_PREFIX), "sensor name must be prefixed "+CHEF_ATTRIBUTE_PREFIX+" for autodetection to work");
-                addSensor(sensor.getName().substring(CHEF_ATTRIBUTE_PREFIX.length()), sensor);
-            }
-            return this;
-        }
-        public Builder period(Duration period) {
-            this.period = period;
-            return this;
-        }
-        public Builder period(long millis) {
-            return period(Duration.of(millis, TimeUnit.MILLISECONDS));
-        }
-        public Builder period(long val, TimeUnit units) {
-            return period(Duration.of(val, units));
-        }
-        public Builder uniqueTag(String uniqueTag) {
-            this.uniqueTag = uniqueTag;
-            return this;
-        }
-        public ChefAttributeFeed build() {
-            built = true;
-            ChefAttributeFeed result = new ChefAttributeFeed(this);
-            result.setEntity(checkNotNull(entity, "entity"));
-            result.start();
-            return result;
-        }
-        @Override
-        protected void finalize() {
-            if (!built) log.warn("SshFeed.Builder created, but build() never called");
-        }
-    }
-
-    private KnifeTaskFactory<String> knifeTaskFactory;
-
-    /**
-     * For rebind; do not call directly; use builder
-     */
-    public ChefAttributeFeed() {
-    }
-    
-    protected ChefAttributeFeed(Builder builder) {
-        setConfig(ONLY_IF_SERVICE_UP, builder.onlyIfServiceUp);
-        setConfig(NODE_NAME, checkNotNull(builder.nodeName, "builder.nodeName"));
-
-        Set<ChefAttributePollConfig<?>> polls = Sets.newLinkedHashSet();
-        for (ChefAttributePollConfig<?> config : builder.polls) {
-            if (!config.isEnabled()) continue;
-            @SuppressWarnings({ "unchecked", "rawtypes" })
-            ChefAttributePollConfig<?> configCopy = new ChefAttributePollConfig(config);
-            if (configCopy.getPeriod() < 0) configCopy.period(builder.period);
-            polls.add(configCopy);
-        }
-        setConfig(POLLS, polls);
-        initUniqueTag(builder.uniqueTag, polls);
-    }
-
-    @Override
-    protected void preStart() {
-        final String nodeName = getConfig(NODE_NAME);
-        final Set<ChefAttributePollConfig<?>> polls = getConfig(POLLS);
-        
-        long minPeriod = Integer.MAX_VALUE;
-        for (ChefAttributePollConfig<?> config : polls) {
-            minPeriod = Math.min(minPeriod, config.getPeriod());
-        }
-
-        knifeTaskFactory = new KnifeNodeAttributeQueryTaskFactory(nodeName);
-        
-        final Callable<SshPollValue> getAttributesFromKnife = new Callable<SshPollValue>() {
-            public SshPollValue call() throws Exception {
-                ProcessTaskWrapper<String> taskWrapper = knifeTaskFactory.newTask();
-                final ExecutionContext executionContext = ((EntityInternal) entity).getManagementSupport().getExecutionContext();
-                log.debug("START: Running knife to query attributes of Chef node {}", nodeName);
-                executionContext.submit(taskWrapper);
-                taskWrapper.block();
-                log.debug("DONE:  Running knife to query attributes of Chef node {}", nodeName);
-                return new SshPollValue(null, taskWrapper.getExitCode(), taskWrapper.getStdout(), taskWrapper.getStderr());
-            }
-        };
-
-        getPoller().scheduleAtFixedRate(
-                new CallInEntityExecutionContext<SshPollValue>(entity, getAttributesFromKnife),
-                new SendChefAttributesToSensors(entity, polls),
-                minPeriod);
-    }
-
-    @SuppressWarnings("unchecked")
-    protected Poller<SshPollValue> getPoller() {
-        return (Poller<SshPollValue>) super.getPoller();
-    }
-
-    /**
-     * An implementation of {@link KnifeTaskFactory} that queries for the attributes of a node.
-     */
-    private static class KnifeNodeAttributeQueryTaskFactory extends KnifeTaskFactory<String> {
-        private final String nodeName;
-
-        public KnifeNodeAttributeQueryTaskFactory(String nodeName) {
-            super("retrieve attributes of node " + nodeName);
-            this.nodeName = nodeName;
-        }
-
-        @Override
-        protected List<String> initialKnifeParameters() {
-            return ImmutableList.of("node", "show", "-l", nodeName, "--format", "json");
-        }
-    }
-
-    /**
-     * A {@link Callable} that wraps another {@link Callable}, where the inner {@link Callable} is executed in the context of a
-     * specific entity.
-     *
-     * @param <T> The type of the {@link Callable}.
-     */
-    private static class CallInEntityExecutionContext<T> implements Callable<T> {
-
-        private final Callable<T> job;
-        private EntityLocal entity;
-
-        private CallInEntityExecutionContext(EntityLocal entity, Callable<T> job) {
-            this.job = job;
-            this.entity = entity;
-        }
-
-        @Override
-        public T call() throws Exception {
-            final ExecutionContext executionContext = ((EntityInternal) entity).getManagementSupport().getExecutionContext();
-            return executionContext.submit(Maps.newHashMap(), job).get();
-        }
-    }
-
-    /**
-     * A poll handler that takes the result of the <tt>knife</tt> invocation and sets the appropriate sensors.
-     */
-    private static class SendChefAttributesToSensors implements PollHandler<SshPollValue> {
-        private static final Iterable<String> PREFIXES = ImmutableList.of("", "automatic", "force_override", "override", "normal", "force_default", "default");
-        private static final Splitter SPLITTER = Splitter.on('.');
-
-        private final EntityLocal entity;
-        private final Map<String, AttributeSensor<?>> chefAttributeSensors;
-
-        public SendChefAttributesToSensors(EntityLocal entity, Set<ChefAttributePollConfig<?>> polls) {
-            this.entity = entity;
-            chefAttributeSensors = Maps.newLinkedHashMap();
-            for (ChefAttributePollConfig<?> config : polls) {
-                chefAttributeSensors.put(config.getChefAttributePath(), config.getSensor());
-            }
-        }
-
-        @Override
-        public boolean checkSuccess(SshPollValue val) {
-            if (val.getExitStatus() != 0) return false;
-            String stderr = val.getStderr();
-            if (stderr == null || stderr.length() != 0) return false;
-            String out = val.getStdout();
-            if (out == null || out.length() == 0) return false;
-            if (!out.contains("{")) return false;
-            return true;
-        }
-
-        @SuppressWarnings({ "unchecked", "rawtypes" })
-        @Override
-        public void onSuccess(SshPollValue val) {
-            String stdout = val.getStdout();
-            int jsonStarts = stdout.indexOf('{');
-            if (jsonStarts > 0)
-                stdout = stdout.substring(jsonStarts);
-            JsonElement jsonElement = new Gson().fromJson(stdout, JsonElement.class);
-
-            for (Map.Entry<String, AttributeSensor<?>> attribute : chefAttributeSensors.entrySet()) {
-                String chefAttributeName = attribute.getKey();
-                AttributeSensor<?> sensor = attribute.getValue();
-                log.trace("Finding value for attribute sensor " + sensor.getName());
-
-                Iterable<String> path = SPLITTER.split(chefAttributeName);
-                JsonElement elementForSensor = null;
-                for(String prefix : PREFIXES) {
-                    Iterable<String> prefixedPath = !Strings.isNullOrEmpty(prefix)
-                            ? Iterables.concat(ImmutableList.of(prefix), path)
-                            : path;
-                    try {
-                        elementForSensor = getElementByPath(jsonElement.getAsJsonObject(), prefixedPath);
-                    } catch(IllegalArgumentException e) {
-                        log.error("Entity {}: bad Chef attribute {} for sensor {}: {}", new Object[]{
-                                entity.getDisplayName(),
-                                Joiner.on('.').join(prefixedPath),
-                                sensor.getName(),
-                                e.getMessage()});
-                        throw Throwables.propagate(e);
-                    }
-                    if (elementForSensor != null) {
-                        log.debug("Entity {}: apply Chef attribute {} to sensor {} with value {}", new Object[]{
-                                entity.getDisplayName(),
-                                Joiner.on('.').join(prefixedPath),
-                                sensor.getName(),
-                                elementForSensor.getAsString()});
-                        break;
-                    }
-                }
-                if (elementForSensor != null) {
-                    entity.setAttribute((AttributeSensor)sensor, TypeCoercions.coerce(elementForSensor.getAsString(), sensor.getTypeToken()));
-                } else {
-                    log.debug("Entity {}: no Chef attribute matching {}; setting sensor {} to null", new Object[]{
-                            entity.getDisplayName(),
-                            chefAttributeName,
-                            sensor.getName()});
-                    entity.setAttribute(sensor, null);
-                }
-            }
-        }
-
-        private JsonElement getElementByPath(JsonElement element, Iterable<String> path) {
-            if (Iterables.isEmpty(path)) {
-                return element;
-            } else {
-                String head = Iterables.getFirst(path, null);
-                Preconditions.checkArgument(!Strings.isNullOrEmpty(head), "path must not contain empty or null elements");
-                Iterable<String> tail = Iterables.skip(path, 1);
-                JsonElement child = ((JsonObject) element).get(head);
-                return child != null
-                        ? getElementByPath(child, tail)
-                        : null;
-            }
-        }
-
-        @Override
-        public void onFailure(SshPollValue val) {
-            log.error("Chef attribute query did not respond as expected. exitcode={} stdout={} stderr={}", new Object[]{val.getExitStatus(), val.getStdout(), val.getStderr()});
-            for (AttributeSensor<?> attribute : chefAttributeSensors.values()) {
-                if (!attribute.getName().startsWith(CHEF_ATTRIBUTE_PREFIX))
-                    continue;
-                entity.setAttribute(attribute, null);
-            }
-        }
-
-        @Override
-        public void onException(Exception exception) {
-            log.error("Detected exception while retrieving Chef attributes from entity " + entity.getDisplayName(), exception);
-            for (AttributeSensor<?> attribute : chefAttributeSensors.values()) {
-                if (!attribute.getName().startsWith(CHEF_ATTRIBUTE_PREFIX))
-                    continue;
-                entity.setAttribute(attribute, null);
-            }
-        }
-        
-        @Override
-        public String toString() {
-            return super.toString()+"["+getDescription()+"]";
-        }
-        
-        @Override
-        public String getDescription() {
-            return ""+chefAttributeSensors;
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/chef/ChefAttributePollConfig.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/chef/ChefAttributePollConfig.java b/software/base/src/main/java/brooklyn/entity/chef/ChefAttributePollConfig.java
deleted file mode 100644
index f2c90d2..0000000
--- a/software/base/src/main/java/brooklyn/entity/chef/ChefAttributePollConfig.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.sensor.feed.PollConfig;
-
-import com.google.common.base.Function;
-import com.google.common.base.Functions;
-
-public class ChefAttributePollConfig<T> extends PollConfig<Object, T, ChefAttributePollConfig<T>>{
-
-    private String chefAttributePath;
-
-    @SuppressWarnings({ "unchecked", "rawtypes" })
-    public ChefAttributePollConfig(AttributeSensor<T> sensor) {
-        super(sensor);
-        onSuccess((Function)Functions.identity());
-    }
-
-    public ChefAttributePollConfig(ChefAttributePollConfig<T> other) {
-        super(other);
-        this.chefAttributePath = other.chefAttributePath;
-    }
-
-    public String getChefAttributePath() {
-        return chefAttributePath;
-    }
-    
-    public ChefAttributePollConfig<T> chefAttributePath(String val) {
-        this.chefAttributePath = val; return this;
-    }
-    
-    @Override protected String toStringBaseName() { return "chef"; }
-    @Override protected String toStringPollSource() { return chefAttributePath; }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/chef/ChefBashCommands.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/chef/ChefBashCommands.java b/software/base/src/main/java/brooklyn/entity/chef/ChefBashCommands.java
deleted file mode 100644
index 1f0577d..0000000
--- a/software/base/src/main/java/brooklyn/entity/chef/ChefBashCommands.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-import static org.apache.brooklyn.util.ssh.BashCommands.INSTALL_CURL;
-import static org.apache.brooklyn.util.ssh.BashCommands.INSTALL_TAR;
-import static org.apache.brooklyn.util.ssh.BashCommands.INSTALL_UNZIP;
-import static org.apache.brooklyn.util.ssh.BashCommands.downloadToStdout;
-import static org.apache.brooklyn.util.ssh.BashCommands.sudo;
-
-import org.apache.brooklyn.util.ssh.BashCommands;
-
-import com.google.common.annotations.Beta;
-
-/** BASH commands useful for setting up Chef */
-@Beta
-public class ChefBashCommands {
-
-    public static final String INSTALL_FROM_OPSCODE =
-            BashCommands.chain(
-                    INSTALL_CURL,
-                    INSTALL_TAR,
-                    INSTALL_UNZIP,
-                    "( "+downloadToStdout("https://www.opscode.com/chef/install.sh") + " | " + sudo("bash")+" )");
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/chef/ChefConfig.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/chef/ChefConfig.java b/software/base/src/main/java/brooklyn/entity/chef/ChefConfig.java
deleted file mode 100644
index 2483157..0000000
--- a/software/base/src/main/java/brooklyn/entity/chef/ChefConfig.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.config.MapConfigKey;
-import org.apache.brooklyn.core.config.SetConfigKey;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-
-import com.google.common.annotations.Beta;
-
-/** {@link ConfigKey}s used to configure the chef driver */
-@Beta
-public interface ChefConfig {
-
-    public static final ConfigKey<String> CHEF_COOKBOOK_PRIMARY_NAME = ConfigKeys.newStringConfigKey("brooklyn.chef.cookbook.primary.name",
-        "Namespace to use for passing data to Chef and for finding effectors");
-    
-    @Deprecated /** @deprecatd since 0.7.0 use #CHEF_COOKBOOK_URLS */
-    @SetFromFlag("cookbooks")
-    public static final MapConfigKey<String> CHEF_COOKBOOKS = new MapConfigKey<String>(String.class, "brooklyn.chef.cookbooksUrls");
-
-    @SetFromFlag("cookbook_urls")
-    public static final MapConfigKey<String> CHEF_COOKBOOK_URLS = new MapConfigKey<String>(String.class, "brooklyn.chef.cookbooksUrls");
-
-    @SetFromFlag("converge_twice")
-    public static final ConfigKey<Boolean> CHEF_RUN_CONVERGE_TWICE = ConfigKeys.newBooleanConfigKey("brooklyn.chef.converge.twice",
-            "Whether to run converge commands twice if the first one fails; needed in some contexts, e.g. when switching between chef-server and chef-solo mode", false);
-
-    @Deprecated /** @deprecated since 0.7.0 use #CHEF_LAUNCH_RUN_LIST */
-    public static final SetConfigKey<String> CHEF_RUN_LIST = new SetConfigKey<String>(String.class, "brooklyn.chef.runList");
-    
-    /** typically set from spec, to customize the launch part of the start effector */
-    @SetFromFlag("launch_run_list")
-    public static final SetConfigKey<String> CHEF_LAUNCH_RUN_LIST = new SetConfigKey<String>(String.class, "brooklyn.chef.launch.runList");
-    /** typically set from spec, to customize the launch part of the start effector */
-    @SetFromFlag("launch_attributes")
-    public static final MapConfigKey<Object> CHEF_LAUNCH_ATTRIBUTES = new MapConfigKey<Object>(Object.class, "brooklyn.chef.launch.attributes");
-    
-    public static enum ChefModes {
-        /** Force use of Chef Solo */
-        SOLO, 
-        /** Force use of Knife; knife must be installed, and either 
-         *  {@link ChefConfig#KNIFE_EXECUTABLE} and {@link ChefConfig#KNIFE_CONFIG_FILE} must be set 
-         *  or knife on the path with valid global config set up */
-        KNIFE,
-        // TODO server via API
-        /** Tries {@link #KNIFE} if valid, else {@link #SOLO} */
-        AUTODETECT
-    };
-
-    @SetFromFlag("chef_mode")
-    public static final ConfigKey<ChefModes> CHEF_MODE = ConfigKeys.newConfigKey(ChefModes.class, "brooklyn.chef.mode",
-            "Whether Chef should run in solo mode, knife mode, or auto-detect", ChefModes.AUTODETECT);
-
-    // TODO server-url for server via API mode
-    
-    public static final ConfigKey<String> KNIFE_SETUP_COMMANDS = ConfigKeys.newStringConfigKey("brooklyn.chef.knife.setupCommands",
-            "An optional set of commands to run on localhost before invoking knife; useful if using ruby version manager for example");
-    public static final ConfigKey<String> KNIFE_EXECUTABLE = ConfigKeys.newStringConfigKey("brooklyn.chef.knife.executableFile",
-            "Knife command to run on the Brooklyn machine, including full path; defaults to scanning the path");
-    public static final ConfigKey<String> KNIFE_CONFIG_FILE = ConfigKeys.newStringConfigKey("brooklyn.chef.knife.configFile",
-            "Knife config file (typically knife.rb) to use, including full path; defaults to knife default/global config");
-
-    @SetFromFlag("chef_node_name")
-    public static final ConfigKey<String> CHEF_NODE_NAME = ConfigKeys.newStringConfigKey("brooklyn.chef.node.nodeName",
-        "Node name to register with the chef server for this entity, if using Chef server and a specific node name is desired; "
-        + "if supplied ,this must be unique across the nodes Chef Server manages; if not supplied, one will be created if needed");
-
-    // for providing some simple (ssh-based) lifecycle operations and checks
-    @SetFromFlag("pid_file")
-    public static final ConfigKey<String> PID_FILE = ConfigKeys.newStringConfigKey("brooklyn.chef.lifecycle.pidFile",
-        "Path to PID file on remote machine, for use in checking running and stopping; may contain wildcards");
-    @SetFromFlag("service_name")
-    public static final ConfigKey<String> SERVICE_NAME = ConfigKeys.newStringConfigKey("brooklyn.chef.lifecycle.serviceName",
-        "Name of OS service this will run as, for use in checking running and stopping");
-    @SetFromFlag("windows_service_name")
-    public static final ConfigKey<String> WINDOWS_SERVICE_NAME = ConfigKeys.newStringConfigKey("brooklyn.chef.lifecycle.windowsServiceName",
-        "Name of OS service this will run as on Windows, if different there, for use in checking running and stopping");
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/chef/ChefConfigs.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/chef/ChefConfigs.java b/software/base/src/main/java/brooklyn/entity/chef/ChefConfigs.java
deleted file mode 100644
index 3ff7490..0000000
--- a/software/base/src/main/java/brooklyn/entity/chef/ChefConfigs.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.MapConfigKey.MapModifications;
-import org.apache.brooklyn.core.config.SetConfigKey.SetModifications;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.apache.brooklyn.util.git.GithubUrls;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Preconditions;
-
-/** Conveniences for configuring brooklyn Chef entities 
- * @since 0.6.0 */
-@Beta
-public class ChefConfigs {
-
-    public static void addToLaunchRunList(EntitySpec<?> entity, String ...recipes) {
-        for (String recipe: recipes)
-            entity.configure(ChefConfig.CHEF_LAUNCH_RUN_LIST, SetModifications.addItem(recipe));
-    }
-
-    public static void addToLaunchRunList(EntityInternal entity, String ...recipes) {
-        for (String recipe: recipes)
-            entity.setConfig(ChefConfig.CHEF_LAUNCH_RUN_LIST, SetModifications.addItem(recipe));
-    }
-
-    public static void addToCookbooksFromGithub(EntitySpec<?> entity, String ...cookbookNames) {
-        for (String cookbookName: cookbookNames)
-            addToCookbooksFromGithub(entity, cookbookName, getGithubOpscodeRepo(cookbookName)); 
-    }
-    
-    public static void addToCookbooksFromGithub(EntityInternal entity, String ...cookbookNames) {
-        for (String cookbookName: cookbookNames)
-            addToCookbooksFromGithub(entity, cookbookName, getGithubOpscodeRepo(cookbookName)); 
-    }
-
-    public static String getGithubOpscodeRepo(String cookbookName) {
-        return getGithubOpscodeRepo(cookbookName, "master");
-    }
-    public static String getGithubOpscodeRepo(String cookbookName, String tag) {
-        return GithubUrls.tgz("opscode-cookbooks", cookbookName, tag);
-    }
-    
-    public static void addToCookbooksFromGithub(EntitySpec<?> entity, String cookbookName, String cookbookUrl) {
-        entity.configure(ChefConfig.CHEF_COOKBOOK_URLS.subKey(cookbookName), cookbookUrl);
-    }
-
-    public static void addToCookbooksFromGithub(EntityInternal entity, String cookbookName, String cookbookUrl) {
-        entity.setConfig(ChefConfig.CHEF_COOKBOOK_URLS.subKey(cookbookName), cookbookUrl);
-    }
-
-    @SuppressWarnings({ "unchecked", "rawtypes" })
-    public static void addLaunchAttributes(EntitySpec<?> entity, Map<? extends Object,? extends Object> attributesMap) {
-        entity.configure(ChefConfig.CHEF_LAUNCH_ATTRIBUTES, MapModifications.add((Map)attributesMap));
-    }
-    
-    @SuppressWarnings({ "unchecked", "rawtypes" })
-    public static void addLaunchAttributes(EntityInternal entity, Map<? extends Object,? extends Object> attributesMap) {
-        entity.setConfig(ChefConfig.CHEF_LAUNCH_ATTRIBUTES, MapModifications.add((Map)attributesMap));
-    }
-    
-    /** replaces the attributes underneath the rootAttribute parameter with the given value;
-     * see {@link #addLaunchAttributesMap(EntitySpec, Map)} for richer functionality */
-    public static void setLaunchAttribute(EntitySpec<?> entity, String rootAttribute, Object value) {
-        entity.configure(ChefConfig.CHEF_LAUNCH_ATTRIBUTES.subKey(rootAttribute), value);
-    }
-    
-    /** replaces the attributes underneath the rootAttribute parameter with the given value;
-     * see {@link #addLaunchAttributesMap(EntitySpec, Map)} for richer functionality */
-    public static void setLaunchAttribute(EntityInternal entity, String rootAttribute, Object value) {
-        entity.setConfig(ChefConfig.CHEF_LAUNCH_ATTRIBUTES.subKey(rootAttribute), value);
-    }
-
-    public static <T> T getRequiredConfig(Entity entity, ConfigKey<T> key) {
-        return Preconditions.checkNotNull(
-                Preconditions.checkNotNull(entity, "Entity must be supplied").getConfig(key), 
-                "Key "+key+" is required on "+entity);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/chef/ChefEntity.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/chef/ChefEntity.java b/software/base/src/main/java/brooklyn/entity/chef/ChefEntity.java
deleted file mode 100644
index 911eacc..0000000
--- a/software/base/src/main/java/brooklyn/entity/chef/ChefEntity.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-import org.apache.brooklyn.api.entity.ImplementedBy;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
-@ImplementedBy(ChefEntityImpl.class)
-public interface ChefEntity extends SoftwareProcess, ChefConfig {
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/chef/ChefEntityImpl.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/chef/ChefEntityImpl.java b/software/base/src/main/java/brooklyn/entity/chef/ChefEntityImpl.java
deleted file mode 100644
index d69640a..0000000
--- a/software/base/src/main/java/brooklyn/entity/chef/ChefEntityImpl.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-import org.apache.brooklyn.entity.stock.EffectorStartableImpl;
-import org.apache.brooklyn.util.text.Strings;
-
-public class ChefEntityImpl extends EffectorStartableImpl implements ChefEntity {
-
-    public void init() {
-        String primaryName = getConfig(CHEF_COOKBOOK_PRIMARY_NAME);
-        if (!Strings.isBlank(primaryName)) setDefaultDisplayName(primaryName+" (chef)");
-        
-        super.init();
-        new ChefLifecycleEffectorTasks().attachLifecycleEffectors(this);
-    }
-
-    @Override
-    public void populateServiceNotUpDiagnostics() {
-        // TODO no-op currently; should check ssh'able etc
-    }    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/chef/ChefLifecycleEffectorTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/chef/ChefLifecycleEffectorTasks.java b/software/base/src/main/java/brooklyn/entity/chef/ChefLifecycleEffectorTasks.java
deleted file mode 100644
index ad28d87..0000000
--- a/software/base/src/main/java/brooklyn/entity/chef/ChefLifecycleEffectorTasks.java
+++ /dev/null
@@ -1,362 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-import java.util.Collection;
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.entity.core.Attributes;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.software.MachineLifecycleEffectorTasks;
-import brooklyn.entity.software.SshEffectorTasks;
-
-import org.apache.brooklyn.location.basic.Machines;
-import org.apache.brooklyn.util.collections.Jsonya;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.collections.Jsonya.Navigator;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.TaskTags;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.brooklyn.util.ssh.BashCommands;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Supplier;
-import com.google.common.collect.ImmutableList;
-
-/** 
- * Creates effectors to start, restart, and stop processes using Chef.
- * <p>
- * Instances of this should use the {@link ChefConfig} config attributes to configure startup,
- * and invoke {@link #usePidFile(String)} or {@link #useService(String)} to determine check-running and stop behaviour.
- * Alternatively this can be subclassed and {@link #postStartCustom()} and {@link #stopProcessesAtMachine()} overridden.
- * 
- * @since 0.6.0
- **/
-@Beta
-public class ChefLifecycleEffectorTasks extends MachineLifecycleEffectorTasks implements ChefConfig {
-
-    private static final Logger log = LoggerFactory.getLogger(ChefLifecycleEffectorTasks.class);
-    
-    protected String _pidFile, _serviceName, _windowsServiceName;
-    
-    public ChefLifecycleEffectorTasks() {
-    }
-    
-    public ChefLifecycleEffectorTasks usePidFile(String pidFile) {
-        this._pidFile = pidFile;
-        return this;
-    }
-    public ChefLifecycleEffectorTasks useService(String serviceName) {
-        this._serviceName = serviceName;
-        return this;
-    }
-    public ChefLifecycleEffectorTasks useWindowsService(String serviceName) {
-        this._windowsServiceName = serviceName;
-        return this;
-    }
-    
-    public String getPidFile() {
-        if (_pidFile!=null) return _pidFile;
-        return _pidFile = entity().getConfig(ChefConfig.PID_FILE);
-    }
-
-    public String getServiceName() {
-        if (_serviceName!=null) return _serviceName;
-        return _serviceName = entity().getConfig(ChefConfig.SERVICE_NAME);
-    }
-
-    protected String getNodeName() {
-        // (node name is needed so we can node delete it)
-        
-        // TODO would be better if CHEF_NODE_NAME were a freemarker template, could access entity.id, or hostname, etc,
-        // in addition to supporting hard-coded node names (which is all we support so far).
-        
-        String nodeName = entity().getConfig(ChefConfig.CHEF_NODE_NAME);
-        if (Strings.isNonBlank(nodeName)) return Strings.makeValidFilename(nodeName);
-        // node name is taken from ID of this entity, if not specified
-        return entity().getId();
-    }
-
-    public String getWindowsServiceName() {
-        if (_windowsServiceName!=null) return _windowsServiceName;
-        return _windowsServiceName = entity().getConfig(ChefConfig.WINDOWS_SERVICE_NAME);
-    }
-
-    @Override
-    public void attachLifecycleEffectors(Entity entity) {
-        if (getPidFile()==null && getServiceName()==null && getClass().equals(ChefLifecycleEffectorTasks.class)) {
-            // warn on incorrect usage
-            log.warn("Uses of "+getClass()+" must define a PID file or a service name (or subclass and override {start,stop} methods as per javadoc) " +
-                    "in order for check-running and stop to work");
-        }
-            
-        super.attachLifecycleEffectors(entity);
-    }
-
-    public static ChefModes detectChefMode(Entity entity) {
-        ChefModes mode = entity.getConfig(ChefConfig.CHEF_MODE);
-        if (mode == ChefModes.AUTODETECT) {
-            // TODO server via API
-            ProcessTaskWrapper<Boolean> installCheck = DynamicTasks.queue(
-                    ChefServerTasks.isKnifeInstalled());
-            mode = installCheck.get() ? ChefModes.KNIFE : ChefModes.SOLO;
-            log.debug("Using Chef in "+mode+" mode due to autodetect exit code "+installCheck.getExitCode());
-        }
-        Preconditions.checkNotNull(mode, "Non-null "+ChefConfig.CHEF_MODE+" required for "+entity);
-        return mode;
-    }
-    
-    @Override
-    protected String startProcessesAtMachine(Supplier<MachineLocation> machineS) {
-        ChefModes mode = detectChefMode(entity());
-        switch (mode) {
-        case KNIFE:
-            startWithKnifeAsync();
-            break;
-            
-        case SOLO:
-            startWithChefSoloAsync();
-            break;
-            
-        default:
-            throw new IllegalStateException("Unknown Chef mode "+mode+" when starting processes for "+entity());
-        }
-        
-        return "chef start tasks submitted ("+mode+")";
-    }
-
-    protected String getPrimaryCookbook() {
-        return entity().getConfig(CHEF_COOKBOOK_PRIMARY_NAME);
-    }
-    
-    @SuppressWarnings({ "unchecked", "deprecation" })
-    protected void startWithChefSoloAsync() {
-        String baseDir = MachineLifecycleEffectorTasks.resolveOnBoxDir(entity(), Machines.findUniqueSshMachineLocation(entity().getLocations()).get());
-        String installDir = Urls.mergePaths(baseDir, "installs/chef");
-        
-        @SuppressWarnings("rawtypes")
-        Map<String, String> cookbooks = (Map) 
-            ConfigBag.newInstance( entity().getConfig(CHEF_COOKBOOK_URLS) )
-            .putIfAbsent( entity().getConfig(CHEF_COOKBOOKS) )
-            .getAllConfig();
-        if (cookbooks.isEmpty())
-            log.warn("No cookbook_urls set for "+entity()+"; launch will likely fail subsequently");
-        DynamicTasks.queue(
-                ChefSoloTasks.installChef(installDir, false), 
-                ChefSoloTasks.installCookbooks(installDir, cookbooks, false));
-
-        // TODO chef for and run a prestart recipe if necessary
-        // TODO open ports
-
-        String primary = getPrimaryCookbook();
-        
-        // put all config under brooklyn/cookbook/config
-        Navigator<MutableMap<Object, Object>> attrs = Jsonya.newInstancePrimitive().at("brooklyn");
-        if (Strings.isNonBlank(primary)) attrs.at(primary);
-        attrs.at("config");
-        attrs.put( entity().getAllConfigBag().getAllConfig() );
-        // and put launch attrs at root
-        try {
-            attrs.root().put((Map<?,?>)Tasks.resolveDeepValue(entity().getConfig(CHEF_LAUNCH_ATTRIBUTES), Object.class, entity().getExecutionContext()));
-        } catch (Exception e) { Exceptions.propagate(e); }
-        
-        Collection<? extends String> runList = entity().getConfig(CHEF_LAUNCH_RUN_LIST);
-        if (runList==null) runList = entity().getConfig(CHEF_RUN_LIST);
-        if (runList==null) {
-            if (Strings.isNonBlank(primary)) runList = ImmutableList.of(primary+"::"+"start");
-            else throw new IllegalStateException("Require a primary cookbook or a run_list to effect "+"start"+" on "+entity());
-        }
-        
-        String runDir = Urls.mergePaths(baseDir,  
-            "apps/"+entity().getApplicationId()+"/chef/entities/"+entity().getEntityType().getSimpleName()+"_"+entity().getId());
-        
-        DynamicTasks.queue(ChefSoloTasks.buildChefFile(runDir, installDir, "launch", 
-                runList, (Map<String, Object>) attrs.root().get()));
-        
-        DynamicTasks.queue(ChefSoloTasks.runChef(runDir, "launch", entity().getConfig(CHEF_RUN_CONVERGE_TWICE)));
-    }
-    
-    @SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
-    protected void startWithKnifeAsync() {
-        // TODO prestart, ports (as above); also, note, some aspects of this are untested as we need a chef server
-        
-        String primary = getPrimaryCookbook();
-
-        // put all config under brooklyn/cookbook/config
-        Navigator<MutableMap<Object, Object>> attrs = Jsonya.newInstancePrimitive().at("brooklyn");
-        if (Strings.isNonBlank(primary)) attrs.at(primary);
-        attrs.at("config");
-        attrs.put( entity().getAllConfigBag().getAllConfig() );
-        // and put launch attrs at root
-        try {
-            attrs.root().put((Map<?,?>)Tasks.resolveDeepValue(entity().getConfig(CHEF_LAUNCH_ATTRIBUTES), Object.class, entity().getExecutionContext()));
-        } catch (Exception e) { Exceptions.propagate(e); }
-
-        Collection<? extends String> runList = entity().getConfig(CHEF_LAUNCH_RUN_LIST);
-        if (runList==null) runList = entity().getConfig(CHEF_RUN_LIST);
-        if (runList==null) {
-            if (Strings.isNonBlank(primary)) runList = ImmutableList.of(primary+"::"+"start");
-            else throw new IllegalStateException("Require a primary cookbook or a run_list to effect "+"start"+" on "+entity());
-        }
-
-        DynamicTasks.queue(
-                ChefServerTasks.knifeConvergeTask()
-                    .knifeNodeName(getNodeName())
-                    .knifeRunList(Strings.join(runList, ","))
-                    .knifeAddAttributes((Map<? extends Object, ? extends Object>)(Map) attrs.root().get())
-                    .knifeRunTwice(entity().getConfig(CHEF_RUN_CONVERGE_TWICE)) );
-    }
-
-    protected void postStartCustom() {
-        boolean result = false;
-        result |= tryCheckStartPid();
-        result |= tryCheckStartService();
-        result |= tryCheckStartWindowsService();
-        if (!result) {
-            log.warn("No way to check whether "+entity()+" is running; assuming yes");
-        }
-        entity().setAttribute(SoftwareProcess.SERVICE_UP, true);
-    }
-    
-    protected boolean tryCheckStartPid() {
-        if (getPidFile()==null) return false;
-        
-        // if it's still up after 5s assume we are good (default behaviour)
-        Time.sleep(Duration.FIVE_SECONDS);
-        if (!DynamicTasks.queue(SshEffectorTasks.isPidFromFileRunning(getPidFile()).runAsRoot()).get()) {
-            throw new IllegalStateException("The process for "+entity()+" appears not to be running (pid file "+getPidFile()+")");
-        }
-
-        // and set the PID
-        entity().setAttribute(Attributes.PID, 
-                Integer.parseInt(DynamicTasks.queue(SshEffectorTasks.ssh("cat "+getPidFile()).runAsRoot()).block().getStdout().trim()));
-        return true;
-    }
-
-    protected boolean tryCheckStartService() {
-        if (getServiceName()==null) return false;
-        
-        // if it's still up after 5s assume we are good (default behaviour)
-        Time.sleep(Duration.FIVE_SECONDS);
-        if (!((Integer)0).equals(DynamicTasks.queue(SshEffectorTasks.ssh("/etc/init.d/"+getServiceName()+" status").runAsRoot()).get())) {
-            throw new IllegalStateException("The process for "+entity()+" appears not to be running (service "+getServiceName()+")");
-        }
-
-        return true;
-    }
-
-    protected boolean tryCheckStartWindowsService() {
-        if (getWindowsServiceName()==null) return false;
-        
-        // if it's still up after 5s assume we are good (default behaviour)
-        Time.sleep(Duration.FIVE_SECONDS);
-        if (!((Integer)0).equals(DynamicTasks.queue(SshEffectorTasks.ssh("sc query \""+getWindowsServiceName()+"\" | find \"RUNNING\"").runAsCommand()).get())) {
-            throw new IllegalStateException("The process for "+entity()+" appears not to be running (windowsService "+getWindowsServiceName()+")");
-        }
-
-        return true;
-    }
-
-    @Override
-    protected String stopProcessesAtMachine() {
-        boolean result = false;
-        result |= tryStopService();
-        result |= tryStopWindowsService();
-        result |= tryStopPid();
-        if (!result) {
-            throw new IllegalStateException("The process for "+entity()+" could not be stopped (no impl!)");
-        }
-        return "stopped";
-    }
-    
-    @Override
-    protected StopMachineDetails<Integer> stopAnyProvisionedMachines() {
-        if (detectChefMode(entity())==ChefModes.KNIFE) {
-            DynamicTasks.queue(
-                // if this task fails show it as failed but don't block subsequent routines
-                // (ie allow us to actually decommission the machine)
-                // TODO args could be a List<String> config key ?
-                TaskTags.markInessential(
-                new KnifeTaskFactory<String>("delete node and client registration at chef server")
-                    .add("knife node delete "+getNodeName()+" -y")
-                    .add("knife client delete "+getNodeName()+" -y")
-                    .requiringZeroAndReturningStdout()
-                    .newTask() ));
-        }
-
-        return super.stopAnyProvisionedMachines();
-    }
-    
-    protected boolean tryStopService() {
-        if (getServiceName()==null) return false;
-        int result = DynamicTasks.queue(SshEffectorTasks.ssh("/etc/init.d/"+getServiceName()+" stop").runAsRoot()).get();
-        if (0==result) return true;
-        if (entity().getAttribute(Attributes.SERVICE_STATE_ACTUAL)!=Lifecycle.RUNNING)
-            return true;
-        
-        throw new IllegalStateException("The process for "+entity()+" appears could not be stopped (exit code "+result+" to service stop)");
-    }
-
-    protected boolean tryStopWindowsService() {
-        if (getWindowsServiceName()==null) return false;
-                int result = DynamicTasks.queue(SshEffectorTasks.ssh("sc query \""+getWindowsServiceName()+"\"").runAsCommand()).get();
-        if (0==result) return true;
-        if (entity().getAttribute(Attributes.SERVICE_STATE_ACTUAL)!=Lifecycle.RUNNING)
-            return true;
-
-        throw new IllegalStateException("The process for "+entity()+" appears could not be stopped (exit code "+result+" to service stop)");
-    }
-
-    protected boolean tryStopPid() {
-        Integer pid = entity().getAttribute(Attributes.PID);
-        if (pid==null) {
-            if (entity().getAttribute(Attributes.SERVICE_STATE_ACTUAL)==Lifecycle.RUNNING && getPidFile()==null)
-                log.warn("No PID recorded for "+entity()+" when running, with PID file "+getPidFile()+"; skipping kill in "+Tasks.current());
-            else 
-                if (log.isDebugEnabled())
-                    log.debug("No PID recorded for "+entity()+"; skipping ("+entity().getAttribute(Attributes.SERVICE_STATE_ACTUAL)+" / "+getPidFile()+")");
-            return false;
-        }
-        
-        // allow non-zero exit as process may have already been killed
-        DynamicTasks.queue(SshEffectorTasks.ssh(
-                "kill "+pid, "sleep 5", BashCommands.ok("kill -9 "+pid)).allowingNonZeroExitCode().runAsRoot()).block();
-        
-        if (DynamicTasks.queue(SshEffectorTasks.isPidRunning(pid).runAsRoot()).get()) {
-            throw new IllegalStateException("Process for "+entity()+" in "+pid+" still running after kill");
-        }
-        entity().setAttribute(Attributes.PID, null);
-        return true;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/chef/ChefServerTasks.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/chef/ChefServerTasks.java b/software/base/src/main/java/brooklyn/entity/chef/ChefServerTasks.java
deleted file mode 100644
index 14ab230..0000000
--- a/software/base/src/main/java/brooklyn/entity/chef/ChefServerTasks.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.chef;
-
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.security.KeyPair;
-
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.util.core.crypto.SecureKeys;
-
-import com.google.common.base.Throwables;
-import com.google.common.io.Files;
-
-public class ChefServerTasks {
-
-    private static File chefKeyDir;
-    
-    private synchronized static File getExtractedKeysDir() {
-        if (chefKeyDir==null) {
-            chefKeyDir = Files.createTempDir();
-            chefKeyDir.deleteOnExit();
-        }
-        return chefKeyDir;
-    }
-    
-    /** extract key to a temp file, but one per machine, scheduled for deletion afterwards;
-     * we extract the key because chef has no way to accept passphrases at present */
-    synchronized static File extractKeyFile(SshMachineLocation machine) {
-        File f = new File(getExtractedKeysDir(), machine.getAddress().getHostName()+".pem");
-        if (f.exists()) return f;
-        KeyPair data = machine.findKeyPair();
-        if (data==null) return null;
-        try {
-            f.deleteOnExit();
-            Files.write(SecureKeys.stringPem(data), f, Charset.defaultCharset());
-            return f;
-        } catch (IOException e) {
-            throw Throwables.propagate(e);
-        }
-    }
-    
-    public static KnifeTaskFactory<Boolean> isKnifeInstalled() {
-        return new KnifeTaskFactory<Boolean>("knife install check")
-                .knifeAddParameters("node list")
-                .notThrowingOnCommonKnifeErrors()
-                .returningIsExitCodeZero();
-    }
-
-    /** plain knife converge task - run list must be set, other arguments are optional */
-    public static KnifeConvergeTaskFactory<String> knifeConvergeTask() {
-        return new KnifeConvergeTaskFactory<String>("knife converge")
-                .requiringZeroAndReturningStdout();
-    }
-    /** knife converge task configured for this run list (and sudo) */
-    public static KnifeConvergeTaskFactory<String> knifeConvergeRunList(String runList) {
-        return knifeConvergeTask()
-                .knifeRunList(runList)
-                .knifeSudo(true);
-    }
-    
-    /** knife converge task configured for this run list on windows (ssh) */
-    public static KnifeConvergeTaskFactory<String> knifeConvergeRunListWindowsSsh(String runList) {
-        return knifeConvergeTask()
-                .knifeRunList(runList)
-                .knifeSudo(false)
-                .knifeAddExtraBootstrapParameters("windows ssh");
-    }
-    
-    /** knife converge task configured for this run list on windows (winrm) */
-    public static KnifeConvergeTaskFactory<String> knifeConvergeRunListWindowsWinrm(String runList) {
-        return knifeConvergeTask()
-                .knifeRunList(runList)
-                .knifeSudo(false)
-                .knifeAddExtraBootstrapParameters("windows winrm")
-                .knifePortUseKnifeDefault();
-    }
-    
-}


[61/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/FixedListMachineProvisioningLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/FixedListMachineProvisioningLocation.java b/core/src/main/java/org/apache/brooklyn/location/basic/FixedListMachineProvisioningLocation.java
deleted file mode 100644
index 78cd0d6..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/FixedListMachineProvisioningLocation.java
+++ /dev/null
@@ -1,474 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.apache.brooklyn.util.GroovyJavaMethods.truth;
-
-import java.io.Closeable;
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.location.MachineLocationCustomizer;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.api.mgmt.LocationManager;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Function;
-import com.google.common.base.Objects;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-import com.google.common.reflect.TypeToken;
-
-import org.apache.brooklyn.location.cloud.CloudLocationConfig;
-import org.apache.brooklyn.util.collections.CollectionFunctionals;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.collections.MutableSet;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.apache.brooklyn.util.stream.Streams;
-import org.apache.brooklyn.util.text.WildcardGlobs;
-import org.apache.brooklyn.util.text.WildcardGlobs.PhraseTreatment;
-
-/**
- * A provisioner of {@link MachineLocation}s which takes a list of machines it can connect to.
- * The collection of initial machines should be supplied in the 'machines' flag in the constructor,
- * for example a list of machines which can be SSH'd to. 
- * 
- * This can be extended to have a mechanism to make more machines to be available
- * (override provisionMore and canProvisionMore).
- */
-public class FixedListMachineProvisioningLocation<T extends MachineLocation> extends AbstractLocation 
-implements MachineProvisioningLocation<T>, Closeable {
-
-    // TODO Synchronization looks very wrong for accessing machines/inUse 
-    // e.g. removeChild doesn't synchronize when doing machines.remove(...),
-    // and getMachines() returns the real sets risking 
-    // ConcurrentModificationException in the caller if it iterates over them etc.
-    
-    private static final Logger log = LoggerFactory.getLogger(FixedListMachineProvisioningLocation.class);
-    
-    public static final ConfigKey<Function<Iterable<? extends MachineLocation>, MachineLocation>> MACHINE_CHOOSER =
-            ConfigKeys.newConfigKey(
-                    new TypeToken<Function<Iterable<? extends MachineLocation>, MachineLocation>>() {}, 
-                    "byon.machineChooser",
-                    "For choosing which of the possible machines is chosen and returned by obtain()",
-                    CollectionFunctionals.<MachineLocation>firstElement());
-
-    public static final ConfigKey<Collection<MachineLocationCustomizer>> MACHINE_LOCATION_CUSTOMIZERS = CloudLocationConfig.MACHINE_LOCATION_CUSTOMIZERS;
-    
-    private final Object lock = new Object();
-    
-    @SetFromFlag
-    protected Set<T> machines;
-    
-    @SetFromFlag
-    protected Set<T> inUse;
-
-    @SetFromFlag
-    protected Set<T> pendingRemoval;
-    
-    @SetFromFlag
-    protected Map<T, Map<String, Object>> origConfigs;
-
-    public FixedListMachineProvisioningLocation() {
-        this(Maps.newLinkedHashMap());
-    }
-    public FixedListMachineProvisioningLocation(Map properties) {
-        super(properties);
-
-        if (isLegacyConstruction()) {
-            init();
-        }
-    }
-
-    @Override
-    public void init() {
-        super.init();
-        
-        Set<T> machinesCopy = MutableSet.of();
-        for (T location: machines) {
-            if (location==null) {
-                log.warn(""+this+" initialized with null location, removing (may be due to rebind with reference to an unmanaged location)");
-            } else {
-                Location parent = location.getParent();
-                if (parent == null) {
-                    addChild(location);
-                }
-                machinesCopy.add(location);
-            }
-        }
-        if (!machinesCopy.equals(machines)) {
-            machines = machinesCopy;
-        }
-    }
-    
-    @Override
-    public String toVerboseString() {
-        return Objects.toStringHelper(this).omitNullValues()
-                .add("id", getId()).add("name", getDisplayName())
-                .add("machinesAvailable", getAvailable()).add("machinesInUse", getInUse())
-                .toString();
-    }
-
-    @Override
-    public AbstractLocation configure(Map<?,?> properties) {
-        if (machines == null) machines = Sets.newLinkedHashSet();
-        if (inUse == null) inUse = Sets.newLinkedHashSet();
-        if (pendingRemoval == null) pendingRemoval = Sets.newLinkedHashSet();
-        if (origConfigs == null) origConfigs = Maps.newLinkedHashMap();
-        return super.configure(properties);
-    }
-    
-    @SuppressWarnings("unchecked")
-    public FixedListMachineProvisioningLocation<T> newSubLocation(Map<?,?> newFlags) {
-        // TODO shouldn't have to copy config bag as it should be inherited (but currently it is not used inherited everywhere; just most places)
-        return getManagementContext().getLocationManager().createLocation(LocationSpec.create(getClass())
-                .parent(this)
-                .configure(config().getLocalBag().getAllConfig())  // FIXME Should this just be inherited?
-                .configure(newFlags));
-    }
-
-    @Override
-    public void close() {
-        for (T machine : machines) {
-            if (machine instanceof Closeable) Streams.closeQuietly((Closeable)machine);
-        }
-    }
-    
-    public void addMachine(T machine) {
-        synchronized (lock) {
-            if (machines.contains(machine)) {
-                throw new IllegalArgumentException("Cannot add "+machine+" to "+toString()+", because already contained");
-            }
-            
-            Location existingParent = ((Location)machine).getParent();
-            if (existingParent == null) {
-                addChild(machine);
-            }
-            
-            machines.add(machine);
-        }
-    }
-    
-    public void removeMachine(T machine) {
-        synchronized (lock) {
-            if (inUse.contains(machine)) {
-                pendingRemoval.add(machine);
-            } else {
-                machines.remove(machine);
-                pendingRemoval.remove(machine);
-                if (this.equals(machine.getParent())) {
-                    removeChild((Location)machine);
-                }
-            }
-        }
-    }
-    
-    protected Set<T> getMachines() {
-        return machines;
-    }
-    
-    public Set<T> getAvailable() {
-        Set<T> a = Sets.newLinkedHashSet(machines);
-        a.removeAll(inUse);
-        return a;
-    }   
-     
-    public Set<T> getInUse() {
-        return Sets.newLinkedHashSet(inUse);
-    }   
-     
-    public Set<T> getAllMachines() {
-        return ImmutableSet.copyOf(machines);
-    }   
-     
-    @Override
-    public void addChild(Location child) {
-        super.addChild(child);
-        machines.add((T)child);
-    }
-
-    @Override
-    public boolean removeChild(Location child) {
-        if (inUse.contains(child)) {
-            throw new IllegalStateException("Child location "+child+" is in use; cannot remove from "+this);
-        }
-        machines.remove(child);
-        return super.removeChild(child);
-    }
-
-    protected boolean canProvisionMore() {
-        return false;
-    }
-    
-    protected void provisionMore(int size) {
-        provisionMore(size, ImmutableMap.of());
-    }
-
-    protected void provisionMore(int size, Map<?,?> flags) {
-        throw new IllegalStateException("more not permitted");
-    }
-
-    public T obtain() throws NoMachinesAvailableException {
-        return obtain(Maps.<String,Object>newLinkedHashMap());
-    }
-    
-    @Override
-    public T obtain(Map<?,?> flags) throws NoMachinesAvailableException {
-        T machine;
-        T desiredMachine = (T) flags.get("desiredMachine");
-        ConfigBag allflags = ConfigBag.newInstanceExtending(config().getBag()).putAll(flags);
-        Function<Iterable<? extends MachineLocation>, MachineLocation> chooser = allflags.get(MACHINE_CHOOSER);
-        
-        synchronized (lock) {
-            Set<T> a = getAvailable();
-            if (a.isEmpty()) {
-                if (canProvisionMore()) {
-                    provisionMore(1, allflags.getAllConfig());
-                    a = getAvailable();
-                }
-                if (a.isEmpty())
-                    throw new NoMachinesAvailableException("No machines available in "+toString());
-            }
-            if (desiredMachine != null) {
-                if (a.contains(desiredMachine)) {
-                    machine = desiredMachine;
-                } else {
-                    throw new IllegalStateException("Desired machine "+desiredMachine+" not available in "+toString()+"; "+
-                            (inUse.contains(desiredMachine) ? "machine in use" : "machine unknown"));
-                }
-            } else {
-                machine = (T) chooser.apply(a);
-                if (!a.contains(machine)) {
-                    throw new IllegalStateException("Machine chooser attempted to choose '"+machine+"' from outside the available set, in "+this);
-                }
-            }
-            inUse.add(machine);
-            updateMachineConfig(machine, flags);
-        }
-        
-        for (MachineLocationCustomizer customizer : getMachineCustomizers(allflags)) {
-            customizer.customize(machine);
-        }
-        
-        return machine;
-    }
-
-    @Override
-    public void release(T machine) {
-        ConfigBag machineConfig = ((ConfigurationSupportInternal)machine.config()).getBag();
-        for (MachineLocationCustomizer customizer : getMachineCustomizers(machineConfig)) {
-            customizer.preRelease(machine);
-        }
-
-        synchronized (lock) {
-            if (inUse.contains(machine) == false)
-                throw new IllegalStateException("Request to release machine "+machine+", but this machine is not currently allocated");
-            restoreMachineConfig(machine);
-            inUse.remove(machine);
-            
-            if (pendingRemoval.contains(machine)) {
-                removeMachine(machine);
-            }
-        }
-    }
-
-    @Override
-    public Map<String,Object> getProvisioningFlags(Collection<String> tags) {
-        return Maps.<String,Object>newLinkedHashMap();
-    }
-    
-    protected void updateMachineConfig(T machine, Map<?, ?> flags) {
-        if (origConfigs == null) {
-            // For backwards compatibility, where peristed state did not have this.
-            origConfigs = Maps.newLinkedHashMap();
-        }
-        Map<String, Object> strFlags = ConfigBag.newInstance(flags).getAllConfig();
-        Map<String, Object> origConfig = ((ConfigurationSupportInternal)machine.config()).getLocalBag().getAllConfig();
-        origConfigs.put(machine, origConfig);
-        requestPersist();
-        
-        ((ConfigurationSupportInternal)machine.config()).addToLocalBag(strFlags);
-    }
-    
-    protected void restoreMachineConfig(MachineLocation machine) {
-        if (origConfigs == null) {
-            // For backwards compatibility, where peristed state did not have this.
-            origConfigs = Maps.newLinkedHashMap();
-        }
-        Map<String, Object> origConfig = origConfigs.remove(machine);
-        if (origConfig == null) return;
-        requestPersist();
-        
-        Set<String> currentKeys = ((ConfigurationSupportInternal)machine.config()).getLocalBag().getAllConfig().keySet();
-        Set<String> newKeys = Sets.difference(currentKeys, origConfig.entrySet());
-        for (String key : newKeys) {
-            ((ConfigurationSupportInternal)machine.config()).removeFromLocalBag(key);
-        }
-        ((ConfigurationSupportInternal)machine.config()).addToLocalBag(origConfig);
-    }
-    
-    @SuppressWarnings("unchecked")
-    private <K> K getConfigPreferringOverridden(ConfigKey<K> key, Map<?,?> overrides) {
-        K result = (K) overrides.get(key);
-        if (result == null) result = (K) overrides.get(key.getName());
-        if (result == null) result = getConfig(key);
-        return result;
-    }
-
-    protected Collection<MachineLocationCustomizer> getMachineCustomizers(ConfigBag setup) {
-        Collection<MachineLocationCustomizer> customizers = setup.get(MACHINE_LOCATION_CUSTOMIZERS);
-        return (customizers == null ? ImmutableList.<MachineLocationCustomizer>of() : customizers);
-    }
-
-    /**
-     * Facilitates fluent/programmatic style for constructing a fixed pool of machines.
-     * <pre>
-     * {@code
-     *   new FixedListMachineProvisioningLocation.Builder()
-     *           .user("alex")
-     *           .keyFile("/Users/alex/.ssh/id_rsa")
-     *           .addAddress("10.0.0.1")
-     *           .addAddress("10.0.0.2")
-     *           .addAddress("10.0.0.3")
-     *           .addAddressMultipleTimes("me@127.0.0.1", 5)
-     *           .build();
-     * }
-     * </pre>
-     */
-    public static class Builder {
-        LocationManager lm;
-        String user;
-        String privateKeyPassphrase;
-        String privateKeyFile;
-        String privateKeyData;
-        File localTempDir;
-        List machines = Lists.newArrayList();
-
-        public Builder(LocationManager lm) {
-            this.lm = lm;
-        }
-        public Builder user(String user) {
-            this.user = user;
-            return this;
-        }
-        public Builder keyPassphrase(String keyPassphrase) {
-            this.privateKeyPassphrase = keyPassphrase;
-            return this; 
-        }
-        public Builder keyFile(String keyFile) {
-            this.privateKeyFile = keyFile;
-            return this; 
-        }
-        public Builder keyData(String keyData) {
-            this.privateKeyData = keyData;
-            return this;
-        }
-        public Builder localTempDir(File val) {
-            this.localTempDir = val;
-            return this;
-        }
-        /** adds the locations; user and keyfile set in the builder are _not_ applied to the machine
-         * (use add(String address) for that)
-         */
-        public Builder add(SshMachineLocation location) {
-            machines.add(location);
-            return this;
-        }
-        public Builder addAddress(String address) {
-            return addAddresses(address);
-        }
-        public Builder addAddressMultipleTimes(String address, int n) {
-            for (int i=0; i<n; i++)
-                addAddresses(address);
-            return this;
-        }
-        public Builder addAddresses(String address1, String ...others) {
-            List<String> addrs = new ArrayList<String>();
-            addrs.addAll(WildcardGlobs.getGlobsAfterBraceExpansion("{"+address1+"}",
-                    true /* numeric */, /* no quote support though */ PhraseTreatment.NOT_A_SPECIAL_CHAR, PhraseTreatment.NOT_A_SPECIAL_CHAR));
-            for (String address: others) 
-                addrs.addAll(WildcardGlobs.getGlobsAfterBraceExpansion("{"+address+"}",
-                        true /* numeric */, /* no quote support though */ PhraseTreatment.NOT_A_SPECIAL_CHAR, PhraseTreatment.NOT_A_SPECIAL_CHAR));
-            for (String addr: addrs)
-                add(createMachine(addr)); 
-            return this;
-        }
-        protected SshMachineLocation createMachine(String addr) {
-            if (lm==null)
-                return new SshMachineLocation(makeConfig(addr));
-            else
-                return lm.createLocation(makeConfig(addr), SshMachineLocation.class);
-        }
-        private Map makeConfig(String address) {
-            String user = this.user;
-            if (address.contains("@")) {
-                user = address.substring(0, address.indexOf("@"));
-                address = address.substring(address.indexOf("@")+1);
-            }
-            Map config = MutableMap.of("address", address);
-            if (truth(user)) {
-                config.put("user", user);
-                config.put("sshconfig.user", user);
-            }
-            if (truth(privateKeyPassphrase)) config.put("sshconfig.privateKeyPassphrase", privateKeyPassphrase);
-            if (truth(privateKeyFile)) config.put("sshconfig.privateKeyFile", privateKeyFile);
-            if (truth(privateKeyData)) config.put("sshconfig.privateKey", privateKeyData);
-            if (truth(localTempDir)) config.put("localTempDir", localTempDir);
-            return config;
-        }
-        @SuppressWarnings("unchecked")
-        public FixedListMachineProvisioningLocation<SshMachineLocation> build() {
-            if (lm==null)
-                return new FixedListMachineProvisioningLocation<SshMachineLocation>(MutableMap.builder()
-                    .putIfNotNull("machines", machines)
-                    .putIfNotNull("user", user)
-                    .putIfNotNull("privateKeyPassphrase", privateKeyPassphrase)
-                    .putIfNotNull("privateKeyFile", privateKeyFile)
-                    .putIfNotNull("privateKeyData", privateKeyData)
-                    .putIfNotNull("localTempDir", localTempDir)
-                    .build());
-            else
-                return lm.createLocation(MutableMap.builder()
-                    .putIfNotNull("machines", machines)
-                    .putIfNotNull("user", user)
-                    .putIfNotNull("privateKeyPassphrase", privateKeyPassphrase)
-                    .putIfNotNull("privateKeyFile", privateKeyFile)
-                    .putIfNotNull("privateKeyData", privateKeyData)
-                    .putIfNotNull("localTempDir", localTempDir)
-                    .build(), 
-                FixedListMachineProvisioningLocation.class);
-        }        
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/HasSubnetHostname.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/HasSubnetHostname.java b/core/src/main/java/org/apache/brooklyn/location/basic/HasSubnetHostname.java
deleted file mode 100644
index e9fbece..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/HasSubnetHostname.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import com.google.common.annotations.Beta;
-
-@Beta
-public interface HasSubnetHostname {
-
-    /** returns a hostname for use internally within a subnet / VPC */
-    @Beta
-    String getSubnetHostname();
-
-    /** returns an IP for use internally within a subnet / VPC */
-    String getSubnetIp();
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/HostLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/HostLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/basic/HostLocationResolver.java
deleted file mode 100644
index ae68f68..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/HostLocationResolver.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationRegistry;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.location.basic.AbstractLocationResolver.SpecParser.ParsedSpec;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.guava.Maybe.Absent;
-import org.apache.brooklyn.util.text.KeyValueParser;
-
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-
-public class HostLocationResolver extends AbstractLocationResolver {
-    
-    private static final String HOST = "host";
-    
-    @SuppressWarnings("rawtypes")
-    @Override
-    public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
-        // Extract args from spec
-        ParsedSpec parsedSpec = specParser.parse(spec);
-        Map<String, String> argsMap = parsedSpec.argsMap;
-        if (argsMap.isEmpty()) {
-            throw new IllegalArgumentException("Invalid host spec (no host supplied): "+spec);
-        } else if (argsMap.size() == 1 && Iterables.get(argsMap.values(), 0) == null) {
-            // only given ip or hostname
-            argsMap = ImmutableMap.of("hosts", Iterables.get(argsMap.keySet(), 0));
-        } else if (!(argsMap.containsKey("host") || argsMap.containsKey("hosts"))) {
-            throw new IllegalArgumentException("Invalid host spec (no host supplied): "+spec);
-        }
-
-        // Find generic applicable properties
-        Map globalProperties = registry.getProperties();
-        String namedLocation = (String) locationFlags.get(LocationInternal.NAMED_SPEC_NAME.getName());
-        Map<String, Object> filteredProperties = new LocationPropertiesFromBrooklynProperties().getLocationProperties(null, namedLocation, globalProperties);
-        ConfigBag flags = ConfigBag.newInstance(locationFlags).putIfAbsent(filteredProperties);
-        flags.remove(LocationInternal.NAMED_SPEC_NAME);
-
-        // Generate target spec
-        String target = "byon("+KeyValueParser.toLine(argsMap)+")";
-        Maybe<Location> testResolve = managementContext.getLocationRegistry().resolve(target, false, null);
-        if (!testResolve.isPresent()) {
-            throw new IllegalArgumentException("Invalid target location '" + target + "' for location '"+HOST+"': "+
-                Exceptions.collapseText( ((Absent<?>)testResolve).getException() ), ((Absent<?>)testResolve).getException());
-        }
-        
-        return managementContext.getLocationManager().createLocation(LocationSpec.create(SingleMachineProvisioningLocation.class)
-                .configure("location", target)
-                .configure("locationFlags", flags.getAllConfig())
-                .configure(LocationConfigUtils.finalAndOriginalSpecs(spec, locationFlags, globalProperties, namedLocation)));
-    }
-    
-    @Override
-    public String getPrefix() {
-        return HOST;
-    }
-    
-    @Override
-    protected Class<? extends Location> getLocationType() {
-        return SingleMachineProvisioningLocation.class;
-    }
-
-    @Override
-    protected SpecParser getSpecParser() {
-        return new SpecParser(getPrefix()).setExampleUsage("\"host(1.1.1.1)\" or \"host(host=1.1.1.1,name=myname)\"");
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/LocalhostLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/LocalhostLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/basic/LocalhostLocationResolver.java
deleted file mode 100644
index 9f9bff6..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/LocalhostLocationResolver.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationRegistry;
-import org.apache.brooklyn.api.location.LocationResolver;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-
-/**
- * Examples of valid specs:
- *   <ul>
- *     <li>localhost
- *     <li>localhost()
- *     <li>localhost(name=abc)
- *     <li>localhost(name="abc")
- *   </ul>
- * 
- * @author alex, aled
- */
-public class LocalhostLocationResolver extends AbstractLocationResolver implements LocationResolver.EnableableLocationResolver {
-
-    public static final String LOCALHOST = "localhost";
-
-    @Override
-    public String getPrefix() {
-        return LOCALHOST;
-    }
-
-    @Override
-    public boolean isEnabled() {
-        return LocationConfigUtils.isEnabled(managementContext, "brooklyn.location.localhost");
-    }
-
-    @Override
-    protected Class<? extends Location> getLocationType() {
-        return LocalhostMachineProvisioningLocation.class;
-    }
-
-    @Override
-    protected SpecParser getSpecParser() {
-        return new AbstractLocationResolver.SpecParser(getPrefix()).setExampleUsage("\"localhost\" or \"localhost(displayName=abc)\"");
-    }
-
-    @Override
-    protected Map<String, Object> getFilteredLocationProperties(String provider, String namedLocation, Map<String, ?> globalProperties) {
-        return new LocalhostPropertiesFromBrooklynProperties().getLocationProperties("localhost", namedLocation, globalProperties);
-    }
-
-    @Override
-    protected ConfigBag extractConfig(Map<?,?> locationFlags, String spec, LocationRegistry registry) {
-        ConfigBag config = super.extractConfig(locationFlags, spec, registry);
-        config.putAsStringKeyIfAbsent("name", "localhost");
-        return config;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/LocalhostMachineProvisioningLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/LocalhostMachineProvisioningLocation.java b/core/src/main/java/org/apache/brooklyn/location/basic/LocalhostMachineProvisioningLocation.java
deleted file mode 100644
index 1257c1b..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/LocalhostMachineProvisioningLocation.java
+++ /dev/null
@@ -1,346 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.apache.brooklyn.util.GroovyJavaMethods.elvis;
-import static org.apache.brooklyn.util.GroovyJavaMethods.truth;
-
-import java.io.File;
-import java.net.InetAddress;
-import java.util.Arrays;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.brooklyn.api.location.AddressableLocation;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.MachineProvisioningLocation;
-import org.apache.brooklyn.api.location.OsDetails;
-import org.apache.brooklyn.api.location.PortRange;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.config.ConfigKey.HasConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.mgmt.rebind.persister.FileBasedObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.LocationWithObjectStore;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.location.geo.HostGeoInfo;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.BrooklynNetworkUtils;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.apache.brooklyn.util.core.internal.ssh.process.ProcessTool;
-import org.apache.brooklyn.util.core.mutex.MutexSupport;
-import org.apache.brooklyn.util.core.mutex.WithMutexes;
-import org.apache.brooklyn.util.net.Networking;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.ssh.BashCommands;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-
-/**
- * An implementation of {@link MachineProvisioningLocation} that can provision a {@link SshMachineLocation} for the
- * local host.
- *
- * By default you can only obtain a single SshMachineLocation for the localhost. Optionally, you can "overload"
- * and choose to allow localhost to be provisioned multiple times, which may be useful in some testing scenarios.
- */
-public class LocalhostMachineProvisioningLocation extends FixedListMachineProvisioningLocation<SshMachineLocation> implements AddressableLocation, LocationWithObjectStore {
-
-    public static final Logger LOG = LoggerFactory.getLogger(LocalhostMachineProvisioningLocation.class);
-    
-    public static final ConfigKey<Boolean> SKIP_ON_BOX_BASE_DIR_RESOLUTION = ConfigKeys.newConfigKeyWithDefault(
-            BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, 
-            true);
-    
-    @SetFromFlag("count")
-    int initialCount;
-
-    @SetFromFlag
-    Boolean canProvisionMore;
-    
-    @SetFromFlag
-    InetAddress address;
-
-    private static Set<Integer> portsInUse = Sets.newLinkedHashSet();
-
-    private static HostGeoInfo cachedHostGeoInfo;
-    
-    @VisibleForTesting
-    public static void clearStaticData() {
-        portsInUse.clear();
-        cachedHostGeoInfo = null;
-    }
-        
-    /**
-     * Construct a new instance.
-     *
-     * The constructor recognises the following properties:
-     * <ul>
-     * <li>count - number of localhost machines to make available
-     * </ul>
-     */
-    public LocalhostMachineProvisioningLocation() {
-        this(Maps.newLinkedHashMap());
-    }
-    /**
-     * @param properties the properties of the new instance.
-     * @deprecated since 0.6
-     * @see #LocalhostMachineProvisioningLocation()
-     */
-    public LocalhostMachineProvisioningLocation(Map properties) {
-        super(properties);
-    }
-    public LocalhostMachineProvisioningLocation(String name) {
-        this(name, 0);
-    }
-    public LocalhostMachineProvisioningLocation(String name, int count) {
-        this(MutableMap.of("name", name, "count", count));
-    }
-    
-    public static LocationSpec<LocalhostMachineProvisioningLocation> spec() {
-        return LocationSpec.create(LocalhostMachineProvisioningLocation.class);
-    }
-    
-    public LocalhostMachineProvisioningLocation configure(Map<?,?> flags) {
-        super.configure(flags);
-        
-        if (!truth(getDisplayName())) { setDisplayName("localhost"); }
-        if (!truth(address)) address = getLocalhostInetAddress();
-        // TODO should try to confirm this machine is accessible on the given address ... but there's no 
-        // immediate convenience in java so early-trapping of that particular error is deferred
-        
-        if (canProvisionMore==null) {
-            if (initialCount>0) canProvisionMore = false;
-            else canProvisionMore = true;
-        }
-        if (getHostGeoInfo()==null) {
-            if (cachedHostGeoInfo==null)
-                cachedHostGeoInfo = HostGeoInfo.fromLocation(this);
-            setHostGeoInfo(cachedHostGeoInfo);
-        }
-        if (initialCount > getMachines().size()) {
-            provisionMore(initialCount - getMachines().size());
-        }
-        
-        if (getConfig(BrooklynConfigKeys.ONBOX_BASE_DIR)==null && (getManagementContext()==null || getManagementContext().getConfig().getConfig(BrooklynConfigKeys.ONBOX_BASE_DIR)==null)) {
-            setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, "/tmp/brooklyn-"+Os.user());
-        }
-        
-        return this;
-    }
-    
-    public static InetAddress getLocalhostInetAddress() {
-        return BrooklynNetworkUtils.getLocalhostInetAddress();
-    }
-
-    @Override
-    public InetAddress getAddress() {
-        return address;
-    }
-    
-    @Override
-    public boolean canProvisionMore() {
-        return canProvisionMore;
-    }
-    
-    @Override
-    protected void provisionMore(int size, Map<?,?> flags) {
-        for (int i=0; i<size; i++) {
-            Map<Object,Object> flags2 = MutableMap.<Object,Object>builder()
-                    .putAll(flags)
-                    .put("address", elvis(address, Networking.getLocalHost()))
-                    .put("mutexSupport", LocalhostMachine.mutexSupport)
-                    .build();
-            
-            // copy inherited keys for ssh; 
-            // shouldn't be necessary but not sure that all contexts traverse the hierarchy
-            // NOTE: changed Nov 2013 to copy only those ssh config keys actually set, rather than all of them
-            // TODO should take the plunge and try removing this altogether!
-            // (or alternatively switch to copying all ancestor keys)
-            for (HasConfigKey<?> k: SshMachineLocation.ALL_SSH_CONFIG_KEYS) {
-                if (config().getRaw(k).isPresent())
-                    flags2.put(k, getConfig(k));
-            }
-            
-            if (isManaged()) {
-                addChild(LocationSpec.create(LocalhostMachine.class).configure(flags2));
-            } else {
-                addChild(new LocalhostMachine(flags2)); // TODO legacy way
-            }
-       }
-    }
-
-    public static synchronized boolean obtainSpecificPort(InetAddress localAddress, int portNumber) {
-        if (portsInUse.contains(portNumber)) {
-            return false;
-        } else {
-            //see if it is available?
-            if (!checkPortAvailable(localAddress, portNumber)) {
-                return false;
-            }
-            portsInUse.add(portNumber);
-            return true;
-        }
-    }
-    /** checks the actual availability of the port on localhost, ie by binding to it; cf {@link Networking#isPortAvailable(int)} */
-    public static boolean checkPortAvailable(InetAddress localAddress, int portNumber) {
-        if (portNumber<1024) {
-            if (LOG.isDebugEnabled()) LOG.debug("Skipping system availability check for privileged localhost port "+portNumber);
-            return true;
-        }
-        return Networking.isPortAvailable(localAddress, portNumber);
-    }
-    public static int obtainPort(PortRange range) {
-        return obtainPort(getLocalhostInetAddress(), range);
-    }
-    public static int obtainPort(InetAddress localAddress, PortRange range) {
-        for (int p: range)
-            if (obtainSpecificPort(localAddress, p)) return p;
-        if (LOG.isDebugEnabled()) LOG.debug("unable to find port in {} on {}; returning -1", range, localAddress);
-        return -1;
-    }
-
-    public static synchronized void releasePort(InetAddress localAddress, int portNumber) {
-        portsInUse.remove((Object) portNumber);
-    }
-
-    public void release(SshMachineLocation machine) {
-        LocalhostMachine localMachine = (LocalhostMachine) machine;
-        Set<Integer> portsObtained = Sets.newLinkedHashSet();
-        synchronized (localMachine.portsObtained) {
-            portsObtained.addAll(localMachine.portsObtained);
-        }
-        
-        super.release(machine);
-        
-        for (int p: portsObtained)
-            releasePort(null, p);
-    }
-    
-    public static class LocalhostMachine extends SshMachineLocation implements HasSubnetHostname {
-        // declaring this here (as well as on LocalhostMachineProvisioningLocation) because:
-        //  1. machine.getConfig(key) will not inherit default value of machine.getParent()'s key
-        //  2. things might instantiate a `LocalhostMachine` without going through LocalhostMachineProvisioningLocation
-        //     so not sufficient for LocalhostMachineProvisioningLocation to just push its config value into
-        //     the LocalhostMachine instance.
-        public static final ConfigKey<Boolean> SKIP_ON_BOX_BASE_DIR_RESOLUTION = ConfigKeys.newConfigKeyWithDefault(
-                BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, 
-                true);
-
-        private static final WithMutexes mutexSupport = new MutexSupport();
-        
-        private final Set<Integer> portsObtained = Sets.newLinkedHashSet();
-
-        public LocalhostMachine() {
-            super();
-        }
-        /** @deprecated since 0.6.0 use no-arg constructor (and spec) then configure */
-        public LocalhostMachine(Map properties) {
-            super(MutableMap.builder().putAll(properties).put("mutexSupport", mutexSupport).build());
-        }
-        
-        @Override
-        protected WithMutexes getMutexSupport() {
-            return mutexSupport;
-        }
-        
-        public boolean obtainSpecificPort(int portNumber) {
-            if (!isSudoAllowed() && portNumber <= 1024)
-                return false;
-            return LocalhostMachineProvisioningLocation.obtainSpecificPort(getAddress(), portNumber);
-        }
-        
-        public int obtainPort(PortRange range) {
-            int r = LocalhostMachineProvisioningLocation.obtainPort(getAddress(), range);
-            synchronized (portsObtained) {
-                if (r>0) portsObtained.add(r);
-            }
-            LOG.debug("localhost.obtainPort("+range+"), returning "+r);
-            return r;
-        }
-        
-        @Override
-        public void releasePort(int portNumber) {
-            synchronized (portsObtained) {
-                portsObtained.remove((Object)portNumber);
-            }
-            LocalhostMachineProvisioningLocation.releasePort(getAddress(), portNumber);
-        }
-        
-        @Override
-        public OsDetails getOsDetails() {
-            return BasicOsDetails.Factory.newLocalhostInstance();
-        }
-        
-        @Override
-        public LocalhostMachine configure(Map<?,?> properties) {
-            if (address==null || !properties.containsKey("address"))
-                address = Networking.getLocalHost();
-            super.configure(properties);
-            return this;
-        }
-        @Override
-        public String getSubnetHostname() {
-           return Networking.getLocalHost().getHostName();
-        }
-        @Override
-        public String getSubnetIp() {
-            return Networking.getLocalHost().getHostAddress();
-        }
-    }
-
-    private static class SudoChecker {
-        static volatile long lastSudoCheckTime = -1;
-        static boolean lastSudoResult = false;
-        public static boolean isSudoAllowed() {
-            if (Time.hasElapsedSince(lastSudoCheckTime, Duration.FIVE_MINUTES))
-                checkIfNeeded();                    
-            return lastSudoResult;
-        }
-        private static synchronized void checkIfNeeded() {
-            if (Time.hasElapsedSince(lastSudoCheckTime, Duration.FIVE_MINUTES)) {
-                try {
-                    lastSudoResult = new ProcessTool().execCommands(MutableMap.<String,Object>of(), Arrays.asList(
-                            BashCommands.sudo("date"))) == 0;
-                } catch (Exception e) {
-                    lastSudoResult = false;
-                    LOG.debug("Error checking sudo at localhost: "+e, e);
-                }
-                lastSudoCheckTime = System.currentTimeMillis();
-            }
-        }
-    }
-
-    public static boolean isSudoAllowed() {
-        return SudoChecker.isSudoAllowed();
-    }
-
-    @Override
-    public PersistenceObjectStore newPersistenceObjectStore(String container) {
-        File basedir = new File(container);
-        if (basedir.isFile()) throw new IllegalArgumentException("Destination directory must not be a file");
-        return new FileBasedObjectStore(basedir);
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/LocalhostPropertiesFromBrooklynProperties.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/LocalhostPropertiesFromBrooklynProperties.java b/core/src/main/java/org/apache/brooklyn/location/basic/LocalhostPropertiesFromBrooklynProperties.java
deleted file mode 100644
index 10e7332..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/LocalhostPropertiesFromBrooklynProperties.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.util.Map;
-
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Strings;
-
-/**
- * @author aledsage
- **/
-public class LocalhostPropertiesFromBrooklynProperties extends LocationPropertiesFromBrooklynProperties {
-
-    // TODO Once delete support for deprecated "location.localhost.*" then can get rid of this class, and use
-    // LocationPropertiesFromBrooklynProperties directly
-    
-    @SuppressWarnings("unused")
-    private static final Logger LOG = LoggerFactory.getLogger(LocalhostPropertiesFromBrooklynProperties.class);
-
-    @Override
-    public Map<String, Object> getLocationProperties(String provider, String namedLocation, Map<String, ?> properties) {
-        if (Strings.isNullOrEmpty(namedLocation) && Strings.isNullOrEmpty(provider)) {
-            throw new IllegalArgumentException("Neither cloud provider/API nor location name have been specified correctly");
-        }
-
-        ConfigBag result = ConfigBag.newInstance();
-        
-        result.putAll(transformDeprecated(getGenericLocationSingleWordProperties(properties)));
-        result.putAll(transformDeprecated(getMatchingSingleWordProperties("brooklyn.location.", properties)));
-        result.putAll(transformDeprecated(getMatchingProperties("brooklyn.location.localhost.", "brooklyn.localhost.", properties)));
-        if (!Strings.isNullOrEmpty(namedLocation)) result.putAll(transformDeprecated(getNamedLocationProperties(namedLocation, properties)));
-        setLocalTempDir(properties, result);
-        
-        return result.getAllConfigRaw();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/LocationConfigKeys.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/LocationConfigKeys.java b/core/src/main/java/org/apache/brooklyn/location/basic/LocationConfigKeys.java
deleted file mode 100644
index 3581bfb..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/LocationConfigKeys.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.io.File;
-import java.util.Set;
-
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.BasicConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.util.os.Os;
-
-import com.google.common.base.CaseFormat;
-import com.google.common.reflect.TypeToken;
-
-public class LocationConfigKeys {
-
-    public static final ConfigKey<String> LOCATION_ID = ConfigKeys.newStringConfigKey("id");
-    public static final ConfigKey<String> DISPLAY_NAME = ConfigKeys.newStringConfigKey("displayName");
-    public static final ConfigKey<Boolean> ENABLED = ConfigKeys.newBooleanConfigKey("enabled", "Whether the location is enabled for listing and use "
-        + "(only supported for selected locations)", true);
-    
-    public static final ConfigKey<String> ACCESS_IDENTITY = ConfigKeys.newStringConfigKey("identity"); 
-    public static final ConfigKey<String> ACCESS_CREDENTIAL = ConfigKeys.newStringConfigKey("credential"); 
-
-    public static final ConfigKey<Double> LATITUDE = new BasicConfigKey<Double>(Double.class, "latitude"); 
-    public static final ConfigKey<Double> LONGITUDE = new BasicConfigKey<Double>(Double.class, "longitude"); 
-
-    public static final ConfigKey<String> CLOUD_PROVIDER = ConfigKeys.newStringConfigKey("provider");
-    public static final ConfigKey<String> CLOUD_ENDPOINT = ConfigKeys.newStringConfigKey("endpoint");
-    public static final ConfigKey<String> CLOUD_REGION_ID = ConfigKeys.newStringConfigKey("region");
-    public static final ConfigKey<String> CLOUD_AVAILABILITY_ZONE_ID = ConfigKeys.newStringConfigKey("availabilityZone");
-
-    @SuppressWarnings("serial")
-    public static final ConfigKey<Set<String>> ISO_3166 = ConfigKeys.newConfigKey(new TypeToken<Set<String>>() {}, "iso3166", "ISO-3166 or ISO-3166-2 location codes"); 
-
-    public static final ConfigKey<String> USER = ConfigKeys.newStringConfigKey("user", 
-            "user account for normal access to the remote machine, defaulting to local user", System.getProperty("user.name"));
-    
-    public static final ConfigKey<String> PASSWORD = ConfigKeys.newStringConfigKey("password", "password to use for ssh; note some images do not allow password-based ssh access");
-    public static final ConfigKey<String> PUBLIC_KEY_FILE = ConfigKeys.newStringConfigKey("publicKeyFile", "ssh public key file to use; if blank will infer from privateKeyFile by appending \".pub\"");
-    public static final ConfigKey<String> PUBLIC_KEY_DATA = ConfigKeys.newStringConfigKey("publicKeyData", "ssh public key string to use (takes precedence over publicKeyFile)");
-    public static final ConfigKey<String> PRIVATE_KEY_FILE = ConfigKeys.newStringConfigKey("privateKeyFile", "a '" + File.pathSeparator + "' separated list of ssh private key files; uses first in list that can be read",
-                                                                                           Os.fromHome(".ssh/id_rsa") + File.pathSeparator + Os.fromHome(".ssh/id_dsa"));
-    public static final ConfigKey<String> PRIVATE_KEY_DATA = ConfigKeys.newStringConfigKey("privateKeyData", "ssh private key string to use (takes precedence over privateKeyFile)");
-    public static final ConfigKey<String> PRIVATE_KEY_PASSPHRASE = ConfigKeys.newStringConfigKey("privateKeyPassphrase");
-
-    /** @deprecated since 0.6.0; included here so it gets picked up in auto-detect routines */ @Deprecated
-    public static final ConfigKey<String> LEGACY_PUBLIC_KEY_FILE = ConfigKeys.convert(PUBLIC_KEY_FILE, CaseFormat.LOWER_CAMEL, CaseFormat.LOWER_HYPHEN);
-    /** @deprecated since 0.6.0; included here so it gets picked up in auto-detect routines */ @Deprecated
-    public static final ConfigKey<String> LEGACY_PUBLIC_KEY_DATA = ConfigKeys.convert(PUBLIC_KEY_DATA, CaseFormat.LOWER_CAMEL, CaseFormat.LOWER_HYPHEN);
-    /** @deprecated since 0.6.0; included here so it gets picked up in auto-detect routines */ @Deprecated
-    public static final ConfigKey<String> LEGACY_PRIVATE_KEY_FILE = ConfigKeys.convert(PRIVATE_KEY_FILE, CaseFormat.LOWER_CAMEL, CaseFormat.LOWER_HYPHEN);
-    /** @deprecated since 0.6.0; included here so it gets picked up in auto-detect routines */ @Deprecated
-    public static final ConfigKey<String> LEGACY_PRIVATE_KEY_DATA = ConfigKeys.convert(PRIVATE_KEY_DATA, CaseFormat.LOWER_CAMEL, CaseFormat.LOWER_HYPHEN);
-    /** @deprecated since 0.6.0; included here so it gets picked up in auto-detect routines */ @Deprecated
-    public static final ConfigKey<String> LEGACY_PRIVATE_KEY_PASSPHRASE = ConfigKeys.convert(PRIVATE_KEY_PASSPHRASE, CaseFormat.LOWER_CAMEL, CaseFormat.LOWER_HYPHEN);
-
-    public static final ConfigKey<Object> CALLER_CONTEXT = new BasicConfigKey<Object>(Object.class, "callerContext",
-            "An object whose toString is used for logging, to indicate wherefore a VM is being created");
-    public static final ConfigKey<String> CLOUD_MACHINE_NAMER_CLASS = ConfigKeys.newStringConfigKey("cloudMachineNamer", "fully qualified class name of a class that extends CloudMachineNamer and has a single-parameter constructor that takes a ConfigBag");
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/LocationConfigUtils.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/LocationConfigUtils.java b/core/src/main/java/org/apache/brooklyn/location/basic/LocationConfigUtils.java
deleted file mode 100644
index 9f70a6e..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/LocationConfigUtils.java
+++ /dev/null
@@ -1,558 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.apache.brooklyn.util.JavaGroovyEquivalents.groovyTruth;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.security.KeyPair;
-import java.security.PublicKey;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.internal.BrooklynFeatureEnablement;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.cloud.CloudLocationConfig;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.collections.MutableSet;
-import org.apache.brooklyn.util.core.ResourceUtils;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-import org.apache.brooklyn.util.core.crypto.SecureKeys;
-import org.apache.brooklyn.util.core.crypto.SecureKeys.PassphraseProblem;
-import org.apache.brooklyn.util.crypto.AuthorizedKeysParser;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.text.StringFunctions;
-import org.apache.brooklyn.util.text.Strings;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Objects;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
-public class LocationConfigUtils {
-
-    private static final Logger log = LoggerFactory.getLogger(LocationConfigUtils.class);
-
-    /** Creates an instance of {@link OsCredential} by inspecting {@link LocationConfigKeys#PASSWORD}; 
-     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE};
-     * {@link LocationConfigKeys#PRIVATE_KEY_PASSPHRASE} if needed, and
-     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE}
-     * (defaulting to the private key file + ".pub"). 
-     **/
-    public static OsCredential getOsCredential(ConfigBag config) {
-        return OsCredential.newInstance(config);
-    }
-    
-    /** Convenience class for holding private/public keys and passwords, inferring from config keys.
-     * See {@link LocationConfigUtils#getOsCredential(ConfigBag)}. */
-    @Beta // would be nice to replace with a builder pattern 
-    public static class OsCredential {
-        private final ConfigBag config;
-        private boolean preferPassword = false;
-        private boolean tryDefaultKeys = true;
-        private boolean requirePublicKey = true;
-        private boolean doKeyValidation = BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_VALIDATE_LOCATION_SSH_KEYS);
-        private boolean warnOnErrors = true;
-        private boolean throwOnErrors = false;
-        
-        private boolean dirty = true;;
-        
-        private String privateKeyData;
-        private String publicKeyData;
-        private String password;
-        
-        private OsCredential(ConfigBag config) {
-            this.config = config;
-        }
-
-        /** throws if there are any problems */
-        public OsCredential checkNotEmpty() {
-            checkNoErrors();
-            
-            if (!hasKey() && !hasPassword()) {
-                if (warningMessages.size()>0)
-                    throw new IllegalStateException("Could not find credentials: "+warningMessages);
-                else 
-                    throw new IllegalStateException("Could not find credentials");
-            }
-            return this;
-        }
-
-        /** throws if there were errors resolving (e.g. explicit keys, none of which were found/valid, or public key required and not found) 
-         * @return */
-        public OsCredential checkNoErrors() {
-            throwOnErrors(true);
-            dirty();
-            infer();
-            return this;
-        }
-        
-        public OsCredential logAnyWarnings() {
-            if (!warningMessages.isEmpty())
-                log.warn("When reading credentials: "+warningMessages);
-            return this;
-        }
-
-        public Set<String> getWarningMessages() {
-            return warningMessages;
-        }
-        
-        /** returns either the key or password or null; if both a key and a password this prefers the key unless otherwise set
-         * via {@link #preferPassword()} */
-        public synchronized String getPreferredCredential() {
-            infer();
-            
-            if (isUsingPassword()) return password;
-            if (hasKey()) return privateKeyData;
-            return null;
-        }
-
-        /** if there is no credential (ignores public key) */
-        public boolean isEmpty() {
-            return !hasKey() && !hasPassword();
-        }
-        public boolean hasKey() {
-            infer();
-            // key has stricter non-blank check than password
-            return Strings.isNonBlank(privateKeyData);
-        }
-        public boolean hasPassword() {
-            infer();
-            // blank, even empty passwords are allowed
-            return password!=null;
-        }
-        /** if a password is available, and either this is preferred over a key or there is no key */
-        public boolean isUsingPassword() {
-            return hasPassword() && (!hasKey() || preferPassword);
-        }
-        
-        public String getPrivateKeyData() {
-            infer();
-            return privateKeyData;
-        }
-        public String getPublicKeyData() {
-            infer();
-            return publicKeyData;
-        }
-        public String getPassword() {
-            infer();
-            return password;
-        }
-        
-        /** if both key and password supplied, prefer the key; the default */
-        public OsCredential preferKey() { preferPassword = false; return dirty(); }
-        /** if both key and password supplied, prefer the password; see {@link #preferKey()} */
-        public OsCredential preferPassword() { preferPassword = true; return dirty(); }
-        
-        /** if false, do not mind if there is no public key corresponding to any private key;
-         * defaults to true; only applies if a private key is set */
-        public OsCredential requirePublicKey(boolean requirePublicKey) {
-            this.requirePublicKey = requirePublicKey;
-            return dirty(); 
-        }
-        /** whether to check the private/public keys and passphrase are coherent; default true */
-        public OsCredential doKeyValidation(boolean doKeyValidation) {
-            this.doKeyValidation = doKeyValidation;
-            return dirty();
-        }
-        /** if true (the default) this will look at default locations set on keys */
-        public OsCredential useDefaultKeys(boolean tryDefaultKeys) {
-            this.tryDefaultKeys = tryDefaultKeys;
-            return dirty(); 
-        }
-        /** whether to log warnings on problems */
-        public OsCredential warnOnErrors(boolean warnOnErrors) {
-            this.warnOnErrors = warnOnErrors;
-            return dirty(); 
-        }
-        /** whether to throw on problems */
-        public OsCredential throwOnErrors(boolean throwOnErrors) {
-            this.throwOnErrors = throwOnErrors;
-            return dirty(); 
-        }
-        
-        private OsCredential dirty() { dirty = true; return this; }
-            
-        public static OsCredential newInstance(ConfigBag config) {
-            return new OsCredential(config);
-        }
-        
-        private synchronized void infer() {
-            if (!dirty) return;
-            warningMessages.clear(); 
-            
-            log.debug("Inferring OS credentials");
-            privateKeyData = config.get(LocationConfigKeys.PRIVATE_KEY_DATA);
-            password = config.get(LocationConfigKeys.PASSWORD);
-            publicKeyData = getKeyDataFromDataKeyOrFileKey(config, LocationConfigKeys.PUBLIC_KEY_DATA, LocationConfigKeys.PUBLIC_KEY_FILE);
-
-            KeyPair privateKey = null;
-            
-            if (Strings.isBlank(privateKeyData)) {
-                // look up private key files
-                String privateKeyFiles = null;
-                boolean privateKeyFilesExplicitlySet = config.containsKey(LocationConfigKeys.PRIVATE_KEY_FILE);
-                if (privateKeyFilesExplicitlySet || (tryDefaultKeys && password==null)) 
-                    privateKeyFiles = config.get(LocationConfigKeys.PRIVATE_KEY_FILE);
-                if (Strings.isNonBlank(privateKeyFiles)) {
-                    Iterator<String> fi = Arrays.asList(privateKeyFiles.split(File.pathSeparator)).iterator();
-                    while (fi.hasNext()) {
-                        String file = fi.next();
-                        if (Strings.isNonBlank(file)) {
-                            try {
-                                // real URL's won't actual work, due to use of path separator above 
-                                // not real important, but we get it for free if "files" is a list instead.
-                                // using ResourceUtils is useful for classpath resources
-                                if (file!=null)
-                                    privateKeyData = ResourceUtils.create().getResourceAsString(file);
-                                // else use data already set
-                                
-                                privateKey = getValidatedPrivateKey(file);
-                                
-                                if (privateKeyData==null) {
-                                    // was cleared due to validation error
-                                } else if (Strings.isNonBlank(publicKeyData)) {
-                                    log.debug("Loaded private key data from "+file+" (public key data explicitly set)");
-                                    break;
-                                } else {
-                                    String publicKeyFile = (file!=null ? file+".pub" : "(data)");
-                                    try {
-                                        publicKeyData = ResourceUtils.create().getResourceAsString(publicKeyFile);
-                                        
-                                        log.debug("Loaded private key data from "+file+
-                                            " and public key data from "+publicKeyFile);
-                                        break;
-                                    } catch (Exception e) {
-                                        Exceptions.propagateIfFatal(e);
-                                        log.debug("No public key file "+publicKeyFile+"; will try extracting from private key");
-                                        publicKeyData = AuthorizedKeysParser.encodePublicKey(privateKey.getPublic());
-                                        
-                                        if (publicKeyData==null) {
-                                            if (requirePublicKey) {
-                                                addWarning("Unable to find or extract public key for "+file, "skipping");
-                                            } else {
-                                                log.debug("Loaded private key data from "+file+" (public key data not found but not required)");
-                                                break;
-                                            }
-                                        } else {
-                                            log.debug("Loaded private key data from "+file+" (public key data extracted)");
-                                            break;
-                                        }
-                                        privateKeyData = null;
-                                    }
-                                }
-
-                            } catch (Exception e) {
-                                Exceptions.propagateIfFatal(e);
-                                String message = "Missing/invalid private key file "+file;
-                                if (privateKeyFilesExplicitlySet) addWarning(message, (!fi.hasNext() ? "no more files to try" : "trying next file")+": "+e);
-                            }
-                        }
-                    }
-                    if (privateKeyFilesExplicitlySet && Strings.isBlank(privateKeyData))
-                        error("No valid private keys found", ""+warningMessages);
-                }
-            } else {
-                privateKey = getValidatedPrivateKey("(data)");
-            }
-            
-            if (privateKeyData!=null) {
-                if (requirePublicKey && Strings.isBlank(publicKeyData)) {
-                    if (privateKey!=null) {
-                        publicKeyData = AuthorizedKeysParser.encodePublicKey(privateKey.getPublic());
-                    }
-                    if (Strings.isBlank(publicKeyData)) {
-                        error("If explicit "+LocationConfigKeys.PRIVATE_KEY_DATA.getName()+" is supplied, then "
-                            + "the corresponding "+LocationConfigKeys.PUBLIC_KEY_DATA.getName()+" must also be supplied.", null);
-                    } else {
-                        log.debug("Public key data extracted");
-                    }
-                }
-                if (doKeyValidation && privateKey!=null && privateKey.getPublic()!=null && Strings.isNonBlank(publicKeyData)) {
-                    PublicKey decoded = null;
-                    try {
-                        decoded = AuthorizedKeysParser.decodePublicKey(publicKeyData);
-                    } catch (Exception e) {
-                        Exceptions.propagateIfFatal(e);
-                        addWarning("Invalid public key: "+decoded);
-                    }
-                    if (decoded!=null && !privateKey.getPublic().equals( decoded )) {
-                        error("Public key inferred from does not match public key extracted from private key", null);
-                    }
-                }
-            }
-
-            log.debug("OS credential inference: "+this);
-            dirty = false;
-        }
-
-        private KeyPair getValidatedPrivateKey(String label) {
-            KeyPair privateKey = null;
-            String passphrase = config.get(CloudLocationConfig.PRIVATE_KEY_PASSPHRASE);
-            try {
-                privateKey = SecureKeys.readPem(new ByteArrayInputStream(privateKeyData.getBytes()), passphrase);
-                if (passphrase!=null) {
-                    // get the unencrypted key data for our internal use (jclouds requires this)
-                    privateKeyData = SecureKeys.toPem(privateKey);
-                }
-            } catch (PassphraseProblem e) {
-                if (doKeyValidation) {
-                    log.debug("Encountered error handling key "+label+": "+e, e);
-                    if (Strings.isBlank(passphrase))
-                        addWarning("Passphrase required for key '"+label+"'");
-                    else
-                        addWarning("Invalid passphrase for key '"+label+"'");
-                    privateKeyData = null;
-                }
-            } catch (Exception e) {
-                Exceptions.propagateIfFatal(e);
-                if (doKeyValidation) {
-                    addWarning("Unable to parse private key from '"+label+"': unknown format");
-                    privateKeyData = null;
-                }
-            }
-            return privateKey;
-        }
-        
-        Set<String> warningMessages = MutableSet.of();
-        
-        private void error(String msg, String logExtension) {
-            addWarning(msg);
-            if (warnOnErrors) log.warn(msg+(logExtension==null ? "" : ": "+logExtension));
-            if (throwOnErrors) throw new IllegalStateException(msg+(logExtension==null ? "" : "; "+logExtension));
-        }
-
-        private void addWarning(String msg) {
-            addWarning(msg, null);
-        }
-        private void addWarning(String msg, String debugExtension) {
-            log.debug(msg+(debugExtension==null ? "" : "; "+debugExtension));
-            warningMessages.add(msg);
-        }
-
-        @Override
-        public String toString() {
-            return getClass().getSimpleName()+"["+
-                (Strings.isNonBlank(publicKeyData) ? publicKeyData : "no-public-key")+";"+
-                (Strings.isNonBlank(privateKeyData) ? "private-key-present" : "no-private-key")+","+
-                (password!=null ? "password(len="+password.length()+")" : "no-password")+"]";
-        }
-    }
-
-    /** @deprecated since 0.7.0, use #getOsCredential(ConfigBag) */ @Deprecated
-    public static String getPrivateKeyData(ConfigBag config) {
-        return getKeyData(config, LocationConfigKeys.PRIVATE_KEY_DATA, LocationConfigKeys.PRIVATE_KEY_FILE);
-    }
-    
-    /** @deprecated since 0.7.0, use #getOsCredential(ConfigBag) */ @Deprecated
-    public static String getPublicKeyData(ConfigBag config) {
-        String data = getKeyData(config, LocationConfigKeys.PUBLIC_KEY_DATA, LocationConfigKeys.PUBLIC_KEY_FILE);
-        if (groovyTruth(data)) return data;
-        
-        String privateKeyFile = config.get(LocationConfigKeys.PRIVATE_KEY_FILE);
-        if (groovyTruth(privateKeyFile)) {
-            List<String> privateKeyFiles = Arrays.asList(privateKeyFile.split(File.pathSeparator));
-            List<String> publicKeyFiles = ImmutableList.copyOf(Iterables.transform(privateKeyFiles, StringFunctions.append(".pub")));
-            List<String> publicKeyFilesTidied = tidyFilePaths(publicKeyFiles);
-            
-            String fileData = getFileContents(publicKeyFilesTidied);
-            if (groovyTruth(fileData)) {
-                if (log.isDebugEnabled()) log.debug("Loaded "+LocationConfigKeys.PUBLIC_KEY_DATA.getName()+" from inferred files, based on "+LocationConfigKeys.PRIVATE_KEY_FILE.getName() + ": used " + publicKeyFilesTidied + " for "+config.getDescription());
-                config.put(LocationConfigKeys.PUBLIC_KEY_DATA, fileData);
-                return fileData;
-            } else {
-                log.info("Not able to load "+LocationConfigKeys.PUBLIC_KEY_DATA.getName()+" from inferred files, based on "+LocationConfigKeys.PRIVATE_KEY_FILE.getName() + ": tried " + publicKeyFilesTidied + " for "+config.getDescription());
-            }
-        }
-        
-        return null;
-    }
-
-    /** @deprecated since 0.7.0, use #getOsCredential(ConfigBag) */ @Deprecated
-    public static String getKeyData(ConfigBag config, ConfigKey<String> dataKey, ConfigKey<String> fileKey) {
-        return getKeyDataFromDataKeyOrFileKey(config, dataKey, fileKey);
-    }
-    
-    private static String getKeyDataFromDataKeyOrFileKey(ConfigBag config, ConfigKey<String> dataKey, ConfigKey<String> fileKey) {
-        boolean unused = config.isUnused(dataKey);
-        String data = config.get(dataKey);
-        if (groovyTruth(data) && !unused) {
-            return data;
-        }
-        
-        String file = config.get(fileKey);
-        if (groovyTruth(file)) {
-            List<String> files = Arrays.asList(file.split(File.pathSeparator));
-            List<String> filesTidied = tidyFilePaths(files);
-            String fileData = getFileContents(filesTidied);
-            if (fileData == null) {
-                log.warn("Invalid file" + (files.size() > 1 ? "s" : "") + " for " + fileKey + " (given " + files + 
-                        (files.equals(filesTidied) ? "" : "; converted to " + filesTidied) + ") " +
-                        "may fail provisioning " + config.getDescription());
-            } else if (groovyTruth(data)) {
-                if (!fileData.trim().equals(data.trim()))
-                    log.warn(dataKey.getName()+" and "+fileKey.getName()+" both specified; preferring the former");
-            } else {
-                data = fileData;
-                config.put(dataKey, data);
-                config.get(dataKey);
-            }
-        }
-        
-        return data;
-    }
-    
-    /**
-     * Reads the given file(s) in-order, returning the contents of the first file that can be read.
-     * Returns the file contents, or null if none of the files can be read.
-     *  
-     * @param files             list of file paths
-     */
-    private static String getFileContents(Iterable<String> files) {
-        Iterator<String> fi = files.iterator();
-        while (fi.hasNext()) {
-            String file = fi.next();
-            if (groovyTruth(file)) {
-                try {
-                    // see comment above
-                    String result = ResourceUtils.create().getResourceAsString(file);
-                    if (result!=null) return result;
-                    log.debug("Invalid file "+file+" ; " + (!fi.hasNext() ? "no more files to try" : "trying next file")+" (null)");
-                } catch (Exception e) {
-                    Exceptions.propagateIfFatal(e);
-                    log.debug("Invalid file "+file+" ; " + (!fi.hasNext() ? "no more files to try" : "trying next file"), e);
-                }
-            }
-        }
-        return null;
-    }
-
-    private static List<String> tidyFilePaths(Iterable<String> files) {
-        List<String> result = Lists.newArrayList();
-        for (String file : files) {
-            result.add(Os.tidyPath(file));
-        }
-        return result;
-    }
-
-    /** @deprecated since 0.6.0 use configBag.getWithDeprecation */
-    @Deprecated
-    @SuppressWarnings("unchecked")
-    public static <T> T getConfigCheckingDeprecatedAlternatives(ConfigBag configBag, ConfigKey<T> preferredKey,
-            ConfigKey<?> ...deprecatedKeys) {
-        T value1 = (T) configBag.getWithDeprecation(preferredKey, deprecatedKeys);
-        T value2 = getConfigCheckingDeprecatedAlternativesInternal(configBag, preferredKey, deprecatedKeys);
-        if (!Objects.equal(value1, value2)) {
-            // points to a bug in one of the get-with-deprecation methods
-            log.warn("Deprecated getConfig with deprecated keys "+Arrays.toString(deprecatedKeys)+" gets different value with " +
-                    "new strategy "+preferredKey+" ("+value1+") and old ("+value2+"); preferring old value for now, but this behaviour will change");
-            return value2;
-        }
-        return value1;
-    }
-    
-    @SuppressWarnings("unchecked")
-    private static <T> T getConfigCheckingDeprecatedAlternativesInternal(ConfigBag configBag, ConfigKey<T> preferredKey,
-            ConfigKey<?> ...deprecatedKeys) {
-        ConfigKey<?> keyProvidingValue = null;
-        T value = null;
-        boolean found = false;
-        if (configBag.containsKey(preferredKey)) {
-            value = configBag.get(preferredKey);
-            found = true;
-            keyProvidingValue = preferredKey;
-        }
-        
-        for (ConfigKey<?> deprecatedKey: deprecatedKeys) {
-            T altValue = null;
-            boolean altFound = false;
-            if (configBag.containsKey(deprecatedKey)) {
-                altValue = (T) configBag.get(deprecatedKey);
-                altFound = true;
-                
-                if (altFound) {
-                    if (found) {
-                        if (Objects.equal(value, altValue)) {
-                            // fine -- nothing
-                        } else {
-                            log.warn("Detected deprecated key "+deprecatedKey+" with value "+altValue+" used in addition to "+keyProvidingValue+" " +
-                                    "with value "+value+" for "+configBag.getDescription()+"; ignoring");
-                            configBag.remove(deprecatedKey);
-                        }
-                    } else {
-                        log.warn("Detected deprecated key "+deprecatedKey+" with value "+altValue+" used instead of recommended "+preferredKey+"; " +
-                                "promoting to preferred key status; will not be supported in future versions");
-                        configBag.put(preferredKey, altValue);
-                        configBag.remove(deprecatedKey);
-                        value = altValue;
-                        found = true;
-                        keyProvidingValue = deprecatedKey;
-                    }
-                }
-            }
-        }
-        
-        if (found) {
-            return value;
-        } else {
-            return configBag.get(preferredKey); // get the default
-        }
-    }
-
-    public static Map<ConfigKey<String>,String> finalAndOriginalSpecs(String finalSpec, Object ...sourcesForOriginalSpec) {
-        // yuck!: TODO should clean up how these things get passed around
-        Map<ConfigKey<String>,String> result = MutableMap.of();
-        if (finalSpec!=null) 
-            result.put(LocationInternal.FINAL_SPEC, finalSpec);
-        
-        String originalSpec = null;
-        for (Object source: sourcesForOriginalSpec) {
-            if (source instanceof CharSequence) originalSpec = source.toString();
-            else if (source instanceof Map) {
-                if (originalSpec==null) originalSpec = Strings.toString( ((Map<?,?>)source).get(LocationInternal.ORIGINAL_SPEC) );
-                if (originalSpec==null) originalSpec = Strings.toString( ((Map<?,?>)source).get(LocationInternal.ORIGINAL_SPEC.getName()) );
-            }
-            if (originalSpec!=null) break; 
-        }
-        if (originalSpec==null) originalSpec = finalSpec;
-        if (originalSpec!=null)
-            result.put(LocationInternal.ORIGINAL_SPEC, originalSpec);
-        
-        return result;
-    }
-
-    public static boolean isEnabled(ManagementContext mgmt, String prefix) {
-        ConfigKey<Boolean> key = ConfigKeys.newConfigKeyWithPrefix(prefix+".", LocationConfigKeys.ENABLED);
-        Boolean enabled = mgmt.getConfig().getConfig(key);
-        if (enabled!=null) return enabled.booleanValue();
-        return true;
-    }
-    
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/LocationDynamicType.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/LocationDynamicType.java b/core/src/main/java/org/apache/brooklyn/location/basic/LocationDynamicType.java
deleted file mode 100644
index 0e55dbc..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/LocationDynamicType.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import org.apache.brooklyn.core.objs.BrooklynDynamicType;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationType;
-
-public class LocationDynamicType extends BrooklynDynamicType<Location, AbstractLocation> {
-
-    public LocationDynamicType(AbstractLocation location) {
-        super(location);
-    }
-    
-    public LocationType getSnapshot() {
-        return (LocationType) super.getSnapshot();
-    }
-
-    @Override
-    protected LocationTypeSnapshot newSnapshot() {
-        return new LocationTypeSnapshot(name, value(configKeys));
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/LocationInternal.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/LocationInternal.java b/core/src/main/java/org/apache/brooklyn/location/basic/LocationInternal.java
deleted file mode 100644
index ee9c419..0000000
--- a/core/src/main/java/org/apache/brooklyn/location/basic/LocationInternal.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.rebind.RebindSupport;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.LocationMemento;
-import org.apache.brooklyn.config.ConfigInheritance;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.objs.BrooklynObjectInternal;
-import org.apache.brooklyn.util.core.config.ConfigBag;
-
-import com.google.common.annotations.Beta;
-
-/**
- * Information about locations private to Brooklyn.
- */
-public interface LocationInternal extends BrooklynObjectInternal, Location {
-
-    @Beta
-    public static final ConfigKey<String> ORIGINAL_SPEC = ConfigKeys.newStringConfigKey("spec.original", "The original spec used to instantiate a location");
-    @Beta
-    public static final ConfigKey<String> FINAL_SPEC = ConfigKeys.newStringConfigKey("spec.final", "The actual spec (in a chain) which instantiates a location");
-    @Beta
-    public static final ConfigKey<String> NAMED_SPEC_NAME = ConfigKeys.newStringConfigKey("spec.named.name", "The name on the (first) named spec in a chain");
-    
-    /**
-     * Registers the given extension for the given type. If an extension already existed for
-     * this type, then this will override it.
-     * 
-     * @throws NullPointerException if extensionType or extension are null
-     * @throws IllegalArgumentException if extension does not implement extensionType
-     */
-    <T> void addExtension(Class<T> extensionType, T extension);
-
-    /**
-     * Get a record of the metadata of this location.
-     * <p/>
-     * <p>Metadata records are used to record an audit trail of events relating to location usage
-     * (for billing purposes, for example). Implementations (and subclasses) should override this
-     * method to return information useful for this purpose.</p>
-     *
-     * @return
-     */
-    public Map<String, String> toMetadataRecord();
-
-    /**
-     * @deprecated since 0.7.0; use {@link #config()}, such as {@code ((LocationInternal)location).config().getLocalBag()}
-     */
-    @Deprecated
-    ConfigBag getLocalConfigBag();
-
-    /**
-     * Returns all config, including that inherited from parents.
-     * 
-     * This method does not respect {@link ConfigInheritance} and so usage is discouraged.
-     * 
-     * @deprecated since 0.7.0; use {@link #config()}, such as {@code ((LocationInternal)location).config().getBag()}
-     */
-    @Deprecated
-    ConfigBag getAllConfigBag();
-
-    /**
-     * Users are strongly discouraged from calling or overriding this method.
-     * It is for internal calls only, relating to persisting/rebinding entities.
-     * This method may change (or be removed) in a future release without notice.
-     */
-    @Override
-    @Beta
-    RebindSupport<LocationMemento> getRebindSupport();
-    
-    ManagementContext getManagementContext();
-}



[06/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/group/DynamicClusterWithAvailabilityZonesMultiLocationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/group/DynamicClusterWithAvailabilityZonesMultiLocationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/group/DynamicClusterWithAvailabilityZonesMultiLocationTest.java
new file mode 100644
index 0000000..474ce0f
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/group/DynamicClusterWithAvailabilityZonesMultiLocationTest.java
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.group;
+
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertNull;
+
+import java.util.List;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.entity.core.EntityPredicates;
+import org.apache.brooklyn.entity.group.DynamicCluster;
+import org.apache.brooklyn.entity.group.DynamicClusterWithAvailabilityZonesTest;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.basic.MultiLocation;
+import org.apache.brooklyn.test.Asserts;
+
+import com.google.common.base.Predicate;
+import com.google.common.base.Predicates;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+
+/**
+ * Uses {@link SoftwareProcess}, so test can't be in core project.
+ * 
+ * Different from {@link DynamicClusterWithAvailabilityZonesTest} in the use of {@link MultiLocation}.
+ * However, the difference is important: the {@link SoftwareProcess} entity has two locations
+ * (the {@link MachineProvisioningLocation} and the {@link MachineLocation}, which was previously
+ * causing a failure - now fixed and tested here.
+ */
+public class DynamicClusterWithAvailabilityZonesMultiLocationTest extends BrooklynAppUnitTestSupport {
+    
+    private DynamicCluster cluster;
+    
+    private LocalhostMachineProvisioningLocation subLoc1;
+    private LocalhostMachineProvisioningLocation subLoc2;
+    private MultiLocation<?> multiLoc;
+    
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.ENABLE_AVAILABILITY_ZONES, true)
+                .configure(DynamicCluster.INITIAL_SIZE, 0)
+                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(EmptySoftwareProcess.class)));
+        
+        subLoc1 = app.newLocalhostProvisioningLocation(ImmutableMap.of("displayName", "loc1"));
+        subLoc2 = app.newLocalhostProvisioningLocation(ImmutableMap.of("displayName", "loc2"));
+        multiLoc = mgmt.getLocationManager().createLocation(LocationSpec.create(MultiLocation.class)
+                .configure(MultiLocation.SUB_LOCATIONS, ImmutableList.<MachineProvisioningLocation<?>>of(subLoc1, subLoc2)));
+    }
+
+    @Test
+    public void testReplacesEntityInSameZone() throws Exception {
+        ((EntityLocal)cluster).config().set(DynamicCluster.ENABLE_AVAILABILITY_ZONES, true);
+        cluster.start(ImmutableList.of(multiLoc));
+        
+        cluster.resize(4);
+        List<String> locsUsed = getLocationNames(getLocationsOf(cluster.getMembers(), Predicates.instanceOf(MachineProvisioningLocation.class)));
+        Asserts.assertEqualsIgnoringOrder(locsUsed, ImmutableList.of("loc1", "loc1", "loc2", "loc2"));
+
+        String idToRemove = Iterables.getFirst(cluster.getMembers(), null).getId();
+        String idAdded = cluster.replaceMember(idToRemove);
+        locsUsed = getLocationNames(getLocationsOf(cluster.getMembers(), Predicates.instanceOf(MachineProvisioningLocation.class)));
+        Asserts.assertEqualsIgnoringOrder(locsUsed, ImmutableList.of("loc1", "loc1", "loc2", "loc2"));
+        assertNull(Iterables.find(cluster.getMembers(), EntityPredicates.idEqualTo(idToRemove), null));
+        assertNotNull(Iterables.find(cluster.getMembers(), EntityPredicates.idEqualTo(idAdded), null));
+    }
+    
+    protected List<Location> getLocationsOf(Iterable<? extends Entity> entities, Predicate<? super Location> filter) {
+        List<Location> result = Lists.newArrayList();
+        for (Entity entity : entities) {
+            Iterables.addAll(result, Iterables.filter(entity.getLocations(), filter));
+        }
+        return result;
+    }
+
+    protected List<String> getLocationNames(Iterable<? extends Location> locs) {
+        List<String> result = Lists.newArrayList();
+        for (Location subLoc : locs) {
+            result.add(subLoc.getDisplayName());
+        }
+        return result;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/jmx/GeneralisedDynamicMBean.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/jmx/GeneralisedDynamicMBean.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/jmx/GeneralisedDynamicMBean.java
new file mode 100644
index 0000000..9c6c551
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/jmx/GeneralisedDynamicMBean.java
@@ -0,0 +1,146 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.jmx;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javax.management.Attribute;
+import javax.management.AttributeList;
+import javax.management.DynamicMBean;
+import javax.management.MBeanAttributeInfo;
+import javax.management.MBeanConstructorInfo;
+import javax.management.MBeanInfo;
+import javax.management.MBeanNotificationInfo;
+import javax.management.MBeanOperationInfo;
+import javax.management.MBeanParameterInfo;
+
+import com.google.common.base.Function;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Maps;
+
+/**
+ * A quick-and-simple general-purpose implementation of DynamicMBean.
+ *
+ * This class provides an implementation of {@link DynamicMBean}. Its initial set of attribute names and values are
+ * provided to the constructor; from this it figures an {@link MBeanInfo}.
+ * <p>
+ * It presently assumes that all attributes are read-only; operations and notifications are not currently supported.
+ * Choosing the descriptions is not supported - they are set to be the same as the name.
+ * <p>
+ * Getting a valid dynamic MBean (in Groovy) is as simple as:
+ * <pre>
+ * new GeneralisedDynamicMBean(meaning: 42, advice: "Don't panic")
+ * </pre>
+ */
+public class GeneralisedDynamicMBean implements DynamicMBean {
+    private final MBeanInfo mBeanInfo;
+    private final Map<String,Object> attributes = Maps.newLinkedHashMap();
+    private final Map<String,Function> operations = Maps.newLinkedHashMap();
+    
+    public GeneralisedDynamicMBean(Map<String,?> initialAttributes, Map<?,?> initialOperations) {
+        attributes.putAll(initialAttributes);
+
+        for (Entry<?,?> entry : initialOperations.entrySet()) {
+            checkArgument(entry.getKey() instanceof String || entry.getKey() instanceof MBeanOperationInfo, "entry.key=%s", entry.getKey());
+            String opName = (entry.getKey() instanceof String) ? (String)entry.getKey() : ((MBeanOperationInfo)entry.getKey()).getName();
+            operations.put(opName, (Function) entry.getValue());
+        }
+        
+        Iterable<MBeanAttributeInfo> attrInfo = Iterables.transform(initialAttributes.entrySet(), new Function<Map.Entry<String,?>, MBeanAttributeInfo>() {
+            @Override public MBeanAttributeInfo apply(Map.Entry<String,?> entry) {
+                return new MBeanAttributeInfo(entry.getKey(), entry.getValue().getClass().getName(), entry.getKey(), true, false, false);
+            }
+        });
+        
+        Iterable<MBeanOperationInfo> opInfo = Iterables.transform(initialOperations.keySet(), new Function<Object, MBeanOperationInfo>() {
+            public MBeanOperationInfo apply(Object it) {
+                if (it instanceof MBeanOperationInfo) {
+                    return (MBeanOperationInfo) it;
+                } else if (it instanceof CharSequence) {
+                    return new MBeanOperationInfo(
+                            it.toString(),
+                            "my descr", 
+                            new MBeanParameterInfo[0], 
+                            "void", 
+                            MBeanOperationInfo.ACTION_INFO);
+                } else {
+                    throw new IllegalArgumentException("Cannot convert "+it+" to MBeanOperationInfo");
+                }
+            }});
+        
+        mBeanInfo = new MBeanInfo(
+                GeneralisedDynamicMBean.class.getName(), 
+                GeneralisedDynamicMBean.class.getName(), 
+                Iterables.toArray(attrInfo, MBeanAttributeInfo.class),
+                new MBeanConstructorInfo[0], 
+                Iterables.toArray(opInfo, MBeanOperationInfo.class),
+                new MBeanNotificationInfo[0]);
+    }
+
+    public void updateAttributeValue(String name, Object value) {
+        attributes.put(name, value);
+    }
+
+    @Override
+    public Object getAttribute(String s) {
+        return attributes.get(s);
+    }
+
+    @Override
+    public void setAttribute(Attribute attribute) {
+        attributes.put(attribute.getName(), attribute.getValue());
+    }
+
+    @Override
+    public AttributeList getAttributes(String[] strings) {
+        AttributeList result = new AttributeList();
+        for (Object obj : mBeanInfo.getAttributes()) {
+            Attribute attrib = (Attribute) obj;
+            result.add(new Attribute(attrib.getName(), attributes.get(attrib.getName())));
+        }
+        return result;
+    }
+
+    @Override
+    public AttributeList setAttributes(AttributeList attributeList) {
+        for (Object element : attributeList) {
+            Attribute attrib = (Attribute) element;
+            attributes.put(attrib.getName(), attrib.getValue());
+        }
+        return attributeList;
+    }
+
+    @Override
+    public Object invoke(String s, Object[] objects, String[] strings) {
+        Function op = operations.get(s);
+        if (op != null) {
+            return op.apply(objects);
+        } else {
+            throw new RuntimeException("Unknown operation "+s);
+        }
+    }
+
+    @Override
+    public MBeanInfo getMBeanInfo() {
+        return mBeanInfo;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/jmx/JmxService.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/jmx/JmxService.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/jmx/JmxService.java
new file mode 100644
index 0000000..bb7b2a5
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/jmx/JmxService.java
@@ -0,0 +1,172 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.jmx;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.MBeanNotificationInfo;
+import javax.management.MBeanRegistrationException;
+import javax.management.MBeanServer;
+import javax.management.MBeanServerFactory;
+import javax.management.MBeanServerInvocationHandler;
+import javax.management.MalformedObjectNameException;
+import javax.management.NotCompliantMBeanException;
+import javax.management.Notification;
+import javax.management.NotificationBroadcasterSupport;
+import javax.management.NotificationEmitter;
+import javax.management.ObjectName;
+import javax.management.StandardEmitterMBean;
+import javax.management.remote.JMXConnectorServer;
+import javax.management.remote.JMXConnectorServerFactory;
+import javax.management.remote.JMXServiceURL;
+
+import mx4j.tools.naming.NamingService;
+import mx4j.tools.naming.NamingServiceMBean;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.sensor.feed.jmx.JmxHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+
+/**
+ * Set up a JMX service ready for clients to connect. This consists of an MBean server, a connector server and a naming
+ * service.
+ */
+public class JmxService {
+    private static final Logger logger = LoggerFactory.getLogger(JmxService.class);
+
+    private MBeanServer server;
+    private NamingServiceMBean namingServiceMBean;
+    private JMXConnectorServer connectorServer;
+    private String jmxHost;
+    private int jmxPort;
+    private String url;
+
+    public JmxService() throws Exception {
+        this("localhost", 28000 + (int)Math.floor(new Random().nextDouble() * 1000));
+        logger.warn("use of deprecated default host and port in JmxService");
+    }
+    
+    /**
+     * @deprecated since 0.6.0; either needs abandoning, or updating to support JmxSupport (and JmxmpAgent, etc) */
+    public JmxService(Entity e) throws Exception {
+        this(e.getAttribute(Attributes.HOSTNAME) != null ? e.getAttribute(Attributes.HOSTNAME) : "localhost", 
+                 e.getAttribute(UsesJmx.JMX_PORT) != null ? e.getAttribute(UsesJmx.JMX_PORT) : null);
+    }
+    
+    public JmxService(String jmxHost, Integer jmxPort) throws Exception {
+        this.jmxHost = jmxHost;
+        Preconditions.checkNotNull(jmxPort, "JMX_PORT must be set when starting JmxService"); 
+        this.jmxPort = jmxPort;
+        url = JmxHelper.toRmiJmxUrl(jmxHost, jmxPort, jmxPort, "jmxrmi");
+
+        try {
+            JMXServiceURL address = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + jmxHost + ":" + jmxPort + "/jmxrmi");
+            connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(address, null, null);
+            server = MBeanServerFactory.createMBeanServer();
+            ObjectName cntorServerName = ObjectName.getInstance("connectors:protocol=rmi");
+            server.registerMBean(connectorServer, cntorServerName);
+    
+            ObjectName naming = new ObjectName("Naming:type=registry");
+            server.registerMBean(new NamingService(jmxPort), naming);
+            Object proxy = MBeanServerInvocationHandler.newProxyInstance(server, naming, NamingServiceMBean.class, false);
+            namingServiceMBean = (NamingServiceMBean) proxy;
+            try {
+                namingServiceMBean.start();
+            } catch (Exception e) {
+                // may take a bit of time for port to be available, if it had just been used
+                logger.warn("JmxService couldn't start test mbean ("+e+"); will delay then retry once");
+                Thread.sleep(1000);
+                namingServiceMBean.start();
+            }
+    
+            connectorServer.start();
+            logger.info("JMX tester service started at URL {}", address);
+        } catch (Exception e) {
+            try {
+                shutdown();
+            } catch (Exception e2) {
+                logger.warn("Error shutting down JmxService, after error during startup; rethrowing original error", e2);
+            }
+            throw e;
+        }
+    }
+
+    public int getJmxPort() {
+        return jmxPort;
+    }
+    
+    public void shutdown() throws IOException {
+        if (connectorServer != null) connectorServer.stop();
+        if (namingServiceMBean != null) namingServiceMBean.stop();
+        if (server != null) MBeanServerFactory.releaseMBeanServer(server);
+        connectorServer = null;
+        namingServiceMBean = null;
+        server = null;
+        logger.info("JMX tester service stopped ({}:{})", jmxHost, jmxPort);
+    }
+
+    public String getUrl() {
+        return url;
+    }
+    
+    public GeneralisedDynamicMBean registerMBean(String name) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, MalformedObjectNameException, NullPointerException {
+        return registerMBean(ImmutableMap.of(), ImmutableMap.of(), name);
+    }
+
+    /**
+     * Construct a {@link GeneralisedDynamicMBean} and register it with this MBean server.
+     *
+     * @param initialAttributes a {@link Map} of attributes that make up the MBean's initial set of attributes and their * values
+     * @param name the name of the MBean
+     * @return the newly created and registered MBean
+     * @throws NullPointerException 
+     * @throws MalformedObjectNameException 
+     * @throws NotCompliantMBeanException 
+     * @throws MBeanRegistrationException 
+     * @throws InstanceAlreadyExistsException 
+     */
+    public GeneralisedDynamicMBean registerMBean(Map initialAttributes, String name) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, MalformedObjectNameException, NullPointerException {
+        return registerMBean(initialAttributes, ImmutableMap.of(), name);
+    }
+    
+    public GeneralisedDynamicMBean registerMBean(Map initialAttributes, Map operations, String name) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, MalformedObjectNameException, NullPointerException {
+        GeneralisedDynamicMBean mbean = new GeneralisedDynamicMBean(initialAttributes, operations);
+        server.registerMBean(mbean, new ObjectName(name));
+        return mbean;
+    }
+    
+    public StandardEmitterMBean registerMBean(List<String> notifications, String name) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, MalformedObjectNameException, NullPointerException {
+        String[] types = (String[]) notifications.toArray(new String[0]);
+        MBeanNotificationInfo info = new MBeanNotificationInfo(types, Notification.class.getName(), "Notification");
+        NotificationEmitter emitter = new NotificationBroadcasterSupport(info);
+        StandardEmitterMBean mbean = new StandardEmitterMBean(emitter, NotificationEmitter.class, emitter);
+        server.registerMBean(mbean, new ObjectName(name));
+        return mbean;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsEc2LiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsEc2LiveTest.java
new file mode 100644
index 0000000..b9e3d68
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsEc2LiveTest.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.location;
+
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.MachineDetails;
+import org.apache.brooklyn.api.location.OsDetails;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
+import org.apache.brooklyn.entity.trait.Startable;
+import org.apache.brooklyn.location.basic.BasicMachineDetails;
+import org.apache.brooklyn.location.basic.Locations;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.ImmutableList;
+
+// This test really belongs in brooklyn-location but depends on AbstractEc2LiveTest in brooklyn-software-base
+public class MachineDetailsEc2LiveTest extends AbstractEc2LiveTest {
+
+    private static final Logger LOG = LoggerFactory.getLogger(MachineDetailsEc2LiveTest.class);
+    private static final int TIMEOUT_MS = 1000 * 60 * 10; // ten minutes
+
+    @Override
+    protected void doTest(Location loc) throws Exception {
+        Entity testEntity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class));
+        app.start(ImmutableList.of(loc));
+        EntityTestUtils.assertAttributeEqualsEventually(MutableMap.of("timeout", TIMEOUT_MS),
+                testEntity, Startable.SERVICE_UP, true);
+
+        SshMachineLocation sshLoc = Locations.findUniqueSshMachineLocation(testEntity.getLocations()).get();
+        MachineDetails machine = app.getExecutionContext()
+                .submit(BasicMachineDetails.taskForSshMachineLocation(sshLoc))
+                .getUnchecked();
+        LOG.info("Found the following at {}: {}", loc, machine);
+        assertNotNull(machine);
+        OsDetails details = machine.getOsDetails();
+        assertNotNull(details);
+        assertNotNull(details.getArch());
+        assertNotNull(details.getName());
+        assertNotNull(details.getVersion());
+        assertFalse(details.getArch().startsWith("architecture:"));
+        assertFalse(details.getName().startsWith("name:"));
+        assertFalse(details.getVersion().startsWith("version:"));
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsGoogleComputeLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsGoogleComputeLiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsGoogleComputeLiveTest.java
new file mode 100644
index 0000000..1234f41
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/MachineDetailsGoogleComputeLiveTest.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.location;
+
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.MachineDetails;
+import org.apache.brooklyn.api.location.OsDetails;
+import org.apache.brooklyn.entity.AbstractGoogleComputeLiveTest;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
+import org.apache.brooklyn.entity.trait.Startable;
+import org.apache.brooklyn.location.basic.BasicMachineDetails;
+import org.apache.brooklyn.location.basic.Locations;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.ImmutableList;
+
+// This test really belongs in brooklyn-location but depends on AbstractGoogleComputeLiveTest in brooklyn-software-base
+public class MachineDetailsGoogleComputeLiveTest extends AbstractGoogleComputeLiveTest {
+
+    private static final Logger LOG = LoggerFactory.getLogger(MachineDetailsGoogleComputeLiveTest.class);
+
+    @Override
+    protected void doTest(Location loc) throws Exception {
+        Entity testEntity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class));
+        app.start(ImmutableList.of(loc));
+        EntityTestUtils.assertAttributeEqualsEventually(testEntity, Startable.SERVICE_UP, true);
+
+        SshMachineLocation sshLoc = Locations.findUniqueSshMachineLocation(testEntity.getLocations()).get();
+        MachineDetails machine = app.getExecutionContext()
+                .submit(BasicMachineDetails.taskForSshMachineLocation(sshLoc))
+                .getUnchecked();
+        LOG.info("Found the following at {}: {}", loc, machine);
+        assertNotNull(machine);
+        OsDetails details = machine.getOsDetails();
+        assertNotNull(details);
+        assertNotNull(details.getArch());
+        assertNotNull(details.getName());
+        assertNotNull(details.getVersion());
+        assertFalse(details.getArch().startsWith("architecture:"));
+        assertFalse(details.getName().startsWith("name:"));
+        assertFalse(details.getVersion().startsWith("version:"));
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/WinRmMachineLocationLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/WinRmMachineLocationLiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/WinRmMachineLocationLiveTest.java
new file mode 100644
index 0000000..12727fa
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/WinRmMachineLocationLiveTest.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.location;
+
+import static org.testng.Assert.assertEquals;
+
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.location.jclouds.JcloudsLocation;
+
+import io.cloudsoft.winrm4j.winrm.WinRmToolResponse;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.jclouds.JcloudsWinRmMachineLocation;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+public class WinRmMachineLocationLiveTest {
+    
+    // FIXME failing locally with:
+    //   Caused by: Traceback (most recent call last):
+    //     File "__pyclasspath__/winrm/__init__.py", line 40, in run_cmd
+    //     File "__pyclasspath__/winrm/protocol.py", line 118, in open_shell
+    //     File "__pyclasspath__/winrm/protocol.py", line 190, in send_message
+    //     File "__pyclasspath__/winrm/transport.py", line 112, in send_message
+    //     winrm.exceptions.WinRMTransportError: 500 WinRMTransport. [Errno 20001] getaddrinfo failed
+    //     at org.python.core.PyException.doRaise(PyException.java:226)
+
+    private static final Logger LOG = LoggerFactory.getLogger(BrooklynAppLiveTestSupport.class);
+
+    protected JcloudsLocation loc;
+    protected TestApplication app;
+    protected ManagementContextInternal mgmt;
+
+    private JcloudsWinRmMachineLocation machine;
+    
+    @BeforeClass(alwaysRun=true)
+    public void setUpClass() throws Exception {
+        mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());
+        JcloudsLocation loc = (JcloudsLocation) mgmt.getLocationRegistry().resolve("jclouds:aws-ec2:us-west-2", ImmutableMap.of(
+                "inboundPorts", ImmutableList.of(5985, 3389),
+                "displayName", "AWS Oregon (Windows)",
+                "imageId", "us-west-2/ami-8fd3f9bf",
+                "hardwareId", "m3.medium",
+                "useJcloudsSshInit", false));
+        machine = (JcloudsWinRmMachineLocation) loc.obtain();
+    }
+
+    @AfterClass(alwaysRun=true)
+    public void tearDownClass() throws Exception {
+        try {
+            if (machine != null) loc.release(machine);
+            if (mgmt != null) Entities.destroyAll(mgmt);
+        } catch (Throwable t) {
+            LOG.error("Caught exception in tearDown method", t);
+        } finally {
+            mgmt = null;
+        }
+    }
+
+    @Test(groups="Live")
+    public void testExecScript() throws Exception {
+        WinRmToolResponse response = machine.executeScript("echo true");
+        assertEquals(response.getStatusCode(), 0);
+        assertEquals(response.getStdErr(), "");
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/WinRmMachineLocationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/WinRmMachineLocationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/WinRmMachineLocationTest.java
new file mode 100644
index 0000000..8880d88
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/location/WinRmMachineLocationTest.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.location;
+
+import static org.testng.Assert.assertEquals;
+
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.location.basic.WinRmMachineLocation;
+import org.apache.brooklyn.util.net.Networking;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+
+public class WinRmMachineLocationTest extends BrooklynAppUnitTestSupport {
+
+    @Test
+    public void testConfigurePrivateAddresses() throws Exception {
+        WinRmMachineLocation host = mgmt.getLocationManager().createLocation(LocationSpec.create(WinRmMachineLocation.class)
+                .configure("address", Networking.getLocalHost())
+                .configure(WinRmMachineLocation.PRIVATE_ADDRESSES, ImmutableList.of("1.2.3.4"))
+                .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, true));
+
+        assertEquals(host.getPrivateAddresses(), ImmutableSet.of("1.2.3.4"));
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/AbstractToyMySqlEntityTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/AbstractToyMySqlEntityTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/AbstractToyMySqlEntityTest.java
new file mode 100644
index 0000000..e7bc7d8
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/AbstractToyMySqlEntityTest.java
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.mysql;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+import com.google.common.base.Predicates;
+import com.google.common.collect.Iterables;
+
+
+public abstract class AbstractToyMySqlEntityTest extends BrooklynAppLiveTestSupport {
+
+    private static final Logger log = LoggerFactory.getLogger(AbstractToyMySqlEntityTest.class);
+    
+    protected MachineProvisioningLocation<? extends SshMachineLocation> targetLocation;
+
+    @Override
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        super.setUp();
+        
+        targetLocation = createLocation();
+    }
+
+    protected MachineProvisioningLocation<? extends SshMachineLocation> createLocation() {
+        return mgmt.getLocationManager().createLocation(LocationSpec.create(
+                LocalhostMachineProvisioningLocation.class));
+    }
+    
+    protected abstract Entity createMysql();
+
+    // deliberately not marked as a test here so that subclasses mark it correctly (Live v Integration)
+    public void testMySqlOnProvisioningLocation() throws Exception {
+        Entity mysql = createMysql();
+        app.start(MutableList.of(targetLocation));
+        checkStartsRunning(mysql);
+        checkIsRunningAndStops(mysql, (SshMachineLocation) Iterables.getOnlyElement( mysql.getLocations() ));
+    }
+
+    protected Integer getPid(Entity mysql) {
+        return mysql.getAttribute(Attributes.PID);
+    }
+
+    protected void checkStartsRunning(Entity mysql) {
+        // should be starting within a few seconds (and almost certainly won't complete in that time)
+        EntityTestUtils.assertAttributeEventually(
+                mysql, 
+                Attributes.SERVICE_STATE_ACTUAL,
+                Predicates.or(Predicates.equalTo(Lifecycle.STARTING), Predicates.equalTo(Lifecycle.RUNNING)));
+        // should be up and running within 5m 
+        EntityTestUtils.assertAttributeEqualsEventually(MutableMap.of("timeout", Duration.FIVE_MINUTES),
+                mysql, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
+    }
+
+    protected void checkIsRunningAndStops(Entity mysql, SshMachineLocation lh) {
+        Integer pid = getPid(mysql);
+        Assert.assertNotNull(pid, "PID should be set as an attribute (or getPid() overridden to supply)");
+        Entities.submit(app, SshEffectorTasks.requirePidRunning(pid).machine(lh).newTask() ).get();
+        
+        app.stop();
+
+        // let the kill -1 take effect 
+        Time.sleep(Duration.ONE_SECOND);
+        
+        // and assert it has died
+        log.info("mysql in pid "+pid+" should be dead now");
+        // (app has stopped, so submit on mgmt context)
+        ProcessTaskWrapper<Integer> t = SshEffectorTasks.codePidRunning(pid).machine(lh).newTask();
+        mgmt.getExecutionManager().submit(t);
+        Assert.assertNotEquals(t.block().getExitCode(), (Integer)0);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityBuilder.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityBuilder.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityBuilder.java
new file mode 100644
index 0000000..650c28c
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityBuilder.java
@@ -0,0 +1,189 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.mysql;
+
+import java.io.File;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntityInitializer;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.OsDetails;
+import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.software.base.lifecycle.MachineLifecycleEffectorTasks;
+import org.apache.brooklyn.entity.stock.BasicStartable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.location.basic.BasicOsDetails.OsVersions;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.core.task.ssh.SshTasks;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.apache.brooklyn.util.ssh.BashCommands;
+import org.apache.brooklyn.util.text.ComparableVersion;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+
+import com.google.common.base.Predicates;
+import com.google.common.base.Splitter;
+import com.google.common.base.Supplier;
+import com.google.common.base.Suppliers;
+import com.google.common.collect.Iterables;
+
+public class DynamicToyMySqlEntityBuilder {
+
+    private static final Logger log = LoggerFactory.getLogger(DynamicToyMySqlEntityBuilder.class);
+
+    public static EntitySpec<? extends Entity> spec() {
+        return EntitySpec.create(BasicStartable.class).addInitializer(MySqlEntityInitializer.class);
+    }
+
+    public static final String downloadUrl(Entity e, boolean isLocalhost) {
+        if (isLocalhost) {
+            for (int i=50; i>20; i--) {
+                String f = System.getProperty("user.home")+"/.brooklyn/repository/MySqlNode/5.5."+i+"/mysql-5.5."+i+"-osx10.6-x86_64.tar.gz";
+                if (new File(f).exists())
+                    return "file://"+f;
+            }
+        }
+        // download
+        String version = "5.5.37";
+        String osTag = getOsTag(e);
+        String mirrorUrl = "http://www.mirrorservice.org/sites/ftp.mysql.com/";
+        return "http://dev.mysql.com/get/Downloads/MySQL-5.5/mysql-"+version+"-"+osTag+".tar.gz/from/"+mirrorUrl;
+    }
+
+    public static final String installDir(Entity e, boolean isLocalhost) {
+        String url = downloadUrl(e, isLocalhost);
+        String archive = Iterables.find(Splitter.on('/').omitEmptyStrings().split(url), Predicates.containsPattern(".tar.gz"));
+        return archive.replace(".tar.gz", "");
+    }
+
+    public static final String dir(Entity e) {
+        return "/tmp/brooklyn-mysql-"+e.getId();
+    }
+
+    // copied from MySqlSshDriver
+    public static String getOsTag(Entity e) {
+        // e.g. "osx10.6-x86_64"; see http://www.mysql.com/downloads/mysql/#downloads
+        OsDetails os = ((SshMachineLocation)Iterables.getOnlyElement(e.getLocations())).getOsDetails();
+        if (os == null) return "linux-glibc2.5-x86_64";
+        if (os.isMac()) {
+            String osp1 = os.getVersion()==null ? "osx10.8" //lowest common denominator
+                : new ComparableVersion(os.getVersion()).isGreaterThanOrEqualTo(OsVersions.MAC_10_9) ? "osx10.9"
+                : "osx10.8";  //lowest common denominator
+            if (!os.is64bit()) {
+                throw new IllegalStateException("Only 64 bit MySQL build is available for OS X");
+            }
+            return osp1+"-x86_64";
+        }
+        //assume generic linux
+        String osp1 = "linux-glibc2.5";
+        String osp2 = os.is64bit() ? "x86_64" : "i686";
+        return osp1+"-"+osp2;
+    }
+
+    public static class MySqlEntityInitializer implements EntityInitializer {
+        public void apply(final EntityLocal entity) {
+          new MachineLifecycleEffectorTasks() {
+            @Override
+            protected String startProcessesAtMachine(Supplier<MachineLocation> machineS) {
+                DynamicTasks.queue(
+                        SshEffectorTasks.ssh(
+                            "mkdir "+dir(entity),
+                            "cd "+dir(entity),
+                            BashCommands.downloadToStdout(downloadUrl(entity, isLocalhost(machineS)))+" | tar xvz"
+                        ).summary("download mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true)));
+                if (isLinux(machineS)) {
+                    DynamicTasks.queue(SshEffectorTasks.ssh(BashCommands.installPackage("libaio1")));
+                }
+                DynamicTasks.queue(
+                        SshEffectorTasks.put(".my.cnf")
+                            .contents(String.format("[mysqld]\nbasedir=%s/%s\n", dir(entity), installDir(entity, isLocalhost(machineS)))),
+                        SshEffectorTasks.ssh(
+                            "cd "+dir(entity)+"/*",
+                            "./scripts/mysql_install_db",
+                            "./support-files/mysql.server start > out.log 2> err.log < /dev/null"
+                        ).summary("setup and run mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true)));
+                return "submitted start";
+            }
+            protected void postStartCustom() {
+                // if it's still up after 5s assume we are good
+                Time.sleep(Duration.FIVE_SECONDS);
+                if (!DynamicTasks.queue(SshEffectorTasks.isPidFromFileRunning(dir(entity)+"/*/data/*.pid")).get()) {
+                    // but if it's not up add a bunch of other info
+                    log.warn("MySQL did not start: "+dir(entity));
+                    ProcessTaskWrapper<Integer> info = DynamicTasks.queue(SshEffectorTasks.ssh(
+                            "cd "+dir(entity)+"/*",
+                            "cat out.log",
+                            "cat err.log > /dev/stderr")).block();
+                    log.info("STDOUT:\n"+info.getStdout());
+                    log.info("STDERR:\n"+info.getStderr());
+                    BrooklynTaskTags.addTagsDynamically(Tasks.current(), 
+                        BrooklynTaskTags.tagForStream("console (nohup stdout)", Suppliers.ofInstance(info.getStdout()), null),
+                        BrooklynTaskTags.tagForStream("console (nohup stderr)", Suppliers.ofInstance(info.getStderr()), null));
+                    throw new IllegalStateException("MySQL appears not to be running");
+                }
+
+                // and set the PID
+                entity().setAttribute(Attributes.PID, 
+                        Integer.parseInt(DynamicTasks.queue(SshEffectorTasks.ssh("cat "+dir(entity)+"/*/data/*.pid")).block().getStdout().trim()));
+                
+                // TODO Without this, tests fail because nothing else sets serviceUp!
+                // Really should set this with a Feed that checks pid periodically.
+                // Should this instead be using SERVICE_NOT_UP_INDICATORS?
+                entity().setAttribute(Attributes.SERVICE_UP, true);
+            }
+
+            @Override
+            protected String stopProcessesAtMachine() {
+                // TODO Where is best place to set? 
+                // Really should set this with a Feed that checks pid periodically.
+                entity().setAttribute(Attributes.SERVICE_UP, false);
+                
+                Integer pid = entity().getAttribute(Attributes.PID);
+                if (pid==null) {
+                    log.info("mysql not running");
+                    return "No pid -- is it running?";
+                }
+
+                DynamicTasks.queue(SshEffectorTasks.ssh(
+                        "cd "+dir(entity)+"/*",
+                        "./support-files/mysql.server stop"
+                    ).summary("stop mysql"));
+                return "submitted stop";
+            }
+          }.attachLifecycleEffectors(entity);
+      }
+    }
+
+    private static boolean isLocalhost(Supplier<MachineLocation> machineS) {
+        return machineS.get() instanceof LocalhostMachine;
+    }
+
+    private static boolean isLinux(Supplier<MachineLocation> machineS) {
+        return machineS.get().getMachineDetails().getOsDetails().isLinux();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityTest.java
new file mode 100644
index 0000000..d676c00
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/mysql/DynamicToyMySqlEntityTest.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.mysql;
+
+import java.util.Arrays;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.util.collections.MutableMap;
+
+
+public class DynamicToyMySqlEntityTest extends AbstractToyMySqlEntityTest {
+
+    private static final Logger log = LoggerFactory.getLogger(DynamicToyMySqlEntityTest.class);
+    
+    protected Entity createMysql() {
+        Entity mysql = app.createAndManageChild(DynamicToyMySqlEntityBuilder.spec());
+        log.debug("created "+mysql);
+        return mysql;
+    }
+
+    // put right group on test (also help Eclipse IDE pick it up)
+    @Override
+    @Test(groups = "Integration")
+    public void testMySqlOnProvisioningLocation() throws Exception {
+        super.testMySqlOnProvisioningLocation();
+    }
+    
+    @Test(groups="Integration")
+    public void testMySqlOnMachineLocation() throws Exception {
+        Entity mysql = createMysql();
+        SshMachineLocation lh = targetLocation.obtain(MutableMap.of());
+        
+        app.start(Arrays.asList(lh));
+        checkStartsRunning(mysql);
+        checkIsRunningAndStops(mysql, lh);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/sensor/core/PortAttributeSensorAndConfigKeyTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/sensor/core/PortAttributeSensorAndConfigKeyTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/sensor/core/PortAttributeSensorAndConfigKeyTest.java
new file mode 100644
index 0000000..66049b5
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/sensor/core/PortAttributeSensorAndConfigKeyTest.java
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.sensor.core;
+
+import static org.testng.Assert.assertEquals;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.entity.ImplementedBy;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
+import org.apache.brooklyn.entity.software.base.EmptySoftwareProcessImpl;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
+
+import com.google.common.collect.ImmutableList;
+
+public class PortAttributeSensorAndConfigKeyTest extends BrooklynAppUnitTestSupport {
+
+    /*
+     * FIXME Fails because port is never released. Nothing calls PortSupplier.releasePort(int).
+     * The stacktrace below shows where it is obtained:
+     * 
+        Daemon Thread [brooklyn-execmanager-XwLLLdS4-5] (Suspended (breakpoint at line 244 in LocalhostMachineProvisioningLocation$LocalhostMachine))   
+            LocalhostMachineProvisioningLocation$LocalhostMachine.obtainPort(PortRange) line: 244   
+            PortAttributeSensorAndConfigKey.convertConfigToSensor(PortRange, Entity) line: 78   
+            PortAttributeSensorAndConfigKey.convertConfigToSensor(Object, Entity) line: 1   
+            PortAttributeSensorAndConfigKey(AttributeSensorAndConfigKey<ConfigType,SensorType>).getAsSensorValue(Entity) line: 93   
+            ConfigToAttributes.apply(EntityLocal, AttributeSensorAndConfigKey<?,T>) line: 28    
+            ConfigToAttributes.apply(EntityLocal) line: 17  
+            SoftwareProcessDriverLifecycleEffectorTasks(MachineLifecycleEffectorTasks).preStartCustom(MachineLocation) line: 343    
+            SoftwareProcessDriverLifecycleEffectorTasks.preStartCustom(MachineLocation) line: 69    
+            MachineLifecycleEffectorTasks$6.run() line: 283 
+     */
+    @Test(enabled=false, groups="Integration") // test is slow (for some reason - why?)
+    public void testStoppingEntityReleasesPortFromMachineForReuse() throws Exception {
+        LocalhostMachineProvisioningLocation loc = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost");
+        SshMachineLocation machine = loc.obtain();
+        runStoppingEntityReleasesPortFromLocalhostForReuse(machine);
+    }
+
+    @Test(groups="Integration") // test is slow (for some reason - why?)
+    public void testStoppingEntityReleasesPortFromLocalhostProvisioningLocationForReuse() throws Exception {
+        LocalhostMachineProvisioningLocation loc = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost");
+        runStoppingEntityReleasesPortFromLocalhostForReuse(loc);
+    }
+    
+    protected void runStoppingEntityReleasesPortFromLocalhostForReuse(Location loc) throws Exception {
+        MyEntity e1 = app.createAndManageChild(EntitySpec.create(MyEntity.class));
+        e1.start(ImmutableList.of(loc));
+        assertEquals(e1.getAttribute(MyEntity.MY_PORT), (Integer)47653);
+        
+        e1.stop();
+        Entities.unmanage(e1);
+        MyEntity e2 = app.createAndManageChild(EntitySpec.create(MyEntity.class));
+        e2.start(ImmutableList.of(loc));
+        assertEquals(e2.getAttribute(MyEntity.MY_PORT), (Integer)47653);
+    }
+
+    @ImplementedBy(MyEntityImpl.class)
+    public interface MyEntity extends EmptySoftwareProcess {
+        PortAttributeSensorAndConfigKey MY_PORT = new PortAttributeSensorAndConfigKey("myport", "", "47653");
+    }
+    
+    public static class MyEntityImpl extends EmptySoftwareProcessImpl implements MyEntity {
+    }        
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/ssh/SshCommandIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/ssh/SshCommandIntegrationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/ssh/SshCommandIntegrationTest.java
new file mode 100644
index 0000000..c51725c
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/test/ssh/SshCommandIntegrationTest.java
@@ -0,0 +1,126 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.software.base.test.ssh;
+
+import static org.testng.Assert.assertTrue;
+
+import java.io.File;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.sensor.ssh.SshCommandEffector;
+import org.apache.brooklyn.sensor.ssh.SshCommandSensor;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.time.Duration;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+import com.google.common.collect.ImmutableList;
+
+public class SshCommandIntegrationTest {
+
+    final static AttributeSensor<String> SENSOR_STRING = Sensors.newStringSensor("aString", "");
+    final static AttributeSensor<Integer> SENSOR_INT = Sensors.newIntegerSensor("aLong", "");
+    final static Effector<String> EFFECTOR_SAY_HI = Effectors.effector(String.class, "sayHi").buildAbstract();
+
+    private TestApplication app;
+    private SshMachineLocation machine;
+    private EntityLocal entity;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        app = TestApplication.Factory.newManagedInstanceForTests();
+        machine = app.newLocalhostProvisioningLocation().obtain();
+        entity = app.createAndManageChild(EntitySpec.create(TestEntity.class).location(machine));
+        app.start(ImmutableList.<Location>of());
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (app != null) Entities.destroyAll(app.getManagementContext());
+    }
+    
+    @Test(groups="Integration")
+    public void testSshSensor() throws Exception {
+        File tempFile = File.createTempFile("testSshCommand", "txt");
+        tempFile.deleteOnExit();
+        new SshCommandSensor<String>(ConfigBag.newInstance()
+                .configure(SshCommandSensor.SENSOR_PERIOD, Duration.millis(100))
+                .configure(SshCommandSensor.SENSOR_NAME, SENSOR_STRING.getName())
+                .configure(SshCommandSensor.SENSOR_COMMAND, "echo foo > "+tempFile.getAbsolutePath()+"\n"
+                    + "wc "+tempFile.getAbsolutePath()))
+            .apply(entity);
+        entity.setAttribute(Attributes.SERVICE_UP, true);
+
+        String val = EntityTestUtils.assertAttributeEventuallyNonNull(entity, SENSOR_STRING);
+        assertTrue(val.contains("1"), "val="+val);
+        String[] counts = val.trim().split("\\s+");
+        Assert.assertEquals(counts.length, 4, "val="+val);
+        Assert.assertEquals(counts[0], "1", "val="+val);
+    }
+
+    @Test(groups="Integration")
+    public void testSshEffector() throws Exception {
+        File tempFile = File.createTempFile("testSshCommand", "txt");
+        tempFile.deleteOnExit();
+        new SshCommandEffector(ConfigBag.newInstance()
+                .configure(SshCommandEffector.EFFECTOR_NAME, "sayHi")
+                .configure(SshCommandEffector.EFFECTOR_COMMAND, "echo hi"))
+            .apply(entity);
+        
+        String val = entity.invoke(EFFECTOR_SAY_HI, MutableMap.<String,String>of()).get();
+        Assert.assertEquals(val.trim(), "hi", "val="+val);
+    }
+
+    @Test(groups="Integration")
+    public void testSshEffectorWithParameters() throws Exception {
+        File tempFile = File.createTempFile("testSshCommand", "txt");
+        tempFile.deleteOnExit();
+        new SshCommandEffector(ConfigBag.newInstance()
+                .configure(SshCommandEffector.EFFECTOR_NAME, "sayHi")
+                .configure(SshCommandEffector.EFFECTOR_COMMAND, "echo $foo")
+                .configure(SshCommandEffector.EFFECTOR_PARAMETER_DEFS, 
+                    MutableMap.<String,Object>of("foo", MutableMap.of("defaultValue", "hi"))))
+            .apply(entity);
+        
+        String val;
+        // explicit value
+        val = entity.invoke(EFFECTOR_SAY_HI, MutableMap.<String,String>of("foo", "bar")).get();
+        Assert.assertEquals(val.trim(), "bar", "val="+val);
+        
+        // default value
+        val = entity.invoke(EFFECTOR_SAY_HI, MutableMap.<String,String>of()).get();
+        Assert.assertEquals(val.trim(), "hi", "val="+val);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricherTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricherTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricherTest.java
new file mode 100644
index 0000000..87ad639
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/system_service/SystemServiceEnricherTest.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.system_service;
+
+import static org.testng.Assert.assertEquals;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.sensor.EnricherSpec;
+import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
+import org.apache.brooklyn.effector.core.EffectorTasks;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.core.EntityPredicates;
+import org.apache.brooklyn.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess;
+import org.apache.brooklyn.entity.software.base.VanillaSoftwareProcessImpl;
+import org.apache.brooklyn.entity.software.base.VanillaSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.system_service.SystemServiceEnricher;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.jclouds.JcloudsLocation;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.ssh.BashCommands;
+import org.apache.brooklyn.util.time.Duration;
+
+import com.google.common.base.Suppliers;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+public class SystemServiceEnricherTest extends BrooklynAppLiveTestSupport {
+    //requires /etc/init.d OS, for example CentOS 6.5
+    private static final String LOCATION_SPEC = "named:service-live-test-location";
+    private JcloudsLocation location;
+
+    @Override
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        super.setUp();
+        location = (JcloudsLocation) mgmt.getLocationRegistry().resolve(LOCATION_SPEC);
+    }
+
+    @Test(groups = "Live")
+    public void testRestartLaunchesService() {
+        String launchCmd = "nohup bash -c \"echo \\$\\$ > $PID_FILE; while true; do sleep 1000; done\" &";
+        EntitySpec<VanillaSoftwareProcess> procSpec = EntitySpec.create(VanillaSoftwareProcess.class)
+                .configure(VanillaSoftwareProcess.LAUNCH_COMMAND, launchCmd)
+                .enricher(EnricherSpec.create(SystemServiceEnricher.class));
+        VanillaSoftwareProcess proc = app.createAndManageChild(procSpec);
+        app.start(ImmutableList.of(location));
+
+        waitHealthy(proc);
+
+        SshMachineLocation machine = EffectorTasks.getSshMachine(proc);
+        String pidFile = getPidFile(proc);
+        String killCmd = "kill -9 `cat " + pidFile + "`";
+        machine.execCommands("kill process", ImmutableList.of(killCmd));
+
+        waitFailed(proc);
+
+        int restartCode = machine.execCommands("restart machine", ImmutableList.of(BashCommands.sudo("/sbin/shutdown -r now")));
+        assertEquals(restartCode, 0);
+
+        waitHealthy(proc);
+    }
+
+    private String getPidFile(VanillaSoftwareProcess proc) {
+        VanillaSoftwareProcessImpl impl = (VanillaSoftwareProcessImpl)Entities.deproxy(proc);
+        return ((VanillaSoftwareProcessSshDriver)impl.getDriver()).getPidFile();
+    }
+
+    private void waitFailed(VanillaSoftwareProcess proc) {
+        Asserts.eventually(ImmutableMap.of("timeout", Duration.FIVE_MINUTES), Suppliers.ofInstance(proc), EntityPredicates.attributeEqualTo(Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE));
+    }
+
+    private void waitHealthy(VanillaSoftwareProcess proc) {
+        Asserts.eventually(ImmutableMap.of("timeout", Duration.FIVE_MINUTES), Suppliers.ofInstance(proc), EntityPredicates.attributeEqualTo(Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING));
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/location/basic/MachineDetailsEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/location/basic/MachineDetailsEc2LiveTest.java b/software/base/src/test/java/org/apache/brooklyn/location/basic/MachineDetailsEc2LiveTest.java
deleted file mode 100644
index 39f787f..0000000
--- a/software/base/src/test/java/org/apache/brooklyn/location/basic/MachineDetailsEc2LiveTest.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNotNull;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.MachineDetails;
-import org.apache.brooklyn.api.location.OsDetails;
-import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.ImmutableList;
-
-import brooklyn.entity.AbstractEc2LiveTest;
-import brooklyn.entity.basic.EmptySoftwareProcess;
-
-// This test really belongs in brooklyn-location but depends on AbstractEc2LiveTest in brooklyn-software-base
-public class MachineDetailsEc2LiveTest extends AbstractEc2LiveTest {
-
-    private static final Logger LOG = LoggerFactory.getLogger(MachineDetailsEc2LiveTest.class);
-    private static final int TIMEOUT_MS = 1000 * 60 * 10; // ten minutes
-
-    @Override
-    protected void doTest(Location loc) throws Exception {
-        Entity testEntity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class));
-        app.start(ImmutableList.of(loc));
-        EntityTestUtils.assertAttributeEqualsEventually(MutableMap.of("timeout", TIMEOUT_MS),
-                testEntity, Startable.SERVICE_UP, true);
-
-        SshMachineLocation sshLoc = Locations.findUniqueSshMachineLocation(testEntity.getLocations()).get();
-        MachineDetails machine = app.getExecutionContext()
-                .submit(BasicMachineDetails.taskForSshMachineLocation(sshLoc))
-                .getUnchecked();
-        LOG.info("Found the following at {}: {}", loc, machine);
-        assertNotNull(machine);
-        OsDetails details = machine.getOsDetails();
-        assertNotNull(details);
-        assertNotNull(details.getArch());
-        assertNotNull(details.getName());
-        assertNotNull(details.getVersion());
-        assertFalse(details.getArch().startsWith("architecture:"));
-        assertFalse(details.getName().startsWith("name:"));
-        assertFalse(details.getVersion().startsWith("version:"));
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/location/basic/MachineDetailsGoogleComputeLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/location/basic/MachineDetailsGoogleComputeLiveTest.java b/software/base/src/test/java/org/apache/brooklyn/location/basic/MachineDetailsGoogleComputeLiveTest.java
deleted file mode 100644
index 6f2a06a..0000000
--- a/software/base/src/test/java/org/apache/brooklyn/location/basic/MachineDetailsGoogleComputeLiveTest.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNotNull;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.MachineDetails;
-import org.apache.brooklyn.api.location.OsDetails;
-import org.apache.brooklyn.entity.trait.Startable;
-import org.apache.brooklyn.test.EntityTestUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.ImmutableList;
-
-import brooklyn.entity.AbstractGoogleComputeLiveTest;
-import brooklyn.entity.basic.EmptySoftwareProcess;
-
-// This test really belongs in brooklyn-location but depends on AbstractGoogleComputeLiveTest in brooklyn-software-base
-public class MachineDetailsGoogleComputeLiveTest extends AbstractGoogleComputeLiveTest {
-
-    private static final Logger LOG = LoggerFactory.getLogger(MachineDetailsGoogleComputeLiveTest.class);
-
-    @Override
-    protected void doTest(Location loc) throws Exception {
-        Entity testEntity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class));
-        app.start(ImmutableList.of(loc));
-        EntityTestUtils.assertAttributeEqualsEventually(testEntity, Startable.SERVICE_UP, true);
-
-        SshMachineLocation sshLoc = Locations.findUniqueSshMachineLocation(testEntity.getLocations()).get();
-        MachineDetails machine = app.getExecutionContext()
-                .submit(BasicMachineDetails.taskForSshMachineLocation(sshLoc))
-                .getUnchecked();
-        LOG.info("Found the following at {}: {}", loc, machine);
-        assertNotNull(machine);
-        OsDetails details = machine.getOsDetails();
-        assertNotNull(details);
-        assertNotNull(details.getArch());
-        assertNotNull(details.getName());
-        assertNotNull(details.getVersion());
-        assertFalse(details.getArch().startsWith("architecture:"));
-        assertFalse(details.getName().startsWith("name:"));
-        assertFalse(details.getVersion().startsWith("version:"));
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/location/basic/WinRmMachineLocationLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/location/basic/WinRmMachineLocationLiveTest.java b/software/base/src/test/java/org/apache/brooklyn/location/basic/WinRmMachineLocationLiveTest.java
deleted file mode 100644
index 1651f15..0000000
--- a/software/base/src/test/java/org/apache/brooklyn/location/basic/WinRmMachineLocationLiveTest.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.location.jclouds.JcloudsLocation;
-
-import io.cloudsoft.winrm4j.winrm.WinRmToolResponse;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.location.jclouds.JcloudsWinRmMachineLocation;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-public class WinRmMachineLocationLiveTest {
-    
-    // FIXME failing locally with:
-    //   Caused by: Traceback (most recent call last):
-    //     File "__pyclasspath__/winrm/__init__.py", line 40, in run_cmd
-    //     File "__pyclasspath__/winrm/protocol.py", line 118, in open_shell
-    //     File "__pyclasspath__/winrm/protocol.py", line 190, in send_message
-    //     File "__pyclasspath__/winrm/transport.py", line 112, in send_message
-    //     winrm.exceptions.WinRMTransportError: 500 WinRMTransport. [Errno 20001] getaddrinfo failed
-    //     at org.python.core.PyException.doRaise(PyException.java:226)
-
-    private static final Logger LOG = LoggerFactory.getLogger(BrooklynAppLiveTestSupport.class);
-
-    protected JcloudsLocation loc;
-    protected TestApplication app;
-    protected ManagementContextInternal mgmt;
-
-    private JcloudsWinRmMachineLocation machine;
-    
-    @BeforeClass(alwaysRun=true)
-    public void setUpClass() throws Exception {
-        mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());
-        JcloudsLocation loc = (JcloudsLocation) mgmt.getLocationRegistry().resolve("jclouds:aws-ec2:us-west-2", ImmutableMap.of(
-                "inboundPorts", ImmutableList.of(5985, 3389),
-                "displayName", "AWS Oregon (Windows)",
-                "imageId", "us-west-2/ami-8fd3f9bf",
-                "hardwareId", "m3.medium",
-                "useJcloudsSshInit", false));
-        machine = (JcloudsWinRmMachineLocation) loc.obtain();
-    }
-
-    @AfterClass(alwaysRun=true)
-    public void tearDownClass() throws Exception {
-        try {
-            if (machine != null) loc.release(machine);
-            if (mgmt != null) Entities.destroyAll(mgmt);
-        } catch (Throwable t) {
-            LOG.error("Caught exception in tearDown method", t);
-        } finally {
-            mgmt = null;
-        }
-    }
-
-    @Test(groups="Live")
-    public void testExecScript() throws Exception {
-        WinRmToolResponse response = machine.executeScript("echo true");
-        assertEquals(response.getStatusCode(), 0);
-        assertEquals(response.getStdErr(), "");
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/location/basic/WinRmMachineLocationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/location/basic/WinRmMachineLocationTest.java b/software/base/src/test/java/org/apache/brooklyn/location/basic/WinRmMachineLocationTest.java
deleted file mode 100644
index ea00d15..0000000
--- a/software/base/src/test/java/org/apache/brooklyn/location/basic/WinRmMachineLocationTest.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.location.basic;
-
-import static org.testng.Assert.assertEquals;
-
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.util.net.Networking;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
-
-public class WinRmMachineLocationTest extends BrooklynAppUnitTestSupport {
-
-    @Test
-    public void testConfigurePrivateAddresses() throws Exception {
-        WinRmMachineLocation host = mgmt.getLocationManager().createLocation(LocationSpec.create(WinRmMachineLocation.class)
-                .configure("address", Networking.getLocalHost())
-                .configure(WinRmMachineLocation.PRIVATE_ADDRESSES, ImmutableList.of("1.2.3.4"))
-                .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, true));
-
-        assertEquals(host.getPrivateAddresses(), ImmutableSet.of("1.2.3.4"));
-    }
-}


[04/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlSshDriver.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlSshDriver.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlSshDriver.java
index 6e68d6a..b73b6c1 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlSshDriver.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlSshDriver.java
@@ -35,18 +35,14 @@ import java.util.Map;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.database.DatastoreMixins;
-
-import brooklyn.entity.software.SshEffectorTasks;
-
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.apache.brooklyn.api.location.OsDetails;
 import org.apache.brooklyn.location.basic.BasicOsDetails.OsVersions;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.task.DynamicTasks;
 import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlDriver.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlDriver.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlDriver.java
index f8b6bad..dc267b4 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlDriver.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlDriver.java
@@ -18,12 +18,11 @@
  */
 package org.apache.brooklyn.entity.database.postgresql;
 
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
-
 /**
- * The {@link brooklyn.entity.basic.SoftwareProcessDriver} for PostgreSQL.
+ * The {@link org.apache.brooklyn.entity.software.base.SoftwareProcessDriver} for PostgreSQL.
  */
 public interface PostgreSqlDriver extends SoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNode.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNode.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNode.java
index 3e3835e..168179c 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNode.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNode.java
@@ -24,13 +24,11 @@ import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.api.objs.HasShortName;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.effector.core.Effectors;
 import org.apache.brooklyn.entity.database.DatabaseNode;
 import org.apache.brooklyn.entity.database.DatastoreMixins;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.location.basic.PortRanges;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNodeChefImplFromScratch.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNodeChefImplFromScratch.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNodeChefImplFromScratch.java
index 69a5363..f839a91 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNodeChefImplFromScratch.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNodeChefImplFromScratch.java
@@ -23,20 +23,18 @@ import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.effector.core.EffectorBody;
 import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.entity.chef.ChefConfig;
+import org.apache.brooklyn.entity.chef.ChefLifecycleEffectorTasks;
+import org.apache.brooklyn.entity.chef.ChefServerTasks;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.stock.EffectorStartableImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.chef.ChefConfig;
-import brooklyn.entity.chef.ChefLifecycleEffectorTasks;
-import brooklyn.entity.chef.ChefServerTasks;
-import brooklyn.entity.software.SshEffectorTasks;
-
 import org.apache.brooklyn.location.basic.Locations;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.ssh.SshFeed;
 import org.apache.brooklyn.sensor.feed.ssh.SshPollConfig;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.Jsonya;
 import org.apache.brooklyn.util.core.ResourceUtils;
 import org.apache.brooklyn.util.core.config.ConfigBag;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNodeImpl.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNodeImpl.java
index 13537a1..15d280e 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNodeImpl.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlNodeImpl.java
@@ -19,12 +19,11 @@
 package org.apache.brooklyn.entity.database.postgresql;
 
 import org.apache.brooklyn.effector.core.EffectorBody;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.util.core.config.ConfigBag;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 public class PostgreSqlNodeImpl extends SoftwareProcessImpl implements PostgreSqlNode {
 
     private static final Logger LOG = LoggerFactory.getLogger(PostgreSqlNodeImpl.class);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlSpecs.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlSpecs.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlSpecs.java
index f560add..b46374d 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlSpecs.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlSpecs.java
@@ -19,9 +19,8 @@
 package org.apache.brooklyn.entity.database.postgresql;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
-
-import brooklyn.entity.chef.ChefConfig;
-import brooklyn.entity.chef.ChefConfig.ChefModes;
+import org.apache.brooklyn.entity.chef.ChefConfig;
+import org.apache.brooklyn.entity.chef.ChefConfig.ChefModes;
 
 /**
  * Utiltiy for creating specs for {@link PostgreSqlNode} instances.

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlSshDriver.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlSshDriver.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlSshDriver.java
index 5ec85de..ec70005 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlSshDriver.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlSshDriver.java
@@ -41,6 +41,7 @@ import javax.annotation.Nullable;
 import org.apache.brooklyn.api.location.OsDetails;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.task.DynamicTasks;
@@ -57,14 +58,10 @@ import org.apache.brooklyn.util.text.StringFunctions;
 import org.apache.brooklyn.util.text.Strings;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.database.DatastoreMixins;
-
-import brooklyn.entity.software.SshEffectorTasks;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 
 import com.google.common.base.Charsets;
 import com.google.common.base.Function;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepDriver.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepDriver.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepDriver.java
index 056dd3d..ab4eec0 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepDriver.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.database.rubyrep;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 
 /**
  * The driver interface for {@link RubyRepNode}.

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepNode.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepNode.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepNode.java
index 8d7ddfb..60f7f32 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepNode.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepNode.java
@@ -23,12 +23,10 @@ import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.database.DatastoreMixins;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.Sensors;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey.StringAttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepNodeImpl.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepNodeImpl.java
index 86aeafe..2554d17 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepNodeImpl.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepNodeImpl.java
@@ -20,10 +20,9 @@ package org.apache.brooklyn.entity.database.rubyrep;
 
 import java.net.URI;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
 import org.apache.brooklyn.util.time.Duration;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepSshDriver.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepSshDriver.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepSshDriver.java
index c915556..4a11b63 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepSshDriver.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepSshDriver.java
@@ -28,11 +28,9 @@ import java.util.concurrent.ExecutionException;
 import org.apache.brooklyn.api.internal.EntityLocal;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.os.Os;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/resources/org/apache/brooklyn/entity/database/mssql/mssql.yaml
----------------------------------------------------------------------
diff --git a/software/database/src/main/resources/org/apache/brooklyn/entity/database/mssql/mssql.yaml b/software/database/src/main/resources/org/apache/brooklyn/entity/database/mssql/mssql.yaml
index 413ec3d..c3d3c99 100644
--- a/software/database/src/main/resources/org/apache/brooklyn/entity/database/mssql/mssql.yaml
+++ b/software/database/src/main/resources/org/apache/brooklyn/entity/database/mssql/mssql.yaml
@@ -12,7 +12,7 @@ location:
       mapNewVolumeToDeviceName: ["/dev/sda1", 100, true]
 
 services:
-- type: brooklyn.entity.basic.VanillaWindowsProcess
+- type: org.apache.brooklyn.entity.software.base.VanillaWindowsProcess
   brooklyn.config:
     templates.install:
       classpath://org/apache/brooklyn/entity/database/mssql/ConfigurationFile.ini: "C:\\ConfigurationFile.ini"

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/test/java/org/apache/brooklyn/entity/database/mariadb/MariaDbLiveEc2Test.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/mariadb/MariaDbLiveEc2Test.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/mariadb/MariaDbLiveEc2Test.java
index 80961dd..222998a 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/mariadb/MariaDbLiveEc2Test.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/mariadb/MariaDbLiveEc2Test.java
@@ -21,9 +21,7 @@ package org.apache.brooklyn.entity.database.mariadb;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.AbstractEc2LiveTest;
-
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.VogellaExampleAccess;
 import org.apache.brooklyn.location.jclouds.JcloudsLocation;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlClusterLiveEc2Test.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlClusterLiveEc2Test.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlClusterLiveEc2Test.java
index 1849ab0..93fe0c9 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlClusterLiveEc2Test.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlClusterLiveEc2Test.java
@@ -19,10 +19,8 @@
 package org.apache.brooklyn.entity.database.mysql;
 
 import org.testng.annotations.Test;
-
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 
 @Test(groups = { "Live" })
 public class MySqlClusterLiveEc2Test extends AbstractEc2LiveTest {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlClusterLiveSoftlayerTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlClusterLiveSoftlayerTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlClusterLiveSoftlayerTest.java
index a911200..c711265 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlClusterLiveSoftlayerTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlClusterLiveSoftlayerTest.java
@@ -19,10 +19,8 @@
 package org.apache.brooklyn.entity.database.mysql;
 
 import org.testng.annotations.Test;
-
-import brooklyn.entity.AbstractSoftlayerLiveTest;
-
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractSoftlayerLiveTest;
 
 @Test(groups = { "Live" })
 public class MySqlClusterLiveSoftlayerTest extends AbstractSoftlayerLiveTest {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlLiveEc2Test.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlLiveEc2Test.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlLiveEc2Test.java
index 1d32bbe..6b04c49 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlLiveEc2Test.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlLiveEc2Test.java
@@ -21,9 +21,7 @@ package org.apache.brooklyn.entity.database.mysql;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.AbstractEc2LiveTest;
-
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.VogellaExampleAccess;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlLiveGceTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlLiveGceTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlLiveGceTest.java
index dbc87e1..45202a0 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlLiveGceTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlLiveGceTest.java
@@ -21,9 +21,7 @@ package org.apache.brooklyn.entity.database.mysql;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.AbstractGoogleComputeLiveTest;
-
+import org.apache.brooklyn.entity.AbstractGoogleComputeLiveTest;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.VogellaExampleAccess;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlRestartIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlRestartIntegrationTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlRestartIntegrationTest.java
index cf7f749..f7913f0 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlRestartIntegrationTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MySqlRestartIntegrationTest.java
@@ -19,13 +19,12 @@
 package org.apache.brooklyn.entity.database.mysql;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessRestartIntegrationTest;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.basic.AbstractSoftwareProcessRestartIntegrationTest;
-import brooklyn.entity.basic.SoftwareProcess;
-
 /**
  * Tests restart of the software *process* (as opposed to the VM).
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MysqlDockerLiveTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MysqlDockerLiveTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MysqlDockerLiveTest.java
index f22cf7b..f8a285c 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MysqlDockerLiveTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/mysql/MysqlDockerLiveTest.java
@@ -20,8 +20,7 @@ package org.apache.brooklyn.entity.database.mysql;
 
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.VogellaExampleAccess;
-
-import brooklyn.entity.software.AbstractDockerLiveTest;
+import org.apache.brooklyn.entity.software.base.AbstractDockerLiveTest;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqDockerLiveTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqDockerLiveTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqDockerLiveTest.java
index 1f7b94a..7ba4ec8 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqDockerLiveTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqDockerLiveTest.java
@@ -20,8 +20,7 @@ package org.apache.brooklyn.entity.database.postgresql;
 
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.VogellaExampleAccess;
-
-import brooklyn.entity.software.AbstractDockerLiveTest;
+import org.apache.brooklyn.entity.software.base.AbstractDockerLiveTest;
 
 import com.google.common.collect.ImmutableList;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlChefTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlChefTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlChefTest.java
index 51c49a7..7ae04f7 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlChefTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlChefTest.java
@@ -24,19 +24,15 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.chef.ChefLiveTestSupport;
-
 import org.apache.brooklyn.effector.core.EffectorTasks;
+import org.apache.brooklyn.entity.chef.ChefLiveTestSupport;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.VogellaExampleAccess;
-
-import brooklyn.entity.software.SshEffectorTasks;
-
 import org.apache.brooklyn.api.location.PortRange;
 import org.apache.brooklyn.location.basic.PortRanges;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
 import org.apache.brooklyn.util.time.Duration;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlEc2LiveTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlEc2LiveTest.java
index eb432c8..f878778 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlEc2LiveTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlEc2LiveTest.java
@@ -21,9 +21,7 @@ package org.apache.brooklyn.entity.database.postgresql;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.AbstractEc2LiveTest;
-
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.VogellaExampleAccess;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlGceLiveTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlGceLiveTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlGceLiveTest.java
index 0428f5d..d6dbb45 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlGceLiveTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlGceLiveTest.java
@@ -21,9 +21,7 @@ package org.apache.brooklyn.entity.database.postgresql;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.AbstractGoogleComputeLiveTest;
-
+import org.apache.brooklyn.entity.AbstractGoogleComputeLiveTest;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.VogellaExampleAccess;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlRestartIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlRestartIntegrationTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlRestartIntegrationTest.java
index 970d3ff..185fec3 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlRestartIntegrationTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/postgresql/PostgreSqlRestartIntegrationTest.java
@@ -19,13 +19,12 @@
 package org.apache.brooklyn.entity.database.postgresql;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessRestartIntegrationTest;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.basic.AbstractSoftwareProcessRestartIntegrationTest;
-import brooklyn.entity.basic.SoftwareProcess;
-
 /**
  * Tests restart of the software *process* (as opposed to the VM).
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepEc2LiveTest.java b/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepEc2LiveTest.java
index 52b919f..db7dcbd 100644
--- a/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepEc2LiveTest.java
+++ b/software/database/src/test/java/org/apache/brooklyn/entity/database/rubyrep/RubyRepEc2LiveTest.java
@@ -21,9 +21,7 @@ package org.apache.brooklyn.entity.database.rubyrep;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.AbstractEc2LiveTest;
-
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
 import org.apache.brooklyn.entity.database.postgresql.PostgreSqlIntegrationTest;
 import org.apache.brooklyn.entity.database.postgresql.PostgreSqlNode;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQBroker.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQBroker.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQBroker.java
index f154f81..cf37106 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQBroker.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQBroker.java
@@ -23,13 +23,11 @@ import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.BasicConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.java.UsesJmx;
-
 import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.entity.messaging.MessageBroker;
 import org.apache.brooklyn.entity.messaging.jms.JMSBroker;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.sensor.core.AttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQBrokerImpl.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQBrokerImpl.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQBrokerImpl.java
index 7dcf3be..4427b52 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQBrokerImpl.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQBrokerImpl.java
@@ -24,14 +24,11 @@ import java.util.concurrent.TimeUnit;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.java.UsesJmx;
-
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.entity.messaging.jms.JMSBrokerImpl;
-
-import brooklyn.event.feed.jmx.JmxAttributePollConfig;
-import brooklyn.event.feed.jmx.JmxFeed;
+import org.apache.brooklyn.sensor.feed.jmx.JmxAttributePollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
 
 import com.google.common.base.Functions;
 import com.google.common.base.Objects.ToStringHelper;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQDestinationImpl.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQDestinationImpl.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQDestinationImpl.java
index ae11770..337d68b 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQDestinationImpl.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQDestinationImpl.java
@@ -27,11 +27,10 @@ import org.apache.brooklyn.api.internal.EntityLocal;
 import com.google.common.base.Preconditions;
 
 import org.apache.brooklyn.entity.messaging.jms.JMSDestinationImpl;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
+import org.apache.brooklyn.sensor.feed.jmx.JmxHelper;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 
-import brooklyn.event.feed.jmx.JmxFeed;
-import brooklyn.event.feed.jmx.JmxHelper;
-
 public abstract class ActiveMQDestinationImpl extends JMSDestinationImpl implements ActiveMQDestination {
     protected ObjectName brokerMBeanName;
     protected transient JmxHelper jmxHelper;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQDriver.java
index 99a7b86..768efa6 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.messaging.activemq;
 
-import brooklyn.entity.java.JavaSoftwareProcessDriver;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessDriver;
 
 public interface ActiveMQDriver extends JavaSoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQQueueImpl.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQQueueImpl.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQQueueImpl.java
index 63d5c1c..dddb6c9 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQQueueImpl.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQQueueImpl.java
@@ -18,12 +18,11 @@
  */
 package org.apache.brooklyn.entity.messaging.activemq;
 
+import org.apache.brooklyn.sensor.feed.jmx.JmxAttributePollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.event.feed.jmx.JmxAttributePollConfig;
-import brooklyn.event.feed.jmx.JmxFeed;
-
 public class ActiveMQQueueImpl extends ActiveMQDestinationImpl implements ActiveMQQueue {
     public static final Logger log = LoggerFactory.getLogger(ActiveMQQueue.class);
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQSshDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQSshDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQSshDriver.java
index c7cf623..56cbbd5 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQSshDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQSshDriver.java
@@ -24,9 +24,8 @@ import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 
-import brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/jms/JMSBroker.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/jms/JMSBroker.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/jms/JMSBroker.java
index a83d259..34d03f7 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/jms/JMSBroker.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/jms/JMSBroker.java
@@ -21,10 +21,10 @@ package org.apache.brooklyn.entity.messaging.jms;
 import java.util.Collection;
 import java.util.Map;
 
-import brooklyn.entity.basic.SoftwareProcess;
 import org.apache.brooklyn.entity.messaging.MessageBroker;
 import org.apache.brooklyn.entity.messaging.Queue;
 import org.apache.brooklyn.entity.messaging.Topic;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 
 import com.google.common.annotations.VisibleForTesting;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/jms/JMSBrokerImpl.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/jms/JMSBrokerImpl.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/jms/JMSBrokerImpl.java
index 73b05a7..2fdfa7f 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/jms/JMSBrokerImpl.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/jms/JMSBrokerImpl.java
@@ -25,12 +25,10 @@ import java.util.Map;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import org.apache.brooklyn.entity.lifecycle.Lifecycle;
 import org.apache.brooklyn.entity.messaging.Queue;
 import org.apache.brooklyn.entity.messaging.Topic;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.time.Duration;
 import org.apache.brooklyn.util.time.Time;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/AbstractfKafkaSshDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/AbstractfKafkaSshDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/AbstractfKafkaSshDriver.java
index b6176a7..efcb5a8 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/AbstractfKafkaSshDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/AbstractfKafkaSshDriver.java
@@ -27,11 +27,9 @@ import java.util.Map;
 import org.apache.brooklyn.api.internal.EntityLocal;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/Kafka.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/Kafka.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/Kafka.java
index fc31708..57d2db9 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/Kafka.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/Kafka.java
@@ -21,11 +21,10 @@ package org.apache.brooklyn.entity.messaging.kafka;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
-import brooklyn.entity.basic.SoftwareProcess;
-
 /**
  * Shared Kafka broker and zookeeper properties.
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBroker.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBroker.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBroker.java
index 52130cf..65576f3 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBroker.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBroker.java
@@ -23,11 +23,9 @@ import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.BasicConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.java.UsesJmx;
-
+import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.entity.messaging.MessageBroker;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.zookeeper.ZooKeeperNode;
 import org.apache.brooklyn.location.basic.PortRanges;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerDriver.java
index 357dae8..fe2a396 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.messaging.kafka;
 
-import brooklyn.entity.java.JavaSoftwareProcessDriver;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessDriver;
 
 public interface KafkaBrokerDriver extends JavaSoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerImpl.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerImpl.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerImpl.java
index 5da2114..0d17099 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerImpl.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerImpl.java
@@ -26,16 +26,13 @@ import javax.management.ObjectName;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.messaging.MessageBroker;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.entity.zookeeper.ZooKeeperNode;
-
-import brooklyn.event.feed.jmx.JmxAttributePollConfig;
-import brooklyn.event.feed.jmx.JmxFeed;
-import brooklyn.event.feed.jmx.JmxHelper;
+import org.apache.brooklyn.sensor.feed.jmx.JmxAttributePollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
+import org.apache.brooklyn.sensor.feed.jmx.JmxHelper;
 
 import com.google.common.base.Functions;
 import com.google.common.base.Objects.ToStringHelper;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerSshDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerSshDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerSshDriver.java
index d50b1bb..b1eeb43 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerSshDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaBrokerSshDriver.java
@@ -22,11 +22,9 @@ import java.util.Map;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.java.UsesJmx;
-import brooklyn.entity.java.UsesJmx.JmxAgentModes;
-
 import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.entity.java.UsesJmx.JmxAgentModes;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaZooKeeper.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaZooKeeper.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaZooKeeper.java
index 0cc8b22..97f1216 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaZooKeeper.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaZooKeeper.java
@@ -21,11 +21,9 @@ package org.apache.brooklyn.entity.messaging.kafka;
 import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.BasicConfigKey;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.entity.annotation.Effector;
 import org.apache.brooklyn.entity.annotation.EffectorParam;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.zookeeper.ZooKeeperNode;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaZooKeeperDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaZooKeeperDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaZooKeeperDriver.java
index f08736d..c1b7ad7 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaZooKeeperDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/kafka/KafkaZooKeeperDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.messaging.kafka;
 
-import brooklyn.entity.java.JavaSoftwareProcessDriver;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessDriver;
 
 public interface KafkaZooKeeperDriver extends JavaSoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidBroker.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidBroker.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidBroker.java
index 291c8b6..4648a76 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidBroker.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidBroker.java
@@ -25,14 +25,12 @@ import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.BasicConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.java.UsesJmx;
-
 import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.entity.messaging.MessageBroker;
 import org.apache.brooklyn.entity.messaging.amqp.AmqpServer;
 import org.apache.brooklyn.entity.messaging.jms.JMSBroker;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidBrokerImpl.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidBrokerImpl.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidBrokerImpl.java
index 80215ca..f3ff24a 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidBrokerImpl.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidBrokerImpl.java
@@ -30,17 +30,14 @@ import javax.management.ObjectName;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.java.JmxSupport;
-
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.JmxSupport;
 import org.apache.brooklyn.entity.messaging.jms.JMSBrokerImpl;
+import org.apache.brooklyn.sensor.feed.jmx.JmxAttributePollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
+import org.apache.brooklyn.sensor.feed.jmx.JmxHelper;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 
-import brooklyn.event.feed.jmx.JmxAttributePollConfig;
-import brooklyn.event.feed.jmx.JmxFeed;
-import brooklyn.event.feed.jmx.JmxHelper;
-
 import com.google.common.base.Function;
 import com.google.common.base.Functions;
 import com.google.common.base.Objects.ToStringHelper;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidDestinationImpl.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidDestinationImpl.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidDestinationImpl.java
index 35e64d4..11b2b2b 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidDestinationImpl.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidDestinationImpl.java
@@ -26,17 +26,14 @@ import javax.management.ObjectName;
 import org.apache.brooklyn.api.internal.EntityLocal;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.java.UsesJmx;
-
+import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.entity.messaging.amqp.AmqpServer;
 import org.apache.brooklyn.entity.messaging.jms.JMSDestinationImpl;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
+import org.apache.brooklyn.sensor.feed.jmx.JmxHelper;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 
-import brooklyn.event.feed.jmx.JmxFeed;
-import brooklyn.event.feed.jmx.JmxHelper;
-
 public abstract class QpidDestinationImpl extends JMSDestinationImpl implements QpidDestination {
     public static final Logger log = LoggerFactory.getLogger(QpidDestination.class);
     

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidDriver.java
index 46aeb09..225c8c9 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.messaging.qpid;
 
-import brooklyn.entity.java.JavaSoftwareProcessDriver;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessDriver;
 
 public interface QpidDriver extends JavaSoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidQueueImpl.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidQueueImpl.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidQueueImpl.java
index e094a74..d1b81af 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidQueueImpl.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidQueueImpl.java
@@ -24,11 +24,10 @@ import javax.management.MalformedObjectNameException;
 import javax.management.ObjectName;
 
 import org.apache.brooklyn.entity.messaging.amqp.AmqpExchange;
+import org.apache.brooklyn.sensor.feed.jmx.JmxAttributePollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 
-import brooklyn.event.feed.jmx.JmxAttributePollConfig;
-import brooklyn.event.feed.jmx.JmxFeed;
-
 public class QpidQueueImpl extends QpidDestinationImpl implements QpidQueue {
     public QpidQueueImpl() {
     }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidSshDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidSshDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidSshDriver.java
index fe5da5b..318c24a 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidSshDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/qpid/QpidSshDriver.java
@@ -26,10 +26,8 @@ import java.util.Map;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitBroker.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitBroker.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitBroker.java
index cf7bdd7..c4190cd 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitBroker.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitBroker.java
@@ -28,11 +28,9 @@ import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.BasicConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.entity.messaging.MessageBroker;
 import org.apache.brooklyn.entity.messaging.amqp.AmqpServer;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.Sensors;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitBrokerImpl.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitBrokerImpl.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitBrokerImpl.java
index 1ae9a59..9fa95c5 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitBrokerImpl.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitBrokerImpl.java
@@ -24,13 +24,12 @@ import java.util.Map;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import com.google.common.base.Objects.ToStringHelper;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 /**
  * An {@link org.apache.brooklyn.api.entity.Entity} that represents a single Rabbit MQ broker instance, using AMQP 0-9-1.
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitDriver.java
index 2c989d5..5b3ce2d 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitDriver.java
@@ -20,7 +20,7 @@ package org.apache.brooklyn.entity.messaging.rabbit;
 
 import java.util.Map;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 
 public interface RabbitDriver extends SoftwareProcessDriver {
     

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitSshDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitSshDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitSshDriver.java
index 7b9da0d..98f87ec 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitSshDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitSshDriver.java
@@ -31,11 +31,10 @@ import com.google.common.base.Strings;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-import brooklyn.entity.basic.lifecycle.ScriptHelper;
-
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.messaging.amqp.AmqpServer;
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelper;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/Storm.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/Storm.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/Storm.java
index 08fe5b4..827a23d 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/Storm.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/Storm.java
@@ -25,10 +25,8 @@ import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.core.config.render.RendererHints;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.java.UsesJmx;
-
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.zookeeper.ZooKeeperEnsemble;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormDriver.java
index f91429e..35bdd9f 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.messaging.storm;
 
-import brooklyn.entity.java.JavaSoftwareProcessDriver;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessDriver;
 
 public interface StormDriver extends JavaSoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormImpl.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormImpl.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormImpl.java
index 71c6531..4fec141 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormImpl.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormImpl.java
@@ -21,17 +21,16 @@ package org.apache.brooklyn.entity.messaging.storm;
 import javax.management.ObjectName;
 
 import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.java.JavaAppUtils;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
+import org.apache.brooklyn.sensor.feed.jmx.JmxHelper;
 import org.apache.brooklyn.util.time.Duration;
 import org.apache.brooklyn.util.time.Time;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
-import brooklyn.entity.java.JavaAppUtils;
-import brooklyn.entity.java.JavaSoftwareProcessDriver;
-import brooklyn.event.feed.jmx.JmxFeed;
-import brooklyn.event.feed.jmx.JmxHelper;
-
 public class StormImpl extends SoftwareProcessImpl implements Storm {
 
     private static final Logger log = LoggerFactory.getLogger(StormImpl.class);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormSshDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormSshDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormSshDriver.java
index f7253b5..3df87fb 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormSshDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/messaging/storm/StormSshDriver.java
@@ -27,12 +27,10 @@ import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.internal.EntityLocal;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcess;
-import brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.zookeeper.ZooKeeperEnsemble;
 import org.apache.brooklyn.location.basic.Machines;
 import org.apache.brooklyn.location.basic.SshMachineLocation;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/AbstractZooKeeperImpl.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/AbstractZooKeeperImpl.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/AbstractZooKeeperImpl.java
index 6cb5ab0..f0d4872 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/AbstractZooKeeperImpl.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/AbstractZooKeeperImpl.java
@@ -22,15 +22,14 @@ import java.util.concurrent.TimeUnit;
 
 import javax.management.ObjectName;
 
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
+import org.apache.brooklyn.sensor.feed.jmx.JmxAttributePollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
+import org.apache.brooklyn.sensor.feed.jmx.JmxHelper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
-import brooklyn.entity.java.JavaSoftwareProcessDriver;
-import brooklyn.event.feed.jmx.JmxAttributePollConfig;
-import brooklyn.event.feed.jmx.JmxFeed;
-import brooklyn.event.feed.jmx.JmxHelper;
-
 import com.google.common.base.Functions;
 import com.google.common.base.Objects.ToStringHelper;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperDriver.java
index 36388f0..b92e9da 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.zookeeper;
 
-import brooklyn.entity.java.JavaSoftwareProcessDriver;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessDriver;
 
 public interface ZooKeeperDriver extends JavaSoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperNode.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperNode.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperNode.java
index 39e43f3..2de34f9 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperNode.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperNode.java
@@ -23,13 +23,12 @@ import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.util.core.flags.SetFromFlag;
 
-import brooklyn.entity.basic.SoftwareProcess;
-
 /**
  * An {@link org.apache.brooklyn.api.entity.Entity} that represents a single Apache ZooKeeper instance.
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperSshDriver.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperSshDriver.java b/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperSshDriver.java
index f14db20..af55acc 100644
--- a/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperSshDriver.java
+++ b/software/messaging/src/main/java/org/apache/brooklyn/entity/zookeeper/ZooKeeperSshDriver.java
@@ -26,9 +26,7 @@ import java.util.concurrent.ExecutionException;
 
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.entity.core.Entities;
-
-import brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Networking;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQEc2LiveTest.java b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQEc2LiveTest.java
index 05dbe56..2c7fe22 100644
--- a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQEc2LiveTest.java
+++ b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQEc2LiveTest.java
@@ -30,12 +30,11 @@ import javax.jms.TextMessage;
 import org.apache.activemq.ActiveMQConnectionFactory;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.collect.ImmutableList;
 
 public class ActiveMQEc2LiveTest extends AbstractEc2LiveTest {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQGoogleComputeLiveTest.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQGoogleComputeLiveTest.java b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQGoogleComputeLiveTest.java
index 31dcd3c..4237008 100644
--- a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQGoogleComputeLiveTest.java
+++ b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQGoogleComputeLiveTest.java
@@ -18,13 +18,12 @@
  */
 package org.apache.brooklyn.entity.messaging.activemq;
 
-import brooklyn.entity.AbstractGoogleComputeLiveTest;
-
 import com.google.common.collect.ImmutableList;
 
 import org.apache.activemq.ActiveMQConnectionFactory;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractGoogleComputeLiveTest;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.annotations.Test;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQIntegrationTest.java b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQIntegrationTest.java
index 7a9dd8f..bfbdbf5 100644
--- a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQIntegrationTest.java
+++ b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/activemq/ActiveMQIntegrationTest.java
@@ -36,6 +36,8 @@ import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.entity.java.UsesJmx.JmxAgentModes;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.slf4j.Logger;
@@ -45,9 +47,6 @@ import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.java.UsesJmx;
-import brooklyn.entity.java.UsesJmx.JmxAgentModes;
-
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/kafka/KafkaLiveTest.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/kafka/KafkaLiveTest.java b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/kafka/KafkaLiveTest.java
index 29d69bf..022aef0 100644
--- a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/kafka/KafkaLiveTest.java
+++ b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/kafka/KafkaLiveTest.java
@@ -25,13 +25,12 @@ import java.util.concurrent.Callable;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.util.collections.MutableMap;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.collect.ImmutableList;
 
 public class KafkaLiveTest extends AbstractEc2LiveTest {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/qpid/QpidEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/qpid/QpidEc2LiveTest.java b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/qpid/QpidEc2LiveTest.java
index d926c45..6d793c8 100644
--- a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/qpid/QpidEc2LiveTest.java
+++ b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/qpid/QpidEc2LiveTest.java
@@ -20,11 +20,10 @@ package org.apache.brooklyn.entity.messaging.qpid;
 
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.AbstractEc2LiveTest;
-
 import com.google.common.collect.ImmutableList;
 
 public class QpidEc2LiveTest extends AbstractEc2LiveTest {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/qpid/QpidIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/qpid/QpidIntegrationTest.java b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/qpid/QpidIntegrationTest.java
index 2909d6c..ef99d26 100644
--- a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/qpid/QpidIntegrationTest.java
+++ b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/qpid/QpidIntegrationTest.java
@@ -39,6 +39,7 @@ import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.EntityTestUtils;
@@ -53,8 +54,6 @@ import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
-import brooklyn.entity.basic.SoftwareProcess;
-
 import com.google.common.collect.ImmutableList;
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitEc2LiveTest.java b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitEc2LiveTest.java
index 2661013..263ae57 100644
--- a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitEc2LiveTest.java
+++ b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/rabbit/RabbitEc2LiveTest.java
@@ -27,9 +27,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.SkipException;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.AbstractEc2LiveTest;
-
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.messaging.MessageBroker;
 import org.apache.brooklyn.entity.messaging.amqp.AmqpExchange;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/storm/StormEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/storm/StormEc2LiveTest.java b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/storm/StormEc2LiveTest.java
index 1096003..40cbcf5 100644
--- a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/storm/StormEc2LiveTest.java
+++ b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/storm/StormEc2LiveTest.java
@@ -22,9 +22,7 @@ import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.AbstractEc2LiveTest;
-
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.entity.zookeeper.ZooKeeperNode;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/zookeeper/ZooKeeperEc2LiveTest.java
----------------------------------------------------------------------
diff --git a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/zookeeper/ZooKeeperEc2LiveTest.java b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/zookeeper/ZooKeeperEc2LiveTest.java
index c947374..d971ea7 100644
--- a/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/zookeeper/ZooKeeperEc2LiveTest.java
+++ b/software/messaging/src/test/java/org/apache/brooklyn/entity/messaging/zookeeper/ZooKeeperEc2LiveTest.java
@@ -22,9 +22,7 @@ import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.annotations.Test;
-
-import brooklyn.entity.AbstractEc2LiveTest;
-
+import org.apache.brooklyn.entity.AbstractEc2LiveTest;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.entity.zookeeper.ZooKeeperNode;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitDriver.java
----------------------------------------------------------------------
diff --git a/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitDriver.java b/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitDriver.java
index a148fd4..d088928 100644
--- a/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitDriver.java
+++ b/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.monitoring.monit;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 
 public interface MonitDriver extends SoftwareProcessDriver {
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitNode.java
----------------------------------------------------------------------
diff --git a/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitNode.java b/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitNode.java
index a6c1906..3ce2489 100644
--- a/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitNode.java
+++ b/software/monitoring/src/main/java/org/apache/brooklyn/entity/monitoring/monit/MonitNode.java
@@ -27,6 +27,7 @@ import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.Sensors;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey.StringAttributeSensorAndConfigKey;
@@ -35,8 +36,6 @@ import org.apache.brooklyn.util.core.flags.SetFromFlag;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.reflect.TypeToken;
 
-import brooklyn.entity.basic.SoftwareProcess;
-
 @Catalog(name="Monit Node", description="Monit is a free open source utility for managing and monitoring, processes, programs, files, directories and filesystems on a UNIX system")
 @ImplementedBy(MonitNodeImpl.class)
 public interface MonitNode extends SoftwareProcess, HasShortName {



[45/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/ssh/SshMachineLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/ssh/SshMachineLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/ssh/SshMachineLocationTest.java
new file mode 100644
index 0000000..b2d0eb9
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/ssh/SshMachineLocationTest.java
@@ -0,0 +1,345 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.ssh;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertSame;
+import static org.testng.Assert.assertTrue;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+
+import org.apache.brooklyn.api.effector.Effector;
+import org.apache.brooklyn.api.entity.EntityInitializer;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineDetails;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.location.PortRange;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.effector.core.EffectorBody;
+import org.apache.brooklyn.effector.core.EffectorTaskTest;
+import org.apache.brooklyn.effector.core.Effectors;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.core.EntityInternal;
+import org.apache.brooklyn.entity.factory.ApplicationBuilder;
+import org.apache.brooklyn.location.core.BasicHardwareDetails;
+import org.apache.brooklyn.location.core.BasicMachineDetails;
+import org.apache.brooklyn.location.core.BasicOsDetails;
+import org.apache.brooklyn.location.core.Machines;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.file.ArchiveUtils;
+import org.apache.brooklyn.util.core.internal.ssh.RecordingSshTool;
+import org.apache.brooklyn.util.core.internal.ssh.SshException;
+import org.apache.brooklyn.util.core.internal.ssh.SshTool;
+import org.apache.brooklyn.util.core.task.BasicExecutionContext;
+import org.apache.brooklyn.util.core.task.BasicExecutionManager;
+import org.apache.brooklyn.util.guava.Maybe;
+import org.apache.brooklyn.util.net.Networking;
+import org.apache.brooklyn.util.net.Urls;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.stream.Streams;
+import org.apache.brooklyn.util.time.Duration;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Charsets;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.io.Files;
+
+/**
+ * Test the {@link SshMachineLocation} implementation of the {@link Location} interface.
+ */
+public class SshMachineLocationTest {
+
+    private SshMachineLocation host;
+    private ManagementContext mgmt;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        mgmt = LocalManagementContextForTests.newInstance();
+        host = new SshMachineLocation(MutableMap.of("address", Networking.getLocalHost()));
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (host != null) Streams.closeQuietly(host);
+        if (mgmt != null) Entities.destroyAll(mgmt);
+    }
+    
+    @Test(groups = "Integration")
+    public void testGetMachineDetails() throws Exception {
+        BasicExecutionManager execManager = new BasicExecutionManager("mycontextid");
+        BasicExecutionContext execContext = new BasicExecutionContext(execManager);
+        try {
+            MachineDetails details = execContext.submit(new Callable<MachineDetails>() {
+                public MachineDetails call() {
+                    return host.getMachineDetails();
+                }}).get();
+            assertNotNull(details);
+        } finally {
+            execManager.shutdownNow();
+        }
+    }
+    
+    @Test
+    public void testSupplyingMachineDetails() throws Exception {
+        MachineDetails machineDetails = new BasicMachineDetails(new BasicHardwareDetails(1, 1024), new BasicOsDetails("myname", "myarch", "myversion"));
+        SshMachineLocation host2 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure(SshMachineLocation.MACHINE_DETAILS, machineDetails));
+        
+        assertSame(host2.getMachineDetails(), machineDetails);
+    }
+    
+    @Test
+    public void testConfigurePrivateAddresses() throws Exception {
+        SshMachineLocation host2 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure("address", Networking.getLocalHost())
+                .configure(SshMachineLocation.PRIVATE_ADDRESSES, ImmutableList.of("1.2.3.4"))
+                .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, true));
+
+        assertEquals(host2.getPrivateAddresses(), ImmutableSet.of("1.2.3.4"));
+    }
+    
+    // Wow, this is hard to test (until I accepted creating the entity + effector)! Code smell?
+    // Need to call getMachineDetails in a DynamicSequentialTask so that the "innessential" takes effect,
+    // to not fail its caller. But to get one of those outside of an effector is non-obvious.
+    @Test(groups = "Integration")
+    public void testGetMachineIsInessentialOnFailure() throws Exception {
+        SshMachineLocation host2 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure("address", Networking.getLocalHost())
+                .configure(SshTool.PROP_TOOL_CLASS, FailingSshTool.class.getName()));
+
+        final Effector<MachineDetails> GET_MACHINE_DETAILS = Effectors.effector(MachineDetails.class, "getMachineDetails")
+                .impl(new EffectorBody<MachineDetails>() {
+                    public MachineDetails call(ConfigBag parameters) {
+                        Maybe<MachineLocation> machine = Machines.findUniqueMachineLocation(entity().getLocations());
+                        try {
+                            machine.get().getMachineDetails();
+                            throw new IllegalStateException("Expected failure in ssh");
+                        } catch (RuntimeException e) {
+                            return null;
+                        }
+                    }})
+                .build();
+
+        EntitySpec<TestApplication> appSpec = EntitySpec.create(TestApplication.class)
+                .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, true)
+                .addInitializer(new EntityInitializer() {
+                        public void apply(EntityLocal entity) {
+                            ((EntityInternal)entity).getMutableEntityType().addEffector(EffectorTaskTest.DOUBLE_1);
+                        }});
+
+        TestApplication app = ApplicationBuilder.newManagedApp(appSpec, mgmt);
+
+        app.start(ImmutableList.of(host2));
+        
+        MachineDetails details = app.invoke(GET_MACHINE_DETAILS, ImmutableMap.<String, Object>of()).get();
+        assertNull(details);
+    }
+    public static class FailingSshTool extends RecordingSshTool {
+        public FailingSshTool(Map<?, ?> props) {
+            super(props);
+        }
+        @Override public int execScript(Map<String, ?> props, List<String> commands, Map<String, ?> env) {
+            throw new RuntimeException("Simulating failure of ssh: cmds="+commands);
+        }
+        @Override public int execCommands(Map<String, ?> props, List<String> commands, Map<String, ?> env) {
+            throw new RuntimeException("Simulating failure of ssh: cmds="+commands);
+        }
+    }
+    
+    // Note: requires `ssh localhost` to be setup such that no password is required    
+    @Test(groups = "Integration")
+    public void testSshExecScript() throws Exception {
+        OutputStream outStream = new ByteArrayOutputStream();
+        String expectedName = Os.user();
+        host.execScript(MutableMap.of("out", outStream), "mysummary", ImmutableList.of("whoami; exit"));
+        String outString = outStream.toString();
+        
+        assertTrue(outString.contains(expectedName), outString);
+    }
+    
+    // Note: requires `ssh localhost` to be setup such that no password is required    
+    @Test(groups = "Integration")
+    public void testSshExecCommands() throws Exception {
+        OutputStream outStream = new ByteArrayOutputStream();
+        String expectedName = Os.user();
+        host.execCommands(MutableMap.of("out", outStream), "mysummary", ImmutableList.of("whoami; exit"));
+        String outString = outStream.toString();
+        
+        assertTrue(outString.contains(expectedName), outString);
+    }
+    
+    // For issue #230
+    @Test(groups = "Integration")
+    public void testOverridingPropertyOnExec() throws Exception {
+        SshMachineLocation host = new SshMachineLocation(MutableMap.of("address", Networking.getLocalHost(), "sshPrivateKeyData", "wrongdata"));
+        
+        OutputStream outStream = new ByteArrayOutputStream();
+        String expectedName = Os.user();
+        host.execCommands(MutableMap.of("sshPrivateKeyData", null, "out", outStream), "my summary", ImmutableList.of("whoami"));
+        String outString = outStream.toString();
+        
+        assertTrue(outString.contains(expectedName), "outString="+outString);
+    }
+
+    @Test(groups = "Integration", expectedExceptions={IllegalStateException.class, SshException.class})
+    public void testSshRunWithInvalidUserFails() throws Exception {
+        SshMachineLocation badHost = new SshMachineLocation(MutableMap.of("user", "doesnotexist", "address", Networking.getLocalHost()));
+        badHost.execScript("mysummary", ImmutableList.of("whoami; exit"));
+    }
+    
+    // Note: requires `ssh localhost` to be setup such that no password is required    
+    @Test(groups = "Integration")
+    public void testCopyFileTo() throws Exception {
+        File dest = Os.newTempFile(getClass(), ".dest.tmp");
+        File src = Os.newTempFile(getClass(), ".src.tmp");
+        try {
+            Files.write("abc", src, Charsets.UTF_8);
+            host.copyTo(src, dest);
+            assertEquals("abc", Files.readFirstLine(dest, Charsets.UTF_8));
+        } finally {
+            src.delete();
+            dest.delete();
+        }
+    }
+
+    // Note: requires `ssh localhost` to be setup such that no password is required    
+    @Test(groups = "Integration")
+    public void testCopyStreamTo() throws Exception {
+        String contents = "abc";
+        File dest = new File(Os.tmp(), "sssMachineLocationTest_dest.tmp");
+        try {
+            host.copyTo(Streams.newInputStreamWithContents(contents), dest.getAbsolutePath());
+            assertEquals("abc", Files.readFirstLine(dest, Charsets.UTF_8));
+        } finally {
+            dest.delete();
+        }
+    }
+
+    @Test(groups = "Integration")
+    public void testInstallUrlTo() throws Exception {
+        File dest = new File(Os.tmp(), "sssMachineLocationTest_dir/");
+        dest.mkdir();
+        try {
+            int result = host.installTo("https://raw.github.com/brooklyncentral/brooklyn/master/README.md", Urls.mergePaths(dest.getAbsolutePath(), "README.md"));
+            assertEquals(result, 0);
+            String contents = ArchiveUtils.readFullyString(new File(dest, "README.md"));
+            assertTrue(contents.contains("http://brooklyncentral.github.com"), "contents missing expected phrase; contains:\n"+contents);
+        } finally {
+            dest.delete();
+        }
+    }
+    
+    @Test(groups = "Integration")
+    public void testInstallClasspathCopyTo() throws Exception {
+        File dest = new File(Os.tmp(), "sssMachineLocationTest_dir/");
+        dest.mkdir();
+        try {
+            int result = host.installTo("classpath://brooklyn/config/sample.properties", Urls.mergePaths(dest.getAbsolutePath(), "sample.properties"));
+            assertEquals(result, 0);
+            String contents = ArchiveUtils.readFullyString(new File(dest, "sample.properties"));
+            assertTrue(contents.contains("Property 1"), "contents missing expected phrase; contains:\n"+contents);
+        } finally {
+            dest.delete();
+        }
+    }
+
+    // Note: requires `ssh localhost` to be setup such that no password is required    
+    @Test(groups = "Integration")
+    public void testIsSshableWhenTrue() throws Exception {
+        assertTrue(host.isSshable());
+    }
+    
+    // Note: on some (home/airport) networks, `ssh 123.123.123.123` hangs seemingly forever.
+    // Make sure we fail, waiting for longer than the 70 second TCP timeout.
+    //
+    // Times out in 2m7s on Ubuntu Vivid (syn retries set to 6)
+    @Test(groups = "Integration")
+    public void testIsSshableWhenFalse() throws Exception {
+        byte[] unreachableIp = new byte[] {123,123,123,123};
+        final SshMachineLocation unreachableHost = new SshMachineLocation(MutableMap.of("address", InetAddress.getByAddress("unreachablename", unreachableIp)));
+        Asserts.assertReturnsEventually(new Runnable() {
+            public void run() {
+                assertFalse(unreachableHost.isSshable());
+            }},
+            Duration.minutes(3));
+    }
+    
+    @Test
+    public void obtainSpecificPortGivesOutPortOnlyOnce() {
+        int port = 2345;
+        assertTrue(host.obtainSpecificPort(port));
+        assertFalse(host.obtainSpecificPort(port));
+        host.releasePort(port);
+        assertTrue(host.obtainSpecificPort(port));
+    }
+    
+    @Test
+    public void obtainPortInRangeGivesBackRequiredPortOnlyIfAvailable() {
+        int port = 2345;
+        assertEquals(host.obtainPort(new PortRanges.LinearPortRange(port, port)), port);
+        assertEquals(host.obtainPort(new PortRanges.LinearPortRange(port, port)), -1);
+        host.releasePort(port);
+        assertEquals(host.obtainPort(new PortRanges.LinearPortRange(port, port)), port);
+    }
+    
+    @Test
+    public void obtainPortInWideRange() {
+        int lowerPort = 2345;
+        int upperPort = 2350;
+        PortRange range = new PortRanges.LinearPortRange(lowerPort, upperPort);
+        for (int i = lowerPort; i <= upperPort; i++) {
+            assertEquals(host.obtainPort(range), i);
+        }
+        assertEquals(host.obtainPort(range), -1);
+        
+        host.releasePort(lowerPort);
+        assertEquals(host.obtainPort(range), lowerPort);
+        assertEquals(host.obtainPort(range), -1);
+    }
+    
+    @Test
+    public void testObtainPortDoesNotUsePreReservedPorts() {
+        host = new SshMachineLocation(MutableMap.of("address", Networking.getLocalHost(), "usedPorts", ImmutableSet.of(8000)));
+        assertEquals(host.obtainPort(PortRanges.fromString("8000")), -1);
+        assertEquals(host.obtainPort(PortRanges.fromString("8000+")), 8001);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/winrm/AdvertiseWinrmLoginPolicyTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/winrm/AdvertiseWinrmLoginPolicyTest.java b/core/src/test/java/org/apache/brooklyn/location/winrm/AdvertiseWinrmLoginPolicyTest.java
new file mode 100644
index 0000000..65ac92e
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/winrm/AdvertiseWinrmLoginPolicyTest.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.winrm;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.policy.PolicySpec;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.winrm.AdvertiseWinrmLoginPolicy;
+import org.apache.brooklyn.location.winrm.WinRmMachineLocation;
+
+import com.google.common.collect.ImmutableList;
+
+public class AdvertiseWinrmLoginPolicyTest extends BrooklynAppUnitTestSupport {
+
+    @Test
+    public void testAdvertisesMachineLoginDetails() throws Exception {
+        TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class)
+                .policy(PolicySpec.create(AdvertiseWinrmLoginPolicy.class)));
+        
+        WinRmMachineLocation machine = mgmt.getLocationManager().createLocation(LocationSpec.create(WinRmMachineLocation.class)
+                .configure("address", "1.2.3.4")
+                .configure("user", "myuser")
+                .configure("port", 5678)
+                .configure("password", "mypassword"));
+        app.start(ImmutableList.of(machine));
+        
+        String expected = "myuser : mypassword @ 1.2.3.4:5678";
+
+        EntityTestUtils.assertAttributeEqualsEventually(entity, AdvertiseWinrmLoginPolicy.VM_USER_CREDENTIALS, expected);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/location/winrm/WinRmMachineLocationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/location/winrm/WinRmMachineLocationTest.java b/core/src/test/java/org/apache/brooklyn/location/winrm/WinRmMachineLocationTest.java
new file mode 100644
index 0000000..4dd4727
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/location/winrm/WinRmMachineLocationTest.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.winrm;
+
+import static org.testng.Assert.assertEquals;
+
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.location.winrm.WinRmMachineLocation;
+import org.apache.brooklyn.util.net.Networking;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+
+public class WinRmMachineLocationTest extends BrooklynAppUnitTestSupport {
+
+    @Test
+    public void testConfigurePrivateAddresses() throws Exception {
+        WinRmMachineLocation host = mgmt.getLocationManager().createLocation(LocationSpec.create(WinRmMachineLocation.class)
+                .configure("address", Networking.getLocalHost())
+                .configure(WinRmMachineLocation.PRIVATE_ADDRESSES, ImmutableList.of("1.2.3.4"))
+                .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, true));
+
+        assertEquals(host.getPrivateAddresses(), ImmutableSet.of("1.2.3.4"));
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/sensor/enricher/CustomAggregatingEnricherDeprecatedTest.groovy
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/sensor/enricher/CustomAggregatingEnricherDeprecatedTest.groovy b/core/src/test/java/org/apache/brooklyn/sensor/enricher/CustomAggregatingEnricherDeprecatedTest.groovy
index 5656aa6..a2416ef 100644
--- a/core/src/test/java/org/apache/brooklyn/sensor/enricher/CustomAggregatingEnricherDeprecatedTest.groovy
+++ b/core/src/test/java/org/apache/brooklyn/sensor/enricher/CustomAggregatingEnricherDeprecatedTest.groovy
@@ -18,13 +18,15 @@
  */
 package org.apache.brooklyn.sensor.enricher
 
+import static org.testng.Assert.assertEquals
+
 import org.apache.brooklyn.api.entity.EntitySpec
 import org.apache.brooklyn.api.sensor.AttributeSensor
 import org.apache.brooklyn.core.test.entity.TestApplication
 import org.apache.brooklyn.core.test.entity.TestEntity
 import org.apache.brooklyn.entity.core.Entities
 import org.apache.brooklyn.entity.group.BasicGroup
-import org.apache.brooklyn.location.basic.SimulatedLocation
+import org.apache.brooklyn.location.core.SimulatedLocation
 import org.apache.brooklyn.sensor.core.BasicAttributeSensor
 import org.apache.brooklyn.test.TestUtils
 import org.slf4j.Logger
@@ -32,7 +34,6 @@ import org.slf4j.LoggerFactory
 import org.testng.annotations.AfterMethod
 import org.testng.annotations.BeforeMethod
 import org.testng.annotations.Test
-import static org.testng.Assert.assertEquals
 
 import com.google.common.base.Function
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/sensor/enricher/CustomAggregatingEnricherTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/sensor/enricher/CustomAggregatingEnricherTest.java b/core/src/test/java/org/apache/brooklyn/sensor/enricher/CustomAggregatingEnricherTest.java
index 6aba673..0d9c2a7 100644
--- a/core/src/test/java/org/apache/brooklyn/sensor/enricher/CustomAggregatingEnricherTest.java
+++ b/core/src/test/java/org/apache/brooklyn/sensor/enricher/CustomAggregatingEnricherTest.java
@@ -36,7 +36,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Function;
 import com.google.common.base.Predicates;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/sensor/enricher/TransformingEnricherDeprecatedTest.groovy
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/sensor/enricher/TransformingEnricherDeprecatedTest.groovy b/core/src/test/java/org/apache/brooklyn/sensor/enricher/TransformingEnricherDeprecatedTest.groovy
index 4251c2d..7b2a290 100644
--- a/core/src/test/java/org/apache/brooklyn/sensor/enricher/TransformingEnricherDeprecatedTest.groovy
+++ b/core/src/test/java/org/apache/brooklyn/sensor/enricher/TransformingEnricherDeprecatedTest.groovy
@@ -25,7 +25,7 @@ import org.apache.brooklyn.api.sensor.AttributeSensor
 import org.apache.brooklyn.core.test.entity.TestApplication
 import org.apache.brooklyn.core.test.entity.TestEntity
 import org.apache.brooklyn.entity.core.Entities
-import org.apache.brooklyn.location.basic.SimulatedLocation
+import org.apache.brooklyn.location.core.SimulatedLocation
 import org.apache.brooklyn.sensor.core.BasicAttributeSensor
 import org.apache.brooklyn.test.TestUtils
 import org.apache.brooklyn.util.collections.MutableMap

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/sensor/enricher/TransformingEnricherTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/sensor/enricher/TransformingEnricherTest.java b/core/src/test/java/org/apache/brooklyn/sensor/enricher/TransformingEnricherTest.java
index 4510c4a..d438933 100644
--- a/core/src/test/java/org/apache/brooklyn/sensor/enricher/TransformingEnricherTest.java
+++ b/core/src/test/java/org/apache/brooklyn/sensor/enricher/TransformingEnricherTest.java
@@ -30,7 +30,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.SimulatedLocation;
+import org.apache.brooklyn.location.core.SimulatedLocation;
 
 import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/sensor/feed/function/FunctionFeedTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/sensor/feed/function/FunctionFeedTest.java b/core/src/test/java/org/apache/brooklyn/sensor/feed/function/FunctionFeedTest.java
index a8f1a1f..bd3e0da 100644
--- a/core/src/test/java/org/apache/brooklyn/sensor/feed/function/FunctionFeedTest.java
+++ b/core/src/test/java/org/apache/brooklyn/sensor/feed/function/FunctionFeedTest.java
@@ -52,7 +52,7 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Function;
 import com.google.common.base.Functions;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/sensor/feed/http/HttpFeedIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/sensor/feed/http/HttpFeedIntegrationTest.java b/core/src/test/java/org/apache/brooklyn/sensor/feed/http/HttpFeedIntegrationTest.java
index 9295b5a..ea01eb3 100644
--- a/core/src/test/java/org/apache/brooklyn/sensor/feed/http/HttpFeedIntegrationTest.java
+++ b/core/src/test/java/org/apache/brooklyn/sensor/feed/http/HttpFeedIntegrationTest.java
@@ -39,8 +39,8 @@ import org.apache.brooklyn.test.EntityTestUtils;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Functions;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/sensor/feed/shell/ShellFeedIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/sensor/feed/shell/ShellFeedIntegrationTest.java b/core/src/test/java/org/apache/brooklyn/sensor/feed/shell/ShellFeedIntegrationTest.java
index 1a53f78..cab9610 100644
--- a/core/src/test/java/org/apache/brooklyn/sensor/feed/shell/ShellFeedIntegrationTest.java
+++ b/core/src/test/java/org/apache/brooklyn/sensor/feed/shell/ShellFeedIntegrationTest.java
@@ -46,7 +46,7 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/sensor/feed/ssh/SshFeedIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/sensor/feed/ssh/SshFeedIntegrationTest.java b/core/src/test/java/org/apache/brooklyn/sensor/feed/ssh/SshFeedIntegrationTest.java
index 02eeaac..c0708b7 100644
--- a/core/src/test/java/org/apache/brooklyn/sensor/feed/ssh/SshFeedIntegrationTest.java
+++ b/core/src/test/java/org/apache/brooklyn/sensor/feed/ssh/SshFeedIntegrationTest.java
@@ -51,8 +51,8 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Function;
 import com.google.common.base.Predicates;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/sensor/feed/windows/WindowsPerformanceCounterFeedTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/sensor/feed/windows/WindowsPerformanceCounterFeedTest.java b/core/src/test/java/org/apache/brooklyn/sensor/feed/windows/WindowsPerformanceCounterFeedTest.java
index 499f549..0c6cbc1 100644
--- a/core/src/test/java/org/apache/brooklyn/sensor/feed/windows/WindowsPerformanceCounterFeedTest.java
+++ b/core/src/test/java/org/apache/brooklyn/sensor/feed/windows/WindowsPerformanceCounterFeedTest.java
@@ -42,7 +42,7 @@ import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 
 import io.cloudsoft.winrm4j.winrm.WinRmToolResponse;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/util/core/file/ArchiveUtilsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/util/core/file/ArchiveUtilsTest.java b/core/src/test/java/org/apache/brooklyn/util/core/file/ArchiveUtilsTest.java
index d44199c..4224d8d 100644
--- a/core/src/test/java/org/apache/brooklyn/util/core/file/ArchiveUtilsTest.java
+++ b/core/src/test/java/org/apache/brooklyn/util/core/file/ArchiveUtilsTest.java
@@ -31,7 +31,7 @@ import org.testng.annotations.BeforeClass;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.ResourceUtils;
 import org.apache.brooklyn.util.core.file.ArchiveBuilder;
 import org.apache.brooklyn.util.core.file.ArchiveUtils;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/util/core/http/HttpToolIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/util/core/http/HttpToolIntegrationTest.java b/core/src/test/java/org/apache/brooklyn/util/core/http/HttpToolIntegrationTest.java
index 788b3c6..fc830a6 100644
--- a/core/src/test/java/org/apache/brooklyn/util/core/http/HttpToolIntegrationTest.java
+++ b/core/src/test/java/org/apache/brooklyn/util/core/http/HttpToolIntegrationTest.java
@@ -27,7 +27,7 @@ import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 import org.apache.brooklyn.core.test.HttpService;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.util.core.http.HttpTool;
 import org.apache.brooklyn.util.core.http.HttpToolResponse;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/util/core/ssh/BashCommandsIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/util/core/ssh/BashCommandsIntegrationTest.java b/core/src/test/java/org/apache/brooklyn/util/core/ssh/BashCommandsIntegrationTest.java
index a2d3480..10bbf67 100644
--- a/core/src/test/java/org/apache/brooklyn/util/core/ssh/BashCommandsIntegrationTest.java
+++ b/core/src/test/java/org/apache/brooklyn/util/core/ssh/BashCommandsIntegrationTest.java
@@ -53,8 +53,8 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
 import com.google.common.base.Charsets;
 import com.google.common.collect.ImmutableList;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/test/java/org/apache/brooklyn/util/core/task/ssh/SshTasksTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/util/core/task/ssh/SshTasksTest.java b/core/src/test/java/org/apache/brooklyn/util/core/task/ssh/SshTasksTest.java
index 96f38c4..7c734ff 100644
--- a/core/src/test/java/org/apache/brooklyn/util/core/task/ssh/SshTasksTest.java
+++ b/core/src/test/java/org/apache/brooklyn/util/core/task/ssh/SshTasksTest.java
@@ -33,8 +33,8 @@ import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.core.ssh.BashCommandsIntegrationTest;
 import org.apache.brooklyn.util.core.task.ssh.SshFetchTaskFactory;
 import org.apache.brooklyn.util.core.task.ssh.SshFetchTaskWrapper;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/examples/global-web-fabric/src/main/java/org/apache/brooklyn/demo/GlobalWebFabricExample.java
----------------------------------------------------------------------
diff --git a/examples/global-web-fabric/src/main/java/org/apache/brooklyn/demo/GlobalWebFabricExample.java b/examples/global-web-fabric/src/main/java/org/apache/brooklyn/demo/GlobalWebFabricExample.java
index ff2627d..5bb8426 100644
--- a/examples/global-web-fabric/src/main/java/org/apache/brooklyn/demo/GlobalWebFabricExample.java
+++ b/examples/global-web-fabric/src/main/java/org/apache/brooklyn/demo/GlobalWebFabricExample.java
@@ -40,7 +40,7 @@ import org.apache.brooklyn.entity.proxy.AbstractController;
 import org.apache.brooklyn.entity.webapp.ElasticJavaWebAppService;
 import org.apache.brooklyn.entity.webapp.JavaWebAppService;
 import org.apache.brooklyn.launcher.BrooklynLauncher;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;
 import org.apache.brooklyn.util.CommandLineUtil;
 import org.apache.brooklyn.util.core.BrooklynMavenArtifacts;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/examples/simple-nosql-cluster/src/main/java/org/apache/brooklyn/demo/CumulusRDFApplication.java
----------------------------------------------------------------------
diff --git a/examples/simple-nosql-cluster/src/main/java/org/apache/brooklyn/demo/CumulusRDFApplication.java b/examples/simple-nosql-cluster/src/main/java/org/apache/brooklyn/demo/CumulusRDFApplication.java
index 26891d5..5f9d297 100644
--- a/examples/simple-nosql-cluster/src/main/java/org/apache/brooklyn/demo/CumulusRDFApplication.java
+++ b/examples/simple-nosql-cluster/src/main/java/org/apache/brooklyn/demo/CumulusRDFApplication.java
@@ -53,7 +53,7 @@ import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.entity.webapp.JavaWebAppService;
 import org.apache.brooklyn.entity.webapp.tomcat.TomcatServer;
 import org.apache.brooklyn.launcher.BrooklynLauncher;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.policy.ha.ServiceFailureDetector;
 import org.apache.brooklyn.policy.ha.ServiceReplacer;
 import org.apache.brooklyn.policy.ha.ServiceRestarter;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/SingleWebServerExample.java
----------------------------------------------------------------------
diff --git a/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/SingleWebServerExample.java b/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/SingleWebServerExample.java
index 46be8bb..77adc18 100644
--- a/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/SingleWebServerExample.java
+++ b/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/SingleWebServerExample.java
@@ -30,7 +30,7 @@ import org.apache.brooklyn.entity.core.StartableApplication;
 import org.apache.brooklyn.entity.webapp.JavaWebAppService;
 import org.apache.brooklyn.entity.webapp.jboss.JBoss7Server;
 import org.apache.brooklyn.launcher.BrooklynLauncher;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.util.CommandLineUtil;
 
 import com.google.common.collect.Lists;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExample.java
----------------------------------------------------------------------
diff --git a/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExample.java b/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExample.java
index 8682335..1092262 100644
--- a/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExample.java
+++ b/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExample.java
@@ -39,7 +39,7 @@ import org.apache.brooklyn.entity.webapp.JavaWebAppService;
 import org.apache.brooklyn.entity.webapp.WebAppService;
 import org.apache.brooklyn.entity.webapp.WebAppServiceConstants;
 import org.apache.brooklyn.launcher.BrooklynLauncher;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.policy.autoscaling.AutoScalerPolicy;
 import org.apache.brooklyn.policy.enricher.HttpLatencyDetector;
 import org.apache.brooklyn.sensor.core.Sensors;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleApp.java
----------------------------------------------------------------------
diff --git a/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleApp.java b/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleApp.java
index e13a632..2030200 100644
--- a/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleApp.java
+++ b/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleApp.java
@@ -44,7 +44,7 @@ import org.apache.brooklyn.entity.database.mysql.MySqlNode;
 import org.apache.brooklyn.entity.group.DynamicCluster;
 import org.apache.brooklyn.entity.java.JavaEntityMethods;
 import org.apache.brooklyn.launcher.BrooklynLauncher;
-import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.core.PortRanges;
 import org.apache.brooklyn.policy.autoscaling.AutoScalerPolicy;
 import org.apache.brooklyn.policy.enricher.HttpLatencyDetector;
 import org.apache.brooklyn.sensor.core.Sensors;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleGroovy.groovy
----------------------------------------------------------------------
diff --git a/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleGroovy.groovy b/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleGroovy.groovy
index dfd677d..9327db4 100644
--- a/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleGroovy.groovy
+++ b/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleGroovy.groovy
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.demo;
 
-import static brooklyn.entity.java.JavaEntityMethods.javaSysProp
+import static org.apache.brooklyn.entity.java.JavaEntityMethods.javaSysProp
 import static org.apache.brooklyn.sensor.core.DependentConfiguration.attributeWhenReady
 import static org.apache.brooklyn.sensor.core.DependentConfiguration.formatString
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/brooklyn/entity/rebind/persister/jclouds/JcloudsBlobStoreBasedObjectStore.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/brooklyn/entity/rebind/persister/jclouds/JcloudsBlobStoreBasedObjectStore.java b/locations/jclouds/src/main/java/brooklyn/entity/rebind/persister/jclouds/JcloudsBlobStoreBasedObjectStore.java
deleted file mode 100644
index 782f160..0000000
--- a/locations/jclouds/src/main/java/brooklyn/entity/rebind/persister/jclouds/JcloudsBlobStoreBasedObjectStore.java
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.rebind.persister.jclouds;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.List;
-
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistMode;
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
-import org.apache.brooklyn.core.server.BrooklynServerConfig;
-import org.jclouds.blobstore.BlobStoreContext;
-import org.jclouds.blobstore.domain.StorageMetadata;
-import org.jclouds.blobstore.options.ListContainerOptions;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.LocationConfigKeys;
-import org.apache.brooklyn.location.cloud.CloudLocationConfig;
-import org.apache.brooklyn.location.jclouds.JcloudsLocation;
-import org.apache.brooklyn.location.jclouds.JcloudsUtil;
-import org.apache.brooklyn.util.exceptions.FatalConfigurationRuntimeException;
-import org.apache.brooklyn.util.text.Strings;
-
-import com.google.common.base.Function;
-import com.google.common.base.Objects;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.FluentIterable;
-
-/**
- * @author Andrea Turli
- */
-public class JcloudsBlobStoreBasedObjectStore implements PersistenceObjectStore {
-
-    private static final Logger log = LoggerFactory.getLogger(JcloudsBlobStoreBasedObjectStore.class);
-
-    private final String containerNameFirstPart;
-    private final String containerSubPath;
-    
-    private String locationSpec;
-    private JcloudsLocation location;
-    private BlobStoreContext context;
-
-    private ManagementContext mgmt;
-
-    public JcloudsBlobStoreBasedObjectStore(String locationSpec, String containerName) {
-        this.locationSpec = locationSpec;
-        String[] segments = splitOnce(containerName);
-        this.containerNameFirstPart = segments[0];
-        this.containerSubPath = segments[1];
-    }
-    
-    private String[] splitOnce(String path) {
-        String separator = subPathSeparator();
-        int index = path.indexOf(separator);
-        if (index<0) return new String[] { path, "" };
-        return new String[] { path.substring(0, index), path.substring(index+separator.length()) };
-    }
-
-    public JcloudsBlobStoreBasedObjectStore(JcloudsLocation location, String containerName) {
-        this.location = location;
-        String[] segments = splitOnce(containerName);
-        this.containerNameFirstPart = segments[0];
-        this.containerSubPath = segments[1];
-        getBlobStoreContext();
-    }
-
-    public String getSummaryName() {
-        return (locationSpec!=null ? locationSpec : location)+":"+getContainerNameFull();
-    }
-    
-    public synchronized BlobStoreContext getBlobStoreContext() {
-        if (context==null) {
-            if (location==null) {
-                Preconditions.checkNotNull(locationSpec, "locationSpec required for remote object store when location is null");
-                Preconditions.checkNotNull(mgmt, "mgmt not injected / object store not prepared");
-                location = (JcloudsLocation) mgmt.getLocationRegistry().resolve(locationSpec);
-            }
-            
-            String identity = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_IDENTITY), "identity must not be null");
-            String credential = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_CREDENTIAL), "credential must not be null");
-            String provider = checkNotNull(location.getConfig(LocationConfigKeys.CLOUD_PROVIDER), "provider must not be null");
-            String endpoint = location.getConfig(CloudLocationConfig.CLOUD_ENDPOINT);
-
-            context = JcloudsUtil.newBlobstoreContext(provider, endpoint, identity, credential);
-     
-            // TODO do we need to get location from region? can't see the jclouds API.
-            // doesn't matter in some places because it's already in the endpoint
-//            String region = location.getConfig(CloudLocationConfig.CLOUD_REGION_ID);
-            context.getBlobStore().createContainerInLocation(null, getContainerNameFirstPart());
-        }
-        return context;
-    }
-
-    @Override
-    public void prepareForMasterUse() {
-        // backups not supported here, that is all which is needed for master use
-        // that's now normally done *prior* to calling in to here for writes
-        // (and we have already thrown in prepareForSharedUse if legacy backups have been specified as required)
-    }
-    
-    public String getContainerName() {
-        return getContainerNameFull();
-    }
-    
-    protected String getContainerNameFull() {
-        return mergePaths(containerNameFirstPart, containerSubPath);
-    }
-
-    protected String getContainerNameFirstPart() {
-        return containerNameFirstPart;
-    }
-    
-    protected String getItemInContainerSubPath(String path) {
-        if (Strings.isBlank(containerSubPath)) return path;
-        return mergePaths(containerSubPath, path);
-    }
-
-    @Override
-    public void createSubPath(String subPath) {
-        // not needed - subpaths are created on demant
-        // (and buggy on softlayer w swift w jclouds 1.7.2:
-        // throws a "not found" if we're creating an empty directory from scratch)
-//        context.getBlobStore().createDirectory(getContainerName(), subPath);
-    }
-
-    protected void checkPrepared() {
-        if (context==null)
-            throw new IllegalStateException("object store not prepared");
-    }
-    
-    @Override
-    public StoreObjectAccessor newAccessor(String path) {
-        checkPrepared();
-        return new JcloudsStoreObjectAccessor(context.getBlobStore(), getContainerNameFirstPart(), getItemInContainerSubPath(path));
-    }
-
-    protected String mergePaths(String basePath, String ...subPaths) {
-        StringBuilder result = new StringBuilder(basePath);
-        for (String subPath: subPaths) {
-            if (result.length()>0 && subPath.length()>0) {
-                result.append(subPathSeparator());
-                result.append(subPath);
-            }
-        }
-        return result.toString();
-    }
-    
-    protected String subPathSeparator() {
-        // in case some object stores don't allow / for paths
-        return "/";
-    }
-
-    @Override
-    public List<String> listContentsWithSubPath(final String parentSubPath) {
-        checkPrepared();
-        return FluentIterable.from(context.getBlobStore().list(getContainerNameFirstPart(), 
-            ListContainerOptions.Builder.inDirectory(getItemInContainerSubPath(parentSubPath))))
-                .transform(new Function<StorageMetadata, String>() {
-                    @Override
-                    public String apply(@javax.annotation.Nullable StorageMetadata input) {
-                        String result = input.getName();
-                        result = Strings.removeFromStart(result, containerSubPath);
-                        result = Strings.removeFromStart(result, "/");
-                        return result;
-                    }
-                }).toList();
-    }
-
-    @Override
-    public void close() {
-        if (context!=null)
-            context.close();
-    }
-
-    @Override
-    public String toString() {
-        return Objects.toStringHelper(this)
-                .add("blobStoreContext", context)
-                .add("basedir", containerNameFirstPart)
-                .toString();
-    }
-    
-    @Override
-    public void injectManagementContext(ManagementContext mgmt) {
-        if (this.mgmt!=null && !this.mgmt.equals(mgmt))
-            throw new IllegalStateException("Cannot change mgmt context of "+this);
-        this.mgmt = mgmt;
-    }
-    
-    @SuppressWarnings("deprecation")
-    @Override
-    public void prepareForSharedUse(@Nullable PersistMode persistMode, HighAvailabilityMode haMode) {
-        if (mgmt==null) throw new NullPointerException("Must inject ManagementContext before preparing "+this);
-        
-        getBlobStoreContext();
-        
-        if (persistMode==null || persistMode==PersistMode.DISABLED) {
-            log.warn("Should not be using "+this+" when persistMode is "+persistMode);
-            return;
-        }
-        
-        Boolean backups = mgmt.getConfig().getConfig(BrooklynServerConfig.PERSISTENCE_BACKUPS_REQUIRED);
-        if (Boolean.TRUE.equals(backups)) {
-            log.warn("Using legacy backup for "+this+"; functionality will be removed in future versions, in favor of promotion/demotion-specific backups to a configurable backup location.");
-            throw new FatalConfigurationRuntimeException("Backups not supported for object store ("+this+")");
-        }
-    }
-
-    @Override
-    public void deleteCompletely() {
-        if (Strings.isBlank(containerSubPath))
-            getBlobStoreContext().getBlobStore().deleteContainer(containerNameFirstPart);
-        else
-            newAccessor(containerSubPath).delete();
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/brooklyn/entity/rebind/persister/jclouds/JcloudsStoreObjectAccessor.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/brooklyn/entity/rebind/persister/jclouds/JcloudsStoreObjectAccessor.java b/locations/jclouds/src/main/java/brooklyn/entity/rebind/persister/jclouds/JcloudsStoreObjectAccessor.java
deleted file mode 100644
index a8f1c76..0000000
--- a/locations/jclouds/src/main/java/brooklyn/entity/rebind/persister/jclouds/JcloudsStoreObjectAccessor.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.rebind.persister.jclouds;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Date;
-
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.commons.io.Charsets;
-import org.jclouds.blobstore.BlobStore;
-import org.jclouds.blobstore.domain.Blob;
-import org.jclouds.util.Strings2;
-
-import com.google.common.base.Throwables;
-import com.google.common.io.ByteSource;
-import com.google.common.io.ByteStreams;
-
-/**
- * @author Andrea Turli
- */
-public class JcloudsStoreObjectAccessor implements PersistenceObjectStore.StoreObjectAccessor {
-
-    private final BlobStore blobStore;
-    private final String containerName;
-    private final String blobName;
-
-    public JcloudsStoreObjectAccessor(BlobStore blobStore, String containerName, String blobNameOptionallyWithPath) {
-        this.blobStore = blobStore;
-        this.containerName = containerName;
-        this.blobName = blobNameOptionallyWithPath;
-    }
-
-    @Override
-    public boolean exists() {
-        return blobStore.blobExists(containerName, blobName);
-    }
-
-    @Override
-    public void put(String val) {
-        if (val==null) val = "";
-        
-        blobStore.createContainerInLocation(null, containerName);
-        // seems not needed, at least not w SoftLayer
-//        blobStore.createDirectory(containerName, directoryName);
-        ByteSource payload = ByteSource.wrap(val.getBytes(Charsets.UTF_8));
-        Blob blob;
-        try {
-            blob = blobStore.blobBuilder(blobName).payload(payload)
-                    .contentLength(payload.size())
-                    .build();
-        } catch (IOException e) {
-            throw Throwables.propagate(e);
-        }
-        blobStore.putBlob(containerName, blob);
-    }
-
-    @Override
-    public void append(String val) {
-        String val0 = get();
-        if (val0==null) val0="";
-        if (val==null) val="";
-        put(val0+val);
-    }
-
-    @Override
-    public void delete() {
-        blobStore.removeBlob(containerName, blobName);
-    }
-
-    @Override
-    public String get() {
-        try {
-            Blob blob = blobStore.getBlob(containerName, blobName);
-            if (blob==null) return null;
-            return Strings2.toStringAndClose(blob.getPayload().openStream());
-        } catch (IOException e) {
-            Exceptions.propagateIfFatal(e);
-            throw new IllegalStateException("Error reading blobstore "+containerName+" "+blobName+": "+e, e);
-        }
-    }
-
-    @Override
-    public byte[] getBytes() {
-        try {
-            Blob blob = blobStore.getBlob(containerName, blobName);
-            if (blob==null) return null;
-            ByteArrayOutputStream out = new ByteArrayOutputStream();
-            InputStream in = blob.getPayload().openStream();
-            try {
-                ByteStreams.copy(in, out);
-                return out.toByteArray();
-            } finally {
-                out.close();
-            }
-        } catch (IOException e) {
-            Exceptions.propagateIfFatal(e);
-            throw new IllegalStateException("Error reading blobstore "+containerName+" "+blobName+": "+e, e);
-        }
-    }
-
-    @Override
-    public Date getLastModifiedDate() {
-        Blob blob = blobStore.getBlob(containerName, blobName);
-        if (blob==null) return null;
-        return blob.getMetadata().getLastModified();
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/brooklyn/policy/os/AdvertiseWinrmLoginPolicy.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/brooklyn/policy/os/AdvertiseWinrmLoginPolicy.java b/locations/jclouds/src/main/java/brooklyn/policy/os/AdvertiseWinrmLoginPolicy.java
deleted file mode 100644
index a08429d..0000000
--- a/locations/jclouds/src/main/java/brooklyn/policy/os/AdvertiseWinrmLoginPolicy.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.policy.os;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.api.sensor.SensorEvent;
-import org.apache.brooklyn.api.sensor.SensorEventListener;
-import org.apache.brooklyn.entity.core.AbstractEntity;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.WinRmMachineLocation;
-import org.apache.brooklyn.policy.core.AbstractPolicy;
-import org.apache.brooklyn.sensor.core.Sensors;
-
-import com.google.common.annotations.Beta;
-
-/**
- * When attached to an entity, this will monitor for when an {@link WinRmMachineLocation} is added to that entity
- * (e.g. when a VM has been provisioned for it).
- * 
- * The policy will then add a sensor that advertises the Administrator login details.
- * 
- * A preferred mechanism would be for an external key-management tool to provide access to the credentials.
- */
-@Beta
-public class AdvertiseWinrmLoginPolicy extends AbstractPolicy implements SensorEventListener<Location> {
-
-    // TODO Would like support user-creation over WinRM
-    
-    private static final Logger LOG = LoggerFactory.getLogger(AdvertiseWinrmLoginPolicy.class);
-
-    public static final AttributeSensor<String> VM_USER_CREDENTIALS = Sensors.newStringSensor(
-            "vm.user.credentials",
-            "The \"<user> : <password> @ <hostname>:<port>\"");
-
-    public void setEntity(EntityLocal entity) {
-        super.setEntity(entity);
-        subscribe(entity, AbstractEntity.LOCATION_ADDED, this);
-    }
-
-    @Override
-    public void onEvent(SensorEvent<Location> event) {
-        final Entity entity = event.getSource();
-        final Location loc = event.getValue();
-        if (loc instanceof WinRmMachineLocation) {
-            advertiseUserAsync(entity, (WinRmMachineLocation)loc);
-        }
-    }
-
-    protected void advertiseUserAsync(final Entity entity, final WinRmMachineLocation machine) {
-        String user = machine.getUser();
-        String hostname = machine.getHostname();
-        int port = machine.config().get(WinRmMachineLocation.WINRM_PORT);
-        String password = machine.config().get(WinRmMachineLocation.PASSWORD);
-        
-        String creds = user + " : " + password + " @ " +hostname + ":" + port;
-        
-        LOG.info("Advertising user "+user+" @ "+hostname+":"+port);
-        
-        ((EntityLocal)entity).setAttribute(VM_USER_CREDENTIALS, creds);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/brooklyn/policy/os/CreateUserPolicy.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/brooklyn/policy/os/CreateUserPolicy.java b/locations/jclouds/src/main/java/brooklyn/policy/os/CreateUserPolicy.java
deleted file mode 100644
index f47a318..0000000
--- a/locations/jclouds/src/main/java/brooklyn/policy/os/CreateUserPolicy.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.policy.os;
-
-import java.util.List;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.api.sensor.SensorEvent;
-import org.apache.brooklyn.api.sensor.SensorEventListener;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.entity.core.AbstractEntity;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.jclouds.compute.config.AdminAccessConfiguration;
-import org.jclouds.scriptbuilder.functions.InitAdminAccess;
-import org.jclouds.scriptbuilder.statements.login.AdminAccess;
-import org.jclouds.scriptbuilder.statements.ssh.SshdConfig;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import org.apache.brooklyn.policy.core.AbstractPolicy;
-import org.apache.brooklyn.sensor.core.Sensors;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.apache.brooklyn.util.core.internal.ssh.SshTool;
-import org.apache.brooklyn.util.text.Identifiers;
-
-import com.google.common.annotations.Beta;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-/**
- * When attached to an entity, this will monitor for when an {@link SshMachineLocation} is added to that entity
- * (e.g. when a VM has been provisioned for it).
- * 
- * The policy will then (asynchronously) add a new user to the VM, with a randomly generated password.
- * The ssh details will be set as a sensor on the entity.
- * 
- * If this is used, it is strongly encouraged to tell users to change the password on first login.
- * 
- * A preferred mechanism would be for an external key-management tool to generate ssh key-pairs for
- * the user, and for the public key to be passed to Brooklyn. However, there is not a customer 
- * requirement for that yet, so focusing on the password-approach.
- */
-@Beta
-public class CreateUserPolicy extends AbstractPolicy implements SensorEventListener<Location> {
-
-    // TODO Should add support for authorizing ssh keys as well
-    
-    // TODO Should review duplication with:
-    //  - JcloudsLocationConfig.GRANT_USER_SUDO
-    //    (but config default/description and context of use are different)
-    //  - AdminAccess in JcloudsLocation.createUserStatements
-    
-    // TODO Could make the password explicitly configurable, or auto-generate if not set?
-    
-    private static final Logger LOG = LoggerFactory.getLogger(CreateUserPolicy.class);
-
-    @SetFromFlag("user")
-    public static final ConfigKey<String> VM_USERNAME = ConfigKeys.newStringConfigKey("createuser.vm.user.name");
-
-    @SetFromFlag("grantSudo")
-    public static final ConfigKey<Boolean> GRANT_SUDO = ConfigKeys.newBooleanConfigKey(
-            "createuser.vm.user.grantSudo",
-            "Whether to give the new user sudo rights",
-            false);
-
-    public static final AttributeSensor<String> VM_USER_CREDENTIALS = Sensors.newStringSensor(
-            "createuser.vm.user.credentials",
-            "The \"<user> : <password> @ <hostname>:<port>\"");
-
-    public void setEntity(EntityLocal entity) {
-        super.setEntity(entity);
-        subscribe(entity, AbstractEntity.LOCATION_ADDED, this);
-    }
-
-    @Override
-    public void onEvent(SensorEvent<Location> event) {
-        final Entity entity = event.getSource();
-        final Location loc = event.getValue();
-        if (loc instanceof SshMachineLocation) {
-            addUserAsync(entity, (SshMachineLocation)loc);
-        }
-    }
-
-    protected void addUserAsync(final Entity entity, final SshMachineLocation machine) {
-        ((EntityInternal)entity).getExecutionContext().execute(new Runnable() {
-            public void run() {
-                addUser(entity, machine);
-            }});
-    }
-    
-    protected void addUser(Entity entity, SshMachineLocation machine) {
-        boolean grantSudo = getRequiredConfig(GRANT_SUDO);
-        String user = getRequiredConfig(VM_USERNAME);
-        String password = Identifiers.makeRandomId(12);
-        String hostname = machine.getAddress().getHostName();
-        int port = machine.getPort();
-        String creds = user + " : " + password + " @ " +hostname + ":" + port;
-        
-        LOG.info("Adding auto-generated user "+user+" @ "+hostname+":"+port);
-        
-        // Build the command to create the user
-        // Note AdminAccess requires _all_ fields set, due to http://code.google.com/p/jclouds/issues/detail?id=1095
-        // If jclouds grants Sudo rights, it overwrites the /etc/sudoers, which makes integration tests very dangerous! Not using it.
-        AdminAccess adminAccess = AdminAccess.builder()
-                .adminUsername(user)
-                .adminPassword(password)
-                .grantSudoToAdminUser(false)
-                .resetLoginPassword(true)
-                .loginPassword(password)
-                .authorizeAdminPublicKey(false)
-                .adminPublicKey("ignored")
-                .installAdminPrivateKey(false)
-                .adminPrivateKey("ignore")
-                .lockSsh(false)
-                .build();
-        
-        org.jclouds.scriptbuilder.domain.OsFamily scriptOsFamily = (machine.getMachineDetails().getOsDetails().isWindows()) 
-                ? org.jclouds.scriptbuilder.domain.OsFamily.WINDOWS
-                : org.jclouds.scriptbuilder.domain.OsFamily.UNIX;
-        
-        InitAdminAccess initAdminAccess = new InitAdminAccess(new AdminAccessConfiguration.Default());
-        initAdminAccess.visit(adminAccess);
-        String cmd = adminAccess.render(scriptOsFamily);
-
-        // Exec command to create the user
-        int result = machine.execScript(ImmutableMap.of(SshTool.PROP_RUN_AS_ROOT.getName(), true), "create-user-"+user, ImmutableList.of(cmd));
-        if (result != 0) {
-            throw new IllegalStateException("Failed to auto-generate user, using command "+cmd);
-        }
-
-        // Exec command to grant password-access to sshd (which may have been disabled earlier).
-        cmd = new SshdConfig(ImmutableMap.of("PasswordAuthentication", "yes")).render(scriptOsFamily);
-        result = machine.execScript(ImmutableMap.of(SshTool.PROP_RUN_AS_ROOT.getName(), true), "create-user-"+user, ImmutableList.of(cmd));
-        if (result != 0) {
-            throw new IllegalStateException("Failed to enable ssh-login-with-password, using command "+cmd);
-        }
-
-        // Exec command to grant sudo rights.
-        if (grantSudo) {
-            List<String> cmds = ImmutableList.of(
-                    "cat >> /etc/sudoers <<-'END_OF_JCLOUDS_FILE'\n"+
-                            user+" ALL = (ALL) NOPASSWD:ALL\n"+
-                            "END_OF_JCLOUDS_FILE\n",
-                    "chmod 0440 /etc/sudoers");
-            result = machine.execScript(ImmutableMap.of(SshTool.PROP_RUN_AS_ROOT.getName(), true), "add-user-to-sudoers-"+user, cmds);
-            if (result != 0) {
-                throw new IllegalStateException("Failed to auto-generate user, using command "+cmd);
-            }
-        }
-        
-        ((EntityLocal)entity).setAttribute(VM_USER_CREDENTIALS, creds);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsBlobStoreBasedObjectStore.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsBlobStoreBasedObjectStore.java b/locations/jclouds/src/main/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsBlobStoreBasedObjectStore.java
new file mode 100644
index 0000000..182e8cd
--- /dev/null
+++ b/locations/jclouds/src/main/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsBlobStoreBasedObjectStore.java
@@ -0,0 +1,237 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist.jclouds;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
+import org.apache.brooklyn.core.server.BrooklynServerConfig;
+import org.jclouds.blobstore.BlobStoreContext;
+import org.jclouds.blobstore.domain.StorageMetadata;
+import org.jclouds.blobstore.options.ListContainerOptions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.location.cloud.CloudLocationConfig;
+import org.apache.brooklyn.location.core.LocationConfigKeys;
+import org.apache.brooklyn.location.jclouds.JcloudsLocation;
+import org.apache.brooklyn.location.jclouds.JcloudsUtil;
+import org.apache.brooklyn.util.exceptions.FatalConfigurationRuntimeException;
+import org.apache.brooklyn.util.text.Strings;
+
+import com.google.common.base.Function;
+import com.google.common.base.Objects;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.FluentIterable;
+
+/**
+ * @author Andrea Turli
+ */
+public class JcloudsBlobStoreBasedObjectStore implements PersistenceObjectStore {
+
+    private static final Logger log = LoggerFactory.getLogger(JcloudsBlobStoreBasedObjectStore.class);
+
+    private final String containerNameFirstPart;
+    private final String containerSubPath;
+    
+    private String locationSpec;
+    private JcloudsLocation location;
+    private BlobStoreContext context;
+
+    private ManagementContext mgmt;
+
+    public JcloudsBlobStoreBasedObjectStore(String locationSpec, String containerName) {
+        this.locationSpec = locationSpec;
+        String[] segments = splitOnce(containerName);
+        this.containerNameFirstPart = segments[0];
+        this.containerSubPath = segments[1];
+    }
+    
+    private String[] splitOnce(String path) {
+        String separator = subPathSeparator();
+        int index = path.indexOf(separator);
+        if (index<0) return new String[] { path, "" };
+        return new String[] { path.substring(0, index), path.substring(index+separator.length()) };
+    }
+
+    public JcloudsBlobStoreBasedObjectStore(JcloudsLocation location, String containerName) {
+        this.location = location;
+        String[] segments = splitOnce(containerName);
+        this.containerNameFirstPart = segments[0];
+        this.containerSubPath = segments[1];
+        getBlobStoreContext();
+    }
+
+    public String getSummaryName() {
+        return (locationSpec!=null ? locationSpec : location)+":"+getContainerNameFull();
+    }
+    
+    public synchronized BlobStoreContext getBlobStoreContext() {
+        if (context==null) {
+            if (location==null) {
+                Preconditions.checkNotNull(locationSpec, "locationSpec required for remote object store when location is null");
+                Preconditions.checkNotNull(mgmt, "mgmt not injected / object store not prepared");
+                location = (JcloudsLocation) mgmt.getLocationRegistry().resolve(locationSpec);
+            }
+            
+            String identity = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_IDENTITY), "identity must not be null");
+            String credential = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_CREDENTIAL), "credential must not be null");
+            String provider = checkNotNull(location.getConfig(LocationConfigKeys.CLOUD_PROVIDER), "provider must not be null");
+            String endpoint = location.getConfig(CloudLocationConfig.CLOUD_ENDPOINT);
+
+            context = JcloudsUtil.newBlobstoreContext(provider, endpoint, identity, credential);
+     
+            // TODO do we need to get location from region? can't see the jclouds API.
+            // doesn't matter in some places because it's already in the endpoint
+//            String region = location.getConfig(CloudLocationConfig.CLOUD_REGION_ID);
+            context.getBlobStore().createContainerInLocation(null, getContainerNameFirstPart());
+        }
+        return context;
+    }
+
+    @Override
+    public void prepareForMasterUse() {
+        // backups not supported here, that is all which is needed for master use
+        // that's now normally done *prior* to calling in to here for writes
+        // (and we have already thrown in prepareForSharedUse if legacy backups have been specified as required)
+    }
+    
+    public String getContainerName() {
+        return getContainerNameFull();
+    }
+    
+    protected String getContainerNameFull() {
+        return mergePaths(containerNameFirstPart, containerSubPath);
+    }
+
+    protected String getContainerNameFirstPart() {
+        return containerNameFirstPart;
+    }
+    
+    protected String getItemInContainerSubPath(String path) {
+        if (Strings.isBlank(containerSubPath)) return path;
+        return mergePaths(containerSubPath, path);
+    }
+
+    @Override
+    public void createSubPath(String subPath) {
+        // not needed - subpaths are created on demant
+        // (and buggy on softlayer w swift w jclouds 1.7.2:
+        // throws a "not found" if we're creating an empty directory from scratch)
+//        context.getBlobStore().createDirectory(getContainerName(), subPath);
+    }
+
+    protected void checkPrepared() {
+        if (context==null)
+            throw new IllegalStateException("object store not prepared");
+    }
+    
+    @Override
+    public StoreObjectAccessor newAccessor(String path) {
+        checkPrepared();
+        return new JcloudsStoreObjectAccessor(context.getBlobStore(), getContainerNameFirstPart(), getItemInContainerSubPath(path));
+    }
+
+    protected String mergePaths(String basePath, String ...subPaths) {
+        StringBuilder result = new StringBuilder(basePath);
+        for (String subPath: subPaths) {
+            if (result.length()>0 && subPath.length()>0) {
+                result.append(subPathSeparator());
+                result.append(subPath);
+            }
+        }
+        return result.toString();
+    }
+    
+    protected String subPathSeparator() {
+        // in case some object stores don't allow / for paths
+        return "/";
+    }
+
+    @Override
+    public List<String> listContentsWithSubPath(final String parentSubPath) {
+        checkPrepared();
+        return FluentIterable.from(context.getBlobStore().list(getContainerNameFirstPart(), 
+            ListContainerOptions.Builder.inDirectory(getItemInContainerSubPath(parentSubPath))))
+                .transform(new Function<StorageMetadata, String>() {
+                    @Override
+                    public String apply(@javax.annotation.Nullable StorageMetadata input) {
+                        String result = input.getName();
+                        result = Strings.removeFromStart(result, containerSubPath);
+                        result = Strings.removeFromStart(result, "/");
+                        return result;
+                    }
+                }).toList();
+    }
+
+    @Override
+    public void close() {
+        if (context!=null)
+            context.close();
+    }
+
+    @Override
+    public String toString() {
+        return Objects.toStringHelper(this)
+                .add("blobStoreContext", context)
+                .add("basedir", containerNameFirstPart)
+                .toString();
+    }
+    
+    @Override
+    public void injectManagementContext(ManagementContext mgmt) {
+        if (this.mgmt!=null && !this.mgmt.equals(mgmt))
+            throw new IllegalStateException("Cannot change mgmt context of "+this);
+        this.mgmt = mgmt;
+    }
+    
+    @SuppressWarnings("deprecation")
+    @Override
+    public void prepareForSharedUse(@Nullable PersistMode persistMode, HighAvailabilityMode haMode) {
+        if (mgmt==null) throw new NullPointerException("Must inject ManagementContext before preparing "+this);
+        
+        getBlobStoreContext();
+        
+        if (persistMode==null || persistMode==PersistMode.DISABLED) {
+            log.warn("Should not be using "+this+" when persistMode is "+persistMode);
+            return;
+        }
+        
+        Boolean backups = mgmt.getConfig().getConfig(BrooklynServerConfig.PERSISTENCE_BACKUPS_REQUIRED);
+        if (Boolean.TRUE.equals(backups)) {
+            log.warn("Using legacy backup for "+this+"; functionality will be removed in future versions, in favor of promotion/demotion-specific backups to a configurable backup location.");
+            throw new FatalConfigurationRuntimeException("Backups not supported for object store ("+this+")");
+        }
+    }
+
+    @Override
+    public void deleteCompletely() {
+        if (Strings.isBlank(containerSubPath))
+            getBlobStoreContext().getBlobStore().deleteContainer(containerNameFirstPart);
+        else
+            newAccessor(containerSubPath).delete();
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/locations/jclouds/src/main/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsStoreObjectAccessor.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsStoreObjectAccessor.java b/locations/jclouds/src/main/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsStoreObjectAccessor.java
new file mode 100644
index 0000000..be6a56e
--- /dev/null
+++ b/locations/jclouds/src/main/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsStoreObjectAccessor.java
@@ -0,0 +1,127 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.mgmt.persist.jclouds;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Date;
+
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.commons.io.Charsets;
+import org.jclouds.blobstore.BlobStore;
+import org.jclouds.blobstore.domain.Blob;
+import org.jclouds.util.Strings2;
+
+import com.google.common.base.Throwables;
+import com.google.common.io.ByteSource;
+import com.google.common.io.ByteStreams;
+
+/**
+ * @author Andrea Turli
+ */
+public class JcloudsStoreObjectAccessor implements PersistenceObjectStore.StoreObjectAccessor {
+
+    private final BlobStore blobStore;
+    private final String containerName;
+    private final String blobName;
+
+    public JcloudsStoreObjectAccessor(BlobStore blobStore, String containerName, String blobNameOptionallyWithPath) {
+        this.blobStore = blobStore;
+        this.containerName = containerName;
+        this.blobName = blobNameOptionallyWithPath;
+    }
+
+    @Override
+    public boolean exists() {
+        return blobStore.blobExists(containerName, blobName);
+    }
+
+    @Override
+    public void put(String val) {
+        if (val==null) val = "";
+        
+        blobStore.createContainerInLocation(null, containerName);
+        // seems not needed, at least not w SoftLayer
+//        blobStore.createDirectory(containerName, directoryName);
+        ByteSource payload = ByteSource.wrap(val.getBytes(Charsets.UTF_8));
+        Blob blob;
+        try {
+            blob = blobStore.blobBuilder(blobName).payload(payload)
+                    .contentLength(payload.size())
+                    .build();
+        } catch (IOException e) {
+            throw Throwables.propagate(e);
+        }
+        blobStore.putBlob(containerName, blob);
+    }
+
+    @Override
+    public void append(String val) {
+        String val0 = get();
+        if (val0==null) val0="";
+        if (val==null) val="";
+        put(val0+val);
+    }
+
+    @Override
+    public void delete() {
+        blobStore.removeBlob(containerName, blobName);
+    }
+
+    @Override
+    public String get() {
+        try {
+            Blob blob = blobStore.getBlob(containerName, blobName);
+            if (blob==null) return null;
+            return Strings2.toStringAndClose(blob.getPayload().openStream());
+        } catch (IOException e) {
+            Exceptions.propagateIfFatal(e);
+            throw new IllegalStateException("Error reading blobstore "+containerName+" "+blobName+": "+e, e);
+        }
+    }
+
+    @Override
+    public byte[] getBytes() {
+        try {
+            Blob blob = blobStore.getBlob(containerName, blobName);
+            if (blob==null) return null;
+            ByteArrayOutputStream out = new ByteArrayOutputStream();
+            InputStream in = blob.getPayload().openStream();
+            try {
+                ByteStreams.copy(in, out);
+                return out.toByteArray();
+            } finally {
+                out.close();
+            }
+        } catch (IOException e) {
+            Exceptions.propagateIfFatal(e);
+            throw new IllegalStateException("Error reading blobstore "+containerName+" "+blobName+": "+e, e);
+        }
+    }
+
+    @Override
+    public Date getLastModifiedDate() {
+        Blob blob = blobStore.getBlob(containerName, blobName);
+        if (blob==null) return null;
+        return blob.getMetadata().getLastModified();
+    }
+    
+}



[05/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeedTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeedTest.java b/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeedTest.java
new file mode 100644
index 0000000..124e00a
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/JmxFeedTest.java
@@ -0,0 +1,422 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.feed.jmx;
+
+import static org.apache.brooklyn.test.TestUtils.executeUntilSucceeds;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import javax.management.MBeanOperationInfo;
+import javax.management.MBeanParameterInfo;
+import javax.management.Notification;
+import javax.management.NotificationListener;
+import javax.management.ObjectName;
+import javax.management.StandardEmitterMBean;
+import javax.management.openmbean.CompositeDataSupport;
+import javax.management.openmbean.CompositeType;
+import javax.management.openmbean.OpenType;
+import javax.management.openmbean.SimpleType;
+import javax.management.openmbean.TabularDataSupport;
+import javax.management.openmbean.TabularType;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.api.sensor.SensorEvent;
+import org.apache.brooklyn.api.sensor.SensorEventListener;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.core.test.entity.TestApplicationImpl;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.core.test.entity.TestEntityImpl;
+import org.apache.brooklyn.entity.core.AbstractEntity;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.JmxSupport;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.entity.java.UsesJmx.JmxAgentModes;
+import org.apache.brooklyn.entity.software.base.test.jmx.GeneralisedDynamicMBean;
+import org.apache.brooklyn.entity.software.base.test.jmx.JmxService;
+import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
+import org.apache.brooklyn.sensor.core.BasicNotificationSensor;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
+import org.apache.brooklyn.sensor.feed.jmx.JmxAttributePollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
+import org.apache.brooklyn.sensor.feed.jmx.JmxHelper;
+import org.apache.brooklyn.sensor.feed.jmx.JmxNotificationFilters;
+import org.apache.brooklyn.sensor.feed.jmx.JmxNotificationSubscriptionConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxOperationPollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxValueFunctions;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.test.TestUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.testng.collections.Lists;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.basic.PortRanges;
+import org.apache.brooklyn.location.basic.SimulatedLocation;
+
+import com.google.common.base.Function;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+/**
+ * Test the operation of the {@link JmxFeed} class.
+ * <p>
+ * Also confirm some of the JMX setup done by {@link JmxSupport} and {@link JmxHelper},
+ * based on ports in {@link UsesJmx}.
+ * <p>
+ * TODO tests of other JMX_AGENT_MODE are done in ActiveMqIntegrationTest; 
+ * would be nice to promote some to live here
+ */
+public class JmxFeedTest {
+    
+    // FIXME Move out the JmxHelper tests into the JmxHelperTest class
+    
+    // FIXME Also test that setting poll period takes effect
+    
+    private static final Logger log = LoggerFactory.getLogger(JmxFeedTest.class);
+
+    private static final int TIMEOUT_MS = 5000;
+    private static final int SHORT_WAIT_MS = 250;
+    
+    private JmxService jmxService;
+    private TestApplication app;
+    private TestEntity entity;
+    private JmxFeed feed;
+    private JmxHelper jmxHelper;
+    
+    private AttributeSensor<Integer> intAttribute = Sensors.newIntegerSensor("brooklyn.test.intAttribute", "Brooklyn testing int attribute");
+    private AttributeSensor<String> stringAttribute = Sensors.newStringSensor("brooklyn.test.stringAttribute", "Brooklyn testing string attribute");
+    private BasicAttributeSensor<Map> mapAttribute = new BasicAttributeSensor<Map>(Map.class, "brooklyn.test.mapAttribute", "Brooklyn testing map attribute");
+    private String objectName = "Brooklyn:type=MyTestMBean,name=myname";
+    private ObjectName jmxObjectName;
+    private String attributeName = "myattrib";
+    private String opName = "myop";
+    
+    public static class TestEntityWithJmx extends TestEntityImpl {
+        @Override public void init() {
+            setAttribute(Attributes.HOSTNAME, "localhost");
+            setAttribute(UsesJmx.JMX_PORT, 
+                    LocalhostMachineProvisioningLocation.obtainPort(PortRanges.fromString("40123+")));
+            // only supports no-agent, at the moment
+            setConfig(UsesJmx.JMX_AGENT_MODE, JmxAgentModes.NONE);
+            setAttribute(UsesJmx.RMI_REGISTRY_PORT, -1);  // -1 means to use the JMX_PORT only
+            ConfigToAttributes.apply(this, UsesJmx.JMX_CONTEXT);
+        }
+    }
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        jmxObjectName = new ObjectName(objectName);
+        
+        // Create an entity and configure it with the above JMX service
+        app = TestApplication.Factory.newManagedInstanceForTests();
+        entity = app.createAndManageChild(EntitySpec.create(TestEntity.class).impl(TestEntityWithJmx.class));
+        app.start(ImmutableList.of(new SimulatedLocation()));
+
+        jmxHelper = new JmxHelper(entity);
+        
+        jmxService = new JmxService(entity);
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (feed != null) feed.stop();
+        if (jmxHelper != null) jmxHelper.disconnect();
+        if (jmxService != null) jmxService.shutdown();
+        if (app != null) Entities.destroyAll(app.getManagementContext());
+        feed = null;
+    }
+
+    @Test
+    public void testJmxAttributePollerReturnsMBeanAttribute() throws Exception {
+        GeneralisedDynamicMBean mbean = jmxService.registerMBean(ImmutableMap.of(attributeName, 42), objectName);
+
+        feed = JmxFeed.builder()
+                .entity(entity)
+                .pollAttribute(new JmxAttributePollConfig<Integer>(intAttribute)
+                        .objectName(objectName)
+                        .period(50)
+                        .attributeName(attributeName))
+                .build();
+        
+        // Starts with value defined when registering...
+        assertSensorEventually(intAttribute, 42, TIMEOUT_MS);
+
+        // Change the value and check it updates
+        mbean.updateAttributeValue(attributeName, 64);
+        assertSensorEventually(intAttribute, 64, TIMEOUT_MS);
+    }
+
+    @Test
+    public void testJmxAttributeOfTypeTabularDataProviderConvertedToMap() throws Exception {
+        // Create the CompositeType and TabularData
+        CompositeType compositeType = new CompositeType(
+                "typeName",
+                "description",
+                new String[] {"myint", "mystring", "mybool"},    // item names
+                new String[] {"myint", "mystring", "mybool"},    // item descriptions, can't be null or empty string
+                new OpenType<?>[] {SimpleType.INTEGER, SimpleType.STRING, SimpleType.BOOLEAN}
+        );
+        TabularType tt = new TabularType(
+                "typeName",
+                "description",
+                compositeType,
+                new String[] {"myint"}
+        );
+        TabularDataSupport tds = new TabularDataSupport(tt);
+        tds.put(new CompositeDataSupport(
+                compositeType,
+                new String[] {"mybool", "myint", "mystring"},
+                new Object[] {true, 1234, "on"}
+        ));
+
+        // Create MBean
+        GeneralisedDynamicMBean mbean = jmxService.registerMBean(ImmutableMap.of(attributeName, tds), objectName);
+
+        feed = JmxFeed.builder()
+                .entity(entity)
+                .pollAttribute(new JmxAttributePollConfig<Map>(mapAttribute)
+                        .objectName(objectName)
+                        .attributeName(attributeName)
+                        .onSuccess((Function)JmxValueFunctions.tabularDataToMap()))
+                .build();
+
+        // Starts with value defined when registering...
+        assertSensorEventually(
+                mapAttribute, 
+                ImmutableMap.of("myint", 1234, "mystring", "on", "mybool", Boolean.TRUE), 
+                TIMEOUT_MS);
+    }
+
+    @Test
+    public void testJmxOperationPolledForSensor() throws Exception {
+        // This is awful syntax...
+        final int opReturnVal = 123;
+        final AtomicInteger invocationCount = new AtomicInteger();
+        MBeanOperationInfo opInfo = new MBeanOperationInfo(opName, "my descr", new MBeanParameterInfo[0], Integer.class.getName(), MBeanOperationInfo.ACTION);
+        GeneralisedDynamicMBean mbean = jmxService.registerMBean(
+                Collections.emptyMap(), 
+                ImmutableMap.of(opInfo, new Function<Object[], Integer>() {
+                        public Integer apply(Object[] args) {
+                            invocationCount.incrementAndGet(); return opReturnVal;
+                        }}),
+                objectName);
+
+        feed = JmxFeed.builder()
+                .entity(entity)
+                .pollOperation(new JmxOperationPollConfig<Integer>(intAttribute)
+                        .objectName(objectName)
+                        .operationName(opName))
+                .build();
+        
+        TestUtils.executeUntilSucceeds(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
+            public void run() {
+                assertTrue(invocationCount.get() > 0, "invocationCount="+invocationCount);
+                assertEquals(entity.getAttribute(intAttribute), (Integer)opReturnVal);
+            }});
+    }
+
+    @Test
+    public void testJmxOperationWithArgPolledForSensor() throws Exception {
+        // This is awful syntax...
+        MBeanParameterInfo paramInfo = new MBeanParameterInfo("param1", String.class.getName(), "my param1");
+        MBeanParameterInfo[] paramInfos = new MBeanParameterInfo[] {paramInfo};
+        MBeanOperationInfo opInfo = new MBeanOperationInfo(opName, "my descr", paramInfos, String.class.getName(), MBeanOperationInfo.ACTION);
+        GeneralisedDynamicMBean mbean = jmxService.registerMBean(
+                Collections.emptyMap(), 
+                ImmutableMap.of(opInfo, new Function<Object[], String>() {
+                        public String apply(Object[] args) {
+                            return args[0]+"suffix";
+                        }}),
+                objectName);
+        
+        feed = JmxFeed.builder()
+                .entity(entity)
+                .pollOperation(new JmxOperationPollConfig<String>(stringAttribute)
+                        .objectName(objectName)
+                        .operationName(opName)
+                        .operationParams(ImmutableList.of("myprefix")))
+                .build();
+        
+        assertSensorEventually(stringAttribute, "myprefix"+"suffix", TIMEOUT_MS);
+    }
+
+    @Test
+    public void testJmxNotificationSubscriptionForSensor() throws Exception {
+        final String one = "notification.one", two = "notification.two";
+        final StandardEmitterMBean mbean = jmxService.registerMBean(ImmutableList.of(one, two), objectName);
+        final AtomicInteger sequence = new AtomicInteger(0);
+
+        feed = JmxFeed.builder()
+                .entity(entity)
+                .subscribeToNotification(new JmxNotificationSubscriptionConfig<Integer>(intAttribute)
+                        .objectName(objectName)
+                        .notificationFilter(JmxNotificationFilters.matchesType(one)))
+                .build();        
+
+        // Notification updates the sensor
+        // Note that subscription is done async, so can't just send notification immediately during test.
+        Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
+            public void run() {
+                sendNotification(mbean, one, sequence.getAndIncrement(), 123);
+                assertEquals(entity.getAttribute(intAttribute), (Integer)123);
+            }});
+        
+        // But other notification types are ignored
+        sendNotification(mbean, two, sequence.getAndIncrement(), -1);
+            
+        Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
+            public void run() {
+                assertEquals(entity.getAttribute(intAttribute), (Integer)123);
+            }});
+    }
+    
+    @Test
+    public void testJmxNotificationSubscriptionForSensorParsingNotification() throws Exception {
+        final String one = "notification.one", two = "notification.two";
+        final StandardEmitterMBean mbean = jmxService.registerMBean(ImmutableList.of(one, two), objectName);
+        final AtomicInteger sequence = new AtomicInteger(0);
+        
+        feed = JmxFeed.builder()
+                .entity(entity)
+                .subscribeToNotification(new JmxNotificationSubscriptionConfig<Integer>(intAttribute)
+                        .objectName(objectName)
+                        .notificationFilter(JmxNotificationFilters.matchesType(one))
+                        .onNotification(new Function<Notification, Integer>() {
+                            public Integer apply(Notification notif) {
+                                return (Integer) notif.getUserData();
+                            }
+                        }))
+                .build();
+        
+        
+        // Notification updates the sensor
+        // Note that subscription is done async, so can't just send notification immediately during test.
+        Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
+            public void run() {
+                sendNotification(mbean, one, sequence.getAndIncrement(), 123);
+                assertEquals(entity.getAttribute(intAttribute), (Integer)123);
+            }});
+    }
+
+    @Test
+    public void testJmxNotificationMultipleSubscriptionUsingListener() throws Exception {
+        final String one = "notification.one";
+        final String two = "notification.two";
+        final StandardEmitterMBean mbean = jmxService.registerMBean(ImmutableList.of(one, two), objectName);
+        final AtomicInteger sequence = new AtomicInteger(0);
+
+        feed = JmxFeed.builder()
+                .entity(entity)
+                .subscribeToNotification(new JmxNotificationSubscriptionConfig<Integer>(intAttribute)
+                        .objectName(objectName)
+                        .notificationFilter(JmxNotificationFilters.matchesTypes(one, two)))
+                .build();
+        
+        // Notification updates the sensor
+        // Note that subscription is done async, so can't just send notification immediately during test.
+        Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
+            public void run() {
+                sendNotification(mbean, one, sequence.getAndIncrement(), 123);
+                assertEquals(entity.getAttribute(intAttribute), (Integer)123);
+            }});
+
+        // And wildcard means other notifications also received
+        sendNotification(mbean, two, sequence.getAndIncrement(), 456);
+        assertSensorEventually(intAttribute, 456, TIMEOUT_MS);
+    }
+
+    // Test reproduces functionality used in Monterey, for Venue entity being told of requestActor
+    @Test
+    public void testSubscribeToJmxNotificationAndEmitCorrespondingNotificationSensor() throws Exception {
+        TestApplication app2 = new TestApplicationImpl();
+        final EntityWithEmitter entity = new EntityWithEmitter(app2);
+        Entities.startManagement(app2);
+        try {
+            app2.start(ImmutableList.of(new SimulatedLocation()));
+            
+            final List<SensorEvent<String>> received = Lists.newArrayList();
+            app2.subscribe(null, EntityWithEmitter.MY_NOTIF, new SensorEventListener<String>() {
+                public void onEvent(SensorEvent<String> event) {
+                    received.add(event);
+                }});
+    
+            final StandardEmitterMBean mbean = jmxService.registerMBean(ImmutableList.of("one"), objectName);
+            final AtomicInteger sequence = new AtomicInteger(0);
+            
+            jmxHelper.connect(TIMEOUT_MS);
+            jmxHelper.addNotificationListener(jmxObjectName, new NotificationListener() {
+                    public void handleNotification(Notification notif, Object callback) {
+                        if (notif.getType().equals("one")) {
+                            entity.emit(EntityWithEmitter.MY_NOTIF, (String) notif.getUserData());
+                        }
+                    }});
+            
+
+            Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
+                public void run() {
+                    sendNotification(mbean, "one", sequence.getAndIncrement(), "abc");
+                    assertTrue(received.size() > 0, "received size should be bigger than 0");
+                    assertEquals(received.get(0).getValue(), "abc");
+                }});
+        } finally {
+            Entities.destroyAll(app2.getManagementContext());
+        }
+    }
+    
+    public static class EntityWithEmitter extends AbstractEntity {
+        public static final BasicNotificationSensor<String> MY_NOTIF = new BasicNotificationSensor<String>(String.class, "test.myNotif", "My notif");
+        
+        public EntityWithEmitter(Entity owner) {
+            super(owner);
+        }
+        public EntityWithEmitter(Map flags) {
+            super(flags);
+        }
+        public EntityWithEmitter(Map flags, Entity owner) {
+            super(flags, owner);
+        }
+    }
+    
+    private Notification sendNotification(StandardEmitterMBean mbean, String type, long seq, Object userData) {
+        Notification notif = new Notification(type, mbean, seq);
+        notif.setUserData(userData);
+        mbean.sendNotification(notif);
+        return notif;
+    }
+    
+    private <T> void assertSensorEventually(final AttributeSensor<T> sensor, final T expectedVal, long timeout) {
+        executeUntilSucceeds(ImmutableMap.of("timeout", timeout), new Callable<Void>() {
+            public Void call() {
+                assertEquals(entity.getAttribute(sensor), expectedVal);
+                return null;
+            }});
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/JmxHelperTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/JmxHelperTest.java b/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/JmxHelperTest.java
new file mode 100644
index 0000000..058947c
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/JmxHelperTest.java
@@ -0,0 +1,311 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.feed.jmx;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.fail;
+
+import java.io.IOException;
+import java.util.List;
+
+import javax.management.DynamicMBean;
+import javax.management.MBeanOperationInfo;
+import javax.management.MBeanParameterInfo;
+import javax.management.Notification;
+import javax.management.NotificationListener;
+import javax.management.ObjectName;
+import javax.management.StandardEmitterMBean;
+
+import org.apache.brooklyn.entity.software.base.test.jmx.GeneralisedDynamicMBean;
+import org.apache.brooklyn.entity.software.base.test.jmx.JmxService;
+import org.apache.brooklyn.sensor.feed.jmx.JmxHelper;
+import org.apache.brooklyn.test.TestUtils;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.jclouds.util.Throwables2;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.testng.collections.Lists;
+
+import com.google.common.base.Function;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+public class JmxHelperTest {
+
+    private static final Logger log = LoggerFactory.getLogger(JmxHelperTest.class);
+    
+    private static final String LOCALHOST_NAME = "localhost";
+    
+    private static final int TIMEOUT_MS = 5000;
+    private static final int SHORT_WAIT_MS = 250;
+
+    private JmxService jmxService;
+    private JmxHelper jmxHelper;
+    
+    private String objectName = "Brooklyn:type=MyTestMBean,name=myname";
+    private String objectNameWithWildcard = "Brooklyn:type=MyTestMBean,name=mynam*";
+    private ObjectName jmxObjectName;
+    private ObjectName jmxObjectNameWithWildcard;
+    private String attributeName = "myattrib";
+    private String opName = "myop";
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        jmxObjectName = new ObjectName(objectName);
+        jmxObjectNameWithWildcard = new ObjectName(objectNameWithWildcard);
+        jmxService = newJmxServiceRetrying(LOCALHOST_NAME, 5);
+        jmxHelper = new JmxHelper(jmxService.getUrl());
+        jmxHelper.setMinTimeBetweenReconnectAttempts(0);
+        jmxHelper.connect(TIMEOUT_MS);
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (jmxHelper != null) jmxHelper.disconnect();
+        if (jmxService != null) jmxService.shutdown();
+        jmxHelper = null;
+        jmxService = null;
+    }
+
+    @Test
+    public void testGetAttribute() throws Exception {
+        GeneralisedDynamicMBean mbean = jmxService.registerMBean(MutableMap.of("myattr", "myval"), objectName);
+        assertEquals(jmxHelper.getAttribute(jmxObjectName, "myattr"), "myval");
+    }
+
+    @Test
+    public void testGetAttributeUsingObjectNameWildcard() throws Exception {
+        GeneralisedDynamicMBean mbean = jmxService.registerMBean(MutableMap.of("myattr", "myval"), objectName);
+        assertEquals(jmxHelper.getAttribute(jmxObjectNameWithWildcard, "myattr"), "myval");
+    }
+
+    @Test
+    public void testSetAttribute() throws Exception {
+        DynamicMBean mbean = jmxService.registerMBean(MutableMap.of("myattr", "myval"), objectName);
+
+        jmxHelper.setAttribute(jmxObjectName, "myattr", "abc");
+        Object actual = jmxHelper.getAttribute(jmxObjectName, "myattr");
+        assertEquals(actual, "abc");
+    }
+
+    @Test
+    public void testSetAttributeUsingObjectNameWildcard() throws Exception {
+        DynamicMBean mbean = jmxService.registerMBean(MutableMap.of("myattr", "myval"), objectName);
+
+        jmxHelper.setAttribute(jmxObjectNameWithWildcard, "myattr", "abc");
+        Object actual = jmxHelper.getAttribute(jmxObjectName, "myattr");
+        assertEquals(actual, "abc");
+    }
+
+    @Test
+    public void testInvokeOperationWithNoArgs() throws Exception {
+        final String opReturnVal = "my result";
+        MBeanOperationInfo opInfo = new MBeanOperationInfo(opName, "my descr", new MBeanParameterInfo[0], String.class.getName(), MBeanOperationInfo.ACTION);
+        Function<Object[], String> opImpl = new Function<Object[], String>() {
+            @Override public String apply(Object[] args) {
+                assertEquals(args.length, 0, "args="+args);
+                return opReturnVal;
+            }
+        };
+        GeneralisedDynamicMBean mbean = jmxService.registerMBean(ImmutableMap.of(), ImmutableMap.of(opInfo, opImpl), objectName);
+        
+        assertEquals(jmxHelper.operation(objectName, opName), opReturnVal);
+    }
+
+    @Test
+    public void testInvokeOperationUsingObjectNameWildcard() throws Exception {
+        final String opReturnVal = "my result";
+        MBeanOperationInfo opInfo = new MBeanOperationInfo(opName, "my descr", new MBeanParameterInfo[0], String.class.getName(), MBeanOperationInfo.ACTION);
+        Function<Object[], String> opImpl = new Function<Object[], String>() {
+            @Override public String apply(Object[] args) {
+                assertEquals(args.length, 0, "args="+args);
+                return opReturnVal;
+            }
+        };
+        GeneralisedDynamicMBean mbean = jmxService.registerMBean(ImmutableMap.of(), ImmutableMap.of(opInfo, opImpl), objectName);
+        
+        assertEquals(jmxHelper.operation(objectNameWithWildcard, opName), opReturnVal);
+    }
+
+    @Test
+    public void testInvokeOperationWithArgs() throws Exception {
+        final String opReturnPrefix = "my result prefix/";
+        String opParam1 = "my param 1";
+        MBeanOperationInfo opInfo = new MBeanOperationInfo(
+                opName, 
+                "my descr", 
+                new MBeanParameterInfo[] {new MBeanParameterInfo("myParam1", String.class.getName(), "my param1 descr")}, 
+                String.class.getName(), 
+                MBeanOperationInfo.ACTION);
+        Function<Object[],String> opImpl = new Function<Object[],String>() {
+            public String apply(Object[] input) {
+                return opReturnPrefix+input[0];
+            }
+        };
+        GeneralisedDynamicMBean mbean = jmxService.registerMBean(ImmutableMap.of(), ImmutableMap.of(opInfo, opImpl), objectName);
+        
+        assertEquals(jmxHelper.operation(objectName, opName, opParam1), opReturnPrefix+opParam1);
+    }
+
+    @Test
+    public void testReconnectsOnJmxServerTemporaryFailure() throws Exception {
+        int port = jmxService.getJmxPort();
+        GeneralisedDynamicMBean mbean = jmxService.registerMBean(MutableMap.of("myattr", "myval"), objectName);
+        assertEquals(jmxHelper.getAttribute(jmxObjectName, "myattr"), "myval");
+        
+        // Simulate temporary network-failure
+        jmxService.shutdown();
+
+        // Ensure that we have a failed query while the "network is down"         
+        try {
+            jmxHelper.getAttribute(jmxObjectName, attributeName);
+            fail();
+        } catch (Exception e) {
+            if (Throwables2.getFirstThrowableOfType(e, IOException.class) == null) {
+                throw e;
+            }
+        }
+
+        // Simulate the network restarting
+        jmxService = new JmxService(LOCALHOST_NAME, port);
+        
+        GeneralisedDynamicMBean mbean2 = jmxService.registerMBean(MutableMap.of("myattr", "myval2"), objectName);
+        assertEquals(jmxHelper.getAttribute(jmxObjectName, "myattr"), "myval2");
+    }
+    
+    @Test(expectedExceptions = {IllegalStateException.class})
+    public void testJmxCheckInstanceExistsEventuallyThrowsIfNotFound() throws Exception {
+        jmxHelper.assertMBeanExistsEventually(new ObjectName("Brooklyn:type=DoesNotExist,name=doesNotExist"), 1L);
+    }
+
+    @Test
+    public void testJmxObjectCheckExistsEventuallyReturnsIfFoundImmediately() throws Exception {
+        GeneralisedDynamicMBean mbean = jmxService.registerMBean(objectName);
+        jmxHelper.assertMBeanExistsEventually(jmxObjectName, 1L);
+    }
+
+    @Test
+    public void testJmxObjectCheckExistsEventuallyTakingLongReturnsIfFoundImmediately() throws Exception {
+        GeneralisedDynamicMBean mbean = jmxService.registerMBean(objectName);
+        jmxHelper.assertMBeanExistsEventually(jmxObjectName, 1L);
+    }
+
+    @Test
+    public void testJmxObjectCheckExistsEventuallyReturnsIfCreatedDuringPolling() throws Exception {
+        Thread t = new Thread(new Runnable() {
+                public void run() {
+                    try {
+                        Thread.sleep(SHORT_WAIT_MS);
+                        GeneralisedDynamicMBean mbean = jmxService.registerMBean(objectName);
+                    } catch (InterruptedException e) {
+                        return; // graceful return
+                    } catch (Exception e) {
+                        throw Exceptions.propagate(e);
+                    }
+                }});
+        try {
+            t.start();
+            
+            jmxHelper.assertMBeanExistsEventually(jmxObjectName, TIMEOUT_MS);
+        } finally {
+            t.interrupt();
+            t.join(TIMEOUT_MS);
+            assertFalse(t.isAlive());
+        }        
+    }
+
+    @Test
+    public void testSubscribeToJmxNotificationsDirectlyWithJmxHelper() throws Exception {
+        StandardEmitterMBean mbean = jmxService.registerMBean(ImmutableList.of("one"), objectName);
+        int sequence = 0;
+        final List<Notification> received = Lists.newArrayList();
+
+        jmxHelper.addNotificationListener(jmxObjectName, new NotificationListener() {
+            public void handleNotification(Notification notif, Object callback) {
+                received.add(notif);
+            }});
+                    
+
+        final Notification notif = sendNotification(mbean, "one", sequence++, "abc");
+
+        TestUtils.executeUntilSucceeds(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
+            public void run() {
+                assertEquals(received.size(), 1);
+                assertNotificationsEqual(received.get(0), notif);
+            }});
+    }
+
+    // Visual-inspection test that LOG.warn happens only once; TODO setup a listener to the logging output
+    @Test
+    public void testMBeanNotFoundLoggedOnlyOncePerUrl() throws Exception {
+        ObjectName wrongObjectName = new ObjectName("DoesNotExist:type=DoesNotExist");
+
+        // Expect just one log message about:
+        //     JMX object DoesNotExist:type=DoesNotExist not found at service:jmx:rmi://localhost:1099/jndi/rmi://localhost:9001/jmxrmi"
+        for (int i = 0; i < 10; i++) {
+            jmxHelper.findMBean(wrongObjectName);
+        }
+
+        jmxService.shutdown();
+        jmxHelper.disconnect();
+        
+        jmxService = newJmxServiceRetrying(LOCALHOST_NAME, 5);
+        jmxHelper = new JmxHelper(jmxService.getUrl());
+        jmxHelper.connect();
+        
+        // Expect just one log message about:
+        //     JMX object DoesNotExist:type=DoesNotExist not found at service:jmx:rmi://localhost:1099/jndi/rmi://localhost:9001/jmxrmi"
+        for (int i = 0; i < 10; i++) {
+            jmxHelper.findMBean(wrongObjectName);
+        }
+    }
+
+    private JmxService newJmxServiceRetrying(String host, int retries) throws Exception {
+        Exception lastexception = null;
+        for (int i = 0; i < retries; i++) {
+            try {
+                return new JmxService(host, (int)(11000+(500*Math.random())));
+            } catch (Exception e) {
+                log.debug("Unable to create JMX service during test - "+retries+" retries remaining");
+                lastexception = e;
+            }
+        }
+        throw lastexception;
+    }
+
+    private Notification sendNotification(StandardEmitterMBean mbean, String type, long seq, Object userData) {
+        Notification notif = new Notification(type, mbean, seq);
+        notif.setUserData(userData);
+        mbean.sendNotification(notif);
+        return notif;
+    }
+    
+    private void assertNotificationsEqual(Notification n1, Notification n2) {
+        assertEquals(n1.getType(), n2.getType());
+        assertEquals(n1.getSequenceNumber(), n2.getSequenceNumber());
+        assertEquals(n1.getUserData(), n2.getUserData());
+        assertEquals(n1.getTimeStamp(), n2.getTimeStamp());
+        assertEquals(n1.getMessage(), n2.getMessage());
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/RebindJmxFeedTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/RebindJmxFeedTest.java b/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/RebindJmxFeedTest.java
new file mode 100644
index 0000000..f4a72cd
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/sensor/feed/jmx/RebindJmxFeedTest.java
@@ -0,0 +1,148 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.feed.jmx;
+
+import static org.testng.Assert.assertEquals;
+
+import java.util.Collection;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.api.sensor.Feed;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestFixtureWithApp;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.core.test.entity.TestEntityImpl;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.entity.java.UsesJmx.JmxAgentModes;
+import org.apache.brooklyn.entity.software.base.test.jmx.GeneralisedDynamicMBean;
+import org.apache.brooklyn.entity.software.base.test.jmx.JmxService;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.sensor.feed.ConfigToAttributes;
+import org.apache.brooklyn.sensor.feed.jmx.JmxAttributePollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
+import org.apache.brooklyn.sensor.feed.jmx.JmxHelper;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.basic.PortRanges;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+
+public class RebindJmxFeedTest extends RebindTestFixtureWithApp {
+
+    private static final Logger log = LoggerFactory.getLogger(RebindJmxFeedTest.class);
+
+    private static final String LOCALHOST_NAME = "localhost";
+
+    static final AttributeSensor<String> SENSOR_STRING = Sensors.newStringSensor("aString", "");
+    static final AttributeSensor<Integer> SENSOR_INT = Sensors.newIntegerSensor( "aLong", "");
+
+    static final String JMX_ATTRIBUTE_NAME = "myattr";
+    static final String OBJECT_NAME = "Brooklyn:type=MyTestMBean,name=myname";
+    
+    private JmxService jmxService;
+    
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        
+        // Create an entity and configure it with the above JMX service
+        //jmxService = newJmxServiceRetrying(LOCALHOST_NAME, 5);
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    @Override
+    public void tearDown() throws Exception {
+        if (jmxService != null) jmxService.shutdown();
+        super.tearDown();
+    }
+
+    @Test
+    public void testJmxFeedIsPersisted() throws Exception {
+        runJmxFeedIsPersisted(false);
+    }
+
+    @Test
+    public void testJmxFeedIsPersistedWithPreCreatedJmxHelper() throws Exception {
+        runJmxFeedIsPersisted(true);
+    }
+
+    protected void runJmxFeedIsPersisted(boolean preCreateJmxHelper) throws Exception {
+        TestEntity origEntity = origApp.createAndManageChild(EntitySpec.create(TestEntity.class).impl(MyEntityWithJmxFeedImpl.class)
+                .configure(MyEntityWithJmxFeedImpl.PRE_CREATE_JMX_HELPER, preCreateJmxHelper));
+        origApp.start(ImmutableList.<Location>of());
+        
+        jmxService = new JmxService(origEntity);
+        GeneralisedDynamicMBean mbean = jmxService.registerMBean(MutableMap.of(JMX_ATTRIBUTE_NAME, "myval"), OBJECT_NAME);
+        
+        EntityTestUtils.assertAttributeEqualsEventually(origEntity, SENSOR_STRING, "myval");
+        assertEquals(origEntity.feeds().getFeeds().size(), 1);
+
+        newApp = rebind();
+        TestEntity newEntity = (TestEntity) Iterables.getOnlyElement(newApp.getChildren());
+        
+        Collection<Feed> newFeeds = newEntity.feeds().getFeeds();
+        assertEquals(newFeeds.size(), 1);
+        
+        // Expect the feed to still be polling
+        newEntity.setAttribute(SENSOR_STRING, null);
+        EntityTestUtils.assertAttributeEqualsEventually(newEntity, SENSOR_STRING, "myval");
+    }
+
+    public static class MyEntityWithJmxFeedImpl extends TestEntityImpl {
+        public static final ConfigKey<Boolean> PRE_CREATE_JMX_HELPER = ConfigKeys.newBooleanConfigKey("test.rebindjmx.preCreateJmxHelper", "", false);
+        
+        @Override
+        public void start(Collection<? extends Location> locs) {
+            // TODO Auto-generated method stub
+            super.start(locs);
+            
+            setAttribute(Attributes.HOSTNAME, "localhost");
+            setAttribute(UsesJmx.JMX_PORT, 
+                    LocalhostMachineProvisioningLocation.obtainPort(PortRanges.fromString("40123+")));
+            // only supports no-agent, at the moment
+            setConfig(UsesJmx.JMX_AGENT_MODE, JmxAgentModes.NONE);
+            setAttribute(UsesJmx.RMI_REGISTRY_PORT, -1);  // -1 means to use the JMX_PORT only
+            ConfigToAttributes.apply(this, UsesJmx.JMX_CONTEXT);
+            
+            JmxFeed.Builder feedBuilder = JmxFeed.builder()
+                    .entity(this)
+                    .pollAttribute(new JmxAttributePollConfig<String>(SENSOR_STRING)
+                            .objectName(OBJECT_NAME)
+                            .period(50)
+                            .attributeName(JMX_ATTRIBUTE_NAME));
+            if (getConfig(PRE_CREATE_JMX_HELPER)) {
+                JmxHelper jmxHelper = new JmxHelper(this);
+                feedBuilder.helper(jmxHelper);
+            }
+            addFeed(feedBuilder.build());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasksTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasksTest.java b/software/base/src/test/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasksTest.java
new file mode 100644
index 0000000..073a8df
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/sensor/ssh/SshEffectorTasksTest.java
@@ -0,0 +1,264 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.ssh;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Arrays;
+
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.TaskAdaptable;
+import org.apache.brooklyn.api.mgmt.TaskFactory;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
+import org.apache.brooklyn.util.core.task.ssh.SshFetchTaskWrapper;
+import org.apache.brooklyn.util.core.task.ssh.SshPutTaskWrapper;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.apache.brooklyn.util.exceptions.PropagatedRuntimeException;
+import org.apache.brooklyn.util.net.Urls;
+import org.apache.commons.io.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+import com.google.common.io.Files;
+
+public class SshEffectorTasksTest {
+
+    private static final Logger log = LoggerFactory.getLogger(SshEffectorTasksTest.class);
+    
+    TestApplication app;
+    ManagementContext mgmt;
+    SshMachineLocation host;
+    File tempDir;
+    
+    boolean failureExpected;
+
+    @BeforeMethod(alwaysRun=true)
+    public void setup() throws Exception {
+        app = TestApplication.Factory.newManagedInstanceForTests();
+        mgmt = app.getManagementContext();
+        
+        LocalhostMachineProvisioningLocation lhc = mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class));
+        host = lhc.obtain();
+        app.start(Arrays.asList(host));
+        clearExpectedFailure();
+        tempDir = Files.createTempDir();
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (mgmt != null) Entities.destroyAll(mgmt);
+        mgmt = null;
+        FileUtils.deleteDirectory(tempDir);
+        checkExpectedFailure();
+    }
+
+    protected void checkExpectedFailure() {
+        if (failureExpected) {
+            clearExpectedFailure();
+            Assert.fail("Test should have thrown an exception but it did not.");
+        }
+    }
+    
+    protected void clearExpectedFailure() {
+        failureExpected = false;
+    }
+
+    protected void setExpectingFailure() {
+        failureExpected = true;
+    }
+    
+    public <T extends TaskAdaptable<?>> T submit(final TaskFactory<T> taskFactory) {
+        return Entities.submit(app, taskFactory);
+    }
+    
+    // ------------------- basic ssh
+    
+    @Test(groups="Integration")
+    public void testSshEchoHello() {
+        ProcessTaskWrapper<Integer> t = submit(SshEffectorTasks.ssh("sleep 1 ; echo hello world"));
+        Assert.assertFalse(t.isDone());
+        Assert.assertEquals(t.get(), (Integer)0);
+        Assert.assertEquals(t.getTask().getUnchecked(), (Integer)0);
+        Assert.assertEquals(t.getStdout().trim(), "hello world");
+    }
+
+    @Test(groups="Integration")
+    public void testSshPut() throws IOException {
+        String fn = Urls.mergePaths(tempDir.getPath(), "f1");
+        SshPutTaskWrapper t = submit(SshEffectorTasks.put(fn).contents("hello world"));
+        t.block();
+        Assert.assertEquals(FileUtils.readFileToString(new File(fn)), "hello world");
+        // and make sure this doesn't throw
+        Assert.assertTrue(t.isDone());
+        Assert.assertTrue(t.isSuccessful());
+        Assert.assertEquals(t.get(), null);
+        Assert.assertEquals(t.getExitCode(), (Integer)0);
+    }
+
+    @Test(groups="Integration")
+    public void testSshFetch() throws IOException {
+        String fn = Urls.mergePaths(tempDir.getPath(), "f2");
+        FileUtils.write(new File(fn), "hello fetched world");
+        
+        SshFetchTaskWrapper t = submit(SshEffectorTasks.fetch(fn));
+        t.block();
+        
+        Assert.assertTrue(t.isDone());
+        Assert.assertEquals(t.get(), "hello fetched world");
+    }
+
+    // ----------------- pid stuff
+    
+    @Test(groups="Integration")
+    public void testNonRunningPid() {
+        ProcessTaskWrapper<Integer> t = submit(SshEffectorTasks.codePidRunning(99999));
+        Assert.assertNotEquals(t.getTask().getUnchecked(), (Integer)0);
+        Assert.assertNotEquals(t.getExitCode(), (Integer)0);
+        ProcessTaskWrapper<Boolean> t2 = submit(SshEffectorTasks.isPidRunning(99999));
+        Assert.assertFalse(t2.getTask().getUnchecked());
+    }
+
+    @Test(groups="Integration")
+    public void testNonRunningPidRequired() {
+        ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidRunning(99999));
+        setExpectingFailure();
+        try {
+            t.getTask().getUnchecked();
+        } catch (Exception e) {
+            log.info("The error if required PID is not found is: "+e);
+            clearExpectedFailure();
+            Assert.assertTrue(e.toString().contains("Process with PID"), "Expected nice clue in error but got: "+e);
+        }
+        checkExpectedFailure();
+    }
+
+    public static Integer getMyPid() {
+        try {
+            java.lang.management.RuntimeMXBean runtime = 
+                    java.lang.management.ManagementFactory.getRuntimeMXBean();
+            java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
+            jvm.setAccessible(true);
+//            sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);
+            Object mgmt = jvm.get(runtime);
+            java.lang.reflect.Method pid_method =  
+                    mgmt.getClass().getDeclaredMethod("getProcessId");
+            pid_method.setAccessible(true);
+
+            return (Integer) pid_method.invoke(mgmt);
+        } catch (Exception e) {
+            throw new PropagatedRuntimeException("Test depends on (fragile) getMyPid method which does not work here", e);
+        }
+    }
+
+    @Test(groups="Integration")
+    public void testRunningPid() {
+        ProcessTaskWrapper<Integer> t = submit(SshEffectorTasks.codePidRunning(getMyPid()));
+        Assert.assertEquals(t.getTask().getUnchecked(), (Integer)0);
+        ProcessTaskWrapper<Boolean> t2 = submit(SshEffectorTasks.isPidRunning(getMyPid()));
+        Assert.assertTrue(t2.getTask().getUnchecked());
+    }
+
+    @Test(groups="Integration")
+    public void testRunningPidFromFile() throws IOException {
+        File f = File.createTempFile("testBrooklynPid", ".pid");
+        Files.write( (""+getMyPid()).getBytes(), f );
+        ProcessTaskWrapper<Integer> t = submit(SshEffectorTasks.codePidFromFileRunning(f.getPath()));
+        Assert.assertEquals(t.getTask().getUnchecked(), (Integer)0);
+        ProcessTaskWrapper<Boolean> t2 = submit(SshEffectorTasks.isPidFromFileRunning(f.getPath()));
+        Assert.assertTrue(t2.getTask().getUnchecked());
+    }
+
+    @Test(groups="Integration")
+    public void testRequirePidFromFileOnFailure() throws IOException {
+        File f = File.createTempFile("testBrooklynPid", ".pid");
+        Files.write( "99999".getBytes(), f );
+        ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidFromFileRunning(f.getPath()));
+        
+        setExpectingFailure();
+        try {
+            t.getTask().getUnchecked();
+        } catch (Exception e) {
+            log.info("The error if required PID is not found is: "+e);
+            clearExpectedFailure();
+            Assert.assertTrue(e.toString().contains("Process with PID"), "Expected nice clue in error but got: "+e);
+            Assert.assertEquals(t.getExitCode(), (Integer)1);
+        }
+        checkExpectedFailure();
+    }
+
+    @Test(groups="Integration")
+    public void testRequirePidFromFileOnFailureNoSuchFile() throws IOException {
+        ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidFromFileRunning("/path/does/not/exist/SADVQW"));
+        
+        setExpectingFailure();
+        try {
+            t.getTask().getUnchecked();
+        } catch (Exception e) {
+            log.info("The error if required PID is not found is: "+e);
+            clearExpectedFailure();
+            Assert.assertTrue(e.toString().contains("Process with PID"), "Expected nice clue in error but got: "+e);
+            Assert.assertEquals(t.getExitCode(), (Integer)1);
+        }
+        checkExpectedFailure();
+    }
+
+    @Test(groups="Integration")
+    public void testRequirePidFromFileOnFailureTooManyFiles() throws IOException {
+        ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidFromFileRunning("/*"));
+        
+        setExpectingFailure();
+        try {
+            t.getTask().getUnchecked();
+        } catch (Exception e) {
+            log.info("The error if required PID is not found is: "+e);
+            clearExpectedFailure();
+            Assert.assertTrue(e.toString().contains("Process with PID"), "Expected nice clue in error but got: "+e);
+            Assert.assertEquals(t.getExitCode(), (Integer)2);
+        }
+        checkExpectedFailure();
+    }
+
+    @Test(groups="Integration")
+    public void testRequirePidFromFileOnSuccess() throws IOException {
+        File f = File.createTempFile("testBrooklynPid", ".pid");
+        Files.write( (""+getMyPid()).getBytes(), f );
+        ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidFromFileRunning(f.getPath()));
+        
+        t.getTask().getUnchecked();
+    }
+
+    @Test(groups="Integration")
+    public void testRequirePidFromFileOnSuccessAcceptsWildcards() throws IOException {
+        File f = File.createTempFile("testBrooklynPid", ".pid");
+        Files.write( (""+getMyPid()).getBytes(), f );
+        ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidFromFileRunning(f.getPath()+"*"));
+        
+        t.getTask().getUnchecked();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/resources/brooklyn/entity/basic/frogs.txt
----------------------------------------------------------------------
diff --git a/software/base/src/test/resources/brooklyn/entity/basic/frogs.txt b/software/base/src/test/resources/brooklyn/entity/basic/frogs.txt
deleted file mode 100644
index a3f617a..0000000
--- a/software/base/src/test/resources/brooklyn/entity/basic/frogs.txt
+++ /dev/null
@@ -1,27 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied.  See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-# The Frogs
-
-Frogs:
-> Brekekekex koax koax.
-
-Dionysus:
-> Go to hell with your koax
-> koax and nothing but koax!
-
-- Artistophanes, c. 400 BC

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/resources/brooklyn/entity/basic/template.yaml
----------------------------------------------------------------------
diff --git a/software/base/src/test/resources/brooklyn/entity/basic/template.yaml b/software/base/src/test/resources/brooklyn/entity/basic/template.yaml
deleted file mode 100644
index 4d2b29e..0000000
--- a/software/base/src/test/resources/brooklyn/entity/basic/template.yaml
+++ /dev/null
@@ -1,23 +0,0 @@
-[#ftl]
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#  http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied.  See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-entity.hostname:
-    ${driver.hostname}
-entity.address:
-    ${driver.address}
-frogs: 12
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/resources/brooklyn/entity/basic/template_with_extra_substitutions.txt
----------------------------------------------------------------------
diff --git a/software/base/src/test/resources/brooklyn/entity/basic/template_with_extra_substitutions.txt b/software/base/src/test/resources/brooklyn/entity/basic/template_with_extra_substitutions.txt
deleted file mode 100644
index 8330e3e..0000000
--- a/software/base/src/test/resources/brooklyn/entity/basic/template_with_extra_substitutions.txt
+++ /dev/null
@@ -1,18 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#  http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied.  See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-${myname}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/resources/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/brooklyn-tests.pem
----------------------------------------------------------------------
diff --git a/software/base/src/test/resources/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/brooklyn-tests.pem b/software/base/src/test/resources/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/brooklyn-tests.pem
deleted file mode 100644
index 4ca4d00..0000000
--- a/software/base/src/test/resources/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/brooklyn-tests.pem
+++ /dev/null
@@ -1,27 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIIEowIBAAKCAQEArJZcg6Y9BuPYuLWgcloS/cH6HzqQqQegW+5d7cgRZC1CCo4e
-GxVglEZXuko4N0PVK2E2khGiMEymVXWqmrHAnTSqV1COmRfxxOxGvmQRleDWMhED
-j2KoOwggwsaoHBEdrZ6NX+yv3iFiOS5fz3Klkt3kPXcXZJGiFsOtyZaSxK/m26no
-upS6ouChmk9TD8YcCQzdUGNAWwyzhiDg5DwqnnNQQUKvQyJuV/nyxwRMcpoNazca
-ghr2KalSF92sonnPzMz2gWhKxWVVbnTSafWQcWY+ov/TiyBHsLXO3/OrHaj7h+SF
-UUfWryHyqZI/eQeoWD/cPGtr8qVELIqhCq8OkQIDAQABAoIBAAS2Eg5x8kaG37qj
-Ep8sgEo3Clnh4mMK10DLL/s2s+rVJXFeUcoRelJx3SEzt3civeXyQGgaXSAOZ5f7
-n02bvpNMBb5eb5YURkBG5uN5ndVGjvJM7pjya385CJPoklw5x2Ke6mMM9fwNUz4W
-Wv0xtv1cW0emQZg4NYGDk/Hlz1nZG+y5j0esRlIiknYqdfuXtaQbVI/jGSyNXFVI
-uVkKCwq+k6HnIkjFEZdvQPRPaGMT4cMwczVr8hCIOfCJEVremEJ0GFnazr9iNEVu
-18YJzOEaqPLgVvjt59o+D+CoZS7U74WX6scCsFCkHLdnxlfNC/qkrn2SEaVyrfeP
-cqPLZJUCgYEA1qmmQzuNzWMhsOVty3EI4M2mePF0iM2P/wHc1ry9lddqdqTSGV7x
-NwzGNZ/OqN9UIR/3chyFXQuegz5VZxsrdIyxcgCmM2cDDxny3pr0Lct39gsWuc9g
-BhebUDP7PoF2g2f4AAllVR6atClwXoKfARoXlmbjfOJSB/q1zXWYNW8CgYEAzdJ/
-2o1B4iwDipKxJE2luuaMN4zqRbKdokBJYw0b1TOOcsyNwB5h0TGcJNFMuIqBeWCK
-J3wr7FTOfy3Qsbf3Vc5Le6NdaHomy7+HEwVMzyEPVNKumHqEL9U3Yheu5TVLLKMU
-rYBXXpoN/XXm9XxvRGhGu7Wu99ye37hIa4Qy+/8CgYB/JWlHdWTefJMeFibcU41w
-qh6qkEn4Jdner5nAz3Zz5G447BNN18CEXNqiNI/R0sYgALEuM9qCbDltf2RSd/Nb
-S2JnJh9LXv6e2T3TwHBVF6lsYNELKdu0gBMMhF2SflhWKSTp0KbmrgPwJoNaV4Aa
-xPunqDWiaOMxurwogDixnQKBgGgGQs5P5IOOIUARQeyKPgAHc8jDtMgDLX6KpUyl
-nHKV+yH0VpRKBsA3JabKDc+bWTLiYxDvxjdM6Y0Ht9mKlDxO5oGXoKckTaVeqMMp
-Q5fQKrKBRPMVwOd4COTP+XopBFSMG/BQ1Feg3v9CbreV65qUZWOLwOHPJJEHz7pf
-d3E7AoGBAMPkKjDuhU8YTpB6H4KlCM+9p/6yE7umoWMPJm70301XxBoQA8spkS3o
-K2s2xL7+MuppvLv0xqyZ1vtvqmUMrw/eisQWekGobEiutk+DuxegRlpUkH0s6CH4
-lypeh/FpGdLayAn84ALIEYhCsr0SnJtEL1MEO9qPKJY24Hl6ATCC
------END RSA PRIVATE KEY-----

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/resources/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/brooklyn-validator.pem
----------------------------------------------------------------------
diff --git a/software/base/src/test/resources/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/brooklyn-validator.pem b/software/base/src/test/resources/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/brooklyn-validator.pem
deleted file mode 100644
index 7fb694c..0000000
--- a/software/base/src/test/resources/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/brooklyn-validator.pem
+++ /dev/null
@@ -1,27 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIIEowIBAAKCAQEA1L/awgkt+AxAHc76IeJAsZYj0ZoW8pP0Ff2SL8ZmkoGOT3C6
-d6DhQ8H194YTYNZ+w+D4K6DkNf8MqoFnQnLyQHlALd+giCE9mS1SUS0YBBdXbGh/
-320cosPqvMrT16nxbTLz7rgGNYSvgS5tnFYIADv4AzvXZMOZ20VXkDNCiqG0Pqy5
-qAMvmNGJNpDfERebdQUoZpqPJysJYXmy2cKYm5cfsDCxmL9iGyPjHazU6FizC50M
-SJ+ZGtqVEB/0d4p4u/pHAZQJCFdxJszHqBbYfQDFJso9lAdkM/11Tq5NtBH3cTPi
-SfcFIWLSS4qu1RcRmURRtsZTr/4FOKcYWpmLcwIDAQABAoIBACLzzi3YsjuxT4tW
-KNQORtCmOQZDiYea9Rvzx+OfddSWAlpcy9XBkaC/Kfjbhy1+r97ghAUu7q9MUrlk
-fyF0nwYmpXuj5MzYoTUcNAzwGqT5bLx7wp5jX7QB+fvAWuNwoSBuoZLTmvmJ7geM
-KCfqHnBjadCmMTH1zL4wez1Onp0FvRDXGPGjERQGptpejTL8PBaarzF2Ufewb/0z
-2/Icl1RAGHNkJHJjedL2mgtKHzW/JTBLcMjN1+PL4pLMriXCTP3VZZlezx8RXrnW
-DTFWe6G8gcPhYh0ni3wtoI/ENvXORg+wFXa2B/FKRObTu+vyYyvDgUSB2TI5LebX
-XsuWEEECgYEA/f9gkab9+m9JDz7AYDF4f+YzECdZwA0ntAnA5Qb/zWnjbcbtOMMF
-lNEm+m9J9GoorSpO9e/4Z61dtEsuX9Vr2tyKSnamNQT2vI+WIUIbGMWFq/VNi390
-o0jQWhEead/xu5BFbLEBD651+NBQGBCQi8slzOAL6jqP8qEGeaYaauECgYEA1m06
-wdHM3U5wwCGsyzTloGZ0LtTFO6oKYPpU/MItEESqVY1grFh5Sqa6tyJEq0jZSdKM
-eXzlqSyJQbaHd85PJnDkVnJVpdeqRj1eMHtv9+s3A8kOzSww+FL7KJHUrnNBZ7MK
-J7wdPtzYBFL124NAhbTaR6+Kv1ZSUpkGFRCV9NMCgYBtMy5BcJog4Vd3xnLO6HX2
-BvJNL53Wg9FeBhN4Y9n2Zl/xAmVa0f3ETWeEo/QXsMxsJpRsCA+0A0UWDnyRlyAX
-qFmMShaLFOc/ijvxcIpVzBX8KCp+nv12dgedsV5yBmXXTd+LK05Zf5gYsPa+YeDD
-OUO3IVv+B897cN9nzZHuAQKBgGIC44ycXUv7AsaPne/0adF7gze0wcKX4s6ZHie6
-ieaZvFIGoV2lwytAMrBq1YCFd+yqdNNDJ6bAWKzUxe8ZOkyT5YsuD8ASaB5bBqaa
-hX+I4Ei2qjFWNbwMEgllPxXOUOMZj1bCQYvuXj77vK1tvRxgojWKI5150381uvX9
-8s1JAoGBAO73ig60VNqPTHg1KDZ7SdAW0KbNiAV+xojvW9pkH5M1vCllz+lpeW1l
-jZFbnL013r5UvzRgwqIuw4t+gZikfIZgPwP8Z2BGtIzNiIHy/RLzOawsPTTXczZA
-hHI2e54G9DgCi8h4LXhFavVykTkNTP62S6za4VTEjxERdWxIBnfL
------END RSA PRIVATE KEY-----
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/resources/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/knife.rb
----------------------------------------------------------------------
diff --git a/software/base/src/test/resources/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/knife.rb b/software/base/src/test/resources/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/knife.rb
deleted file mode 100644
index d52e492..0000000
--- a/software/base/src/test/resources/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/knife.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#  http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied.  See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-current_dir = File.dirname(__FILE__)
-log_level                :info
-log_location             STDOUT
-node_name                "brooklyn-tests"
-client_key               "#{current_dir}/brooklyn-tests.pem"
-validation_client_name   "brooklyn-validator"
-validation_key           "#{current_dir}/brooklyn-validator.pem"
-chef_server_url          "https://api.opscode.com/organizations/brooklyn"

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/resources/org/apache/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/brooklyn-tests.pem
----------------------------------------------------------------------
diff --git a/software/base/src/test/resources/org/apache/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/brooklyn-tests.pem b/software/base/src/test/resources/org/apache/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/brooklyn-tests.pem
new file mode 100644
index 0000000..4ca4d00
--- /dev/null
+++ b/software/base/src/test/resources/org/apache/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/brooklyn-tests.pem
@@ -0,0 +1,27 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIEowIBAAKCAQEArJZcg6Y9BuPYuLWgcloS/cH6HzqQqQegW+5d7cgRZC1CCo4e
+GxVglEZXuko4N0PVK2E2khGiMEymVXWqmrHAnTSqV1COmRfxxOxGvmQRleDWMhED
+j2KoOwggwsaoHBEdrZ6NX+yv3iFiOS5fz3Klkt3kPXcXZJGiFsOtyZaSxK/m26no
+upS6ouChmk9TD8YcCQzdUGNAWwyzhiDg5DwqnnNQQUKvQyJuV/nyxwRMcpoNazca
+ghr2KalSF92sonnPzMz2gWhKxWVVbnTSafWQcWY+ov/TiyBHsLXO3/OrHaj7h+SF
+UUfWryHyqZI/eQeoWD/cPGtr8qVELIqhCq8OkQIDAQABAoIBAAS2Eg5x8kaG37qj
+Ep8sgEo3Clnh4mMK10DLL/s2s+rVJXFeUcoRelJx3SEzt3civeXyQGgaXSAOZ5f7
+n02bvpNMBb5eb5YURkBG5uN5ndVGjvJM7pjya385CJPoklw5x2Ke6mMM9fwNUz4W
+Wv0xtv1cW0emQZg4NYGDk/Hlz1nZG+y5j0esRlIiknYqdfuXtaQbVI/jGSyNXFVI
+uVkKCwq+k6HnIkjFEZdvQPRPaGMT4cMwczVr8hCIOfCJEVremEJ0GFnazr9iNEVu
+18YJzOEaqPLgVvjt59o+D+CoZS7U74WX6scCsFCkHLdnxlfNC/qkrn2SEaVyrfeP
+cqPLZJUCgYEA1qmmQzuNzWMhsOVty3EI4M2mePF0iM2P/wHc1ry9lddqdqTSGV7x
+NwzGNZ/OqN9UIR/3chyFXQuegz5VZxsrdIyxcgCmM2cDDxny3pr0Lct39gsWuc9g
+BhebUDP7PoF2g2f4AAllVR6atClwXoKfARoXlmbjfOJSB/q1zXWYNW8CgYEAzdJ/
+2o1B4iwDipKxJE2luuaMN4zqRbKdokBJYw0b1TOOcsyNwB5h0TGcJNFMuIqBeWCK
+J3wr7FTOfy3Qsbf3Vc5Le6NdaHomy7+HEwVMzyEPVNKumHqEL9U3Yheu5TVLLKMU
+rYBXXpoN/XXm9XxvRGhGu7Wu99ye37hIa4Qy+/8CgYB/JWlHdWTefJMeFibcU41w
+qh6qkEn4Jdner5nAz3Zz5G447BNN18CEXNqiNI/R0sYgALEuM9qCbDltf2RSd/Nb
+S2JnJh9LXv6e2T3TwHBVF6lsYNELKdu0gBMMhF2SflhWKSTp0KbmrgPwJoNaV4Aa
+xPunqDWiaOMxurwogDixnQKBgGgGQs5P5IOOIUARQeyKPgAHc8jDtMgDLX6KpUyl
+nHKV+yH0VpRKBsA3JabKDc+bWTLiYxDvxjdM6Y0Ht9mKlDxO5oGXoKckTaVeqMMp
+Q5fQKrKBRPMVwOd4COTP+XopBFSMG/BQ1Feg3v9CbreV65qUZWOLwOHPJJEHz7pf
+d3E7AoGBAMPkKjDuhU8YTpB6H4KlCM+9p/6yE7umoWMPJm70301XxBoQA8spkS3o
+K2s2xL7+MuppvLv0xqyZ1vtvqmUMrw/eisQWekGobEiutk+DuxegRlpUkH0s6CH4
+lypeh/FpGdLayAn84ALIEYhCsr0SnJtEL1MEO9qPKJY24Hl6ATCC
+-----END RSA PRIVATE KEY-----

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/resources/org/apache/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/brooklyn-validator.pem
----------------------------------------------------------------------
diff --git a/software/base/src/test/resources/org/apache/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/brooklyn-validator.pem b/software/base/src/test/resources/org/apache/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/brooklyn-validator.pem
new file mode 100644
index 0000000..7fb694c
--- /dev/null
+++ b/software/base/src/test/resources/org/apache/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/brooklyn-validator.pem
@@ -0,0 +1,27 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIEowIBAAKCAQEA1L/awgkt+AxAHc76IeJAsZYj0ZoW8pP0Ff2SL8ZmkoGOT3C6
+d6DhQ8H194YTYNZ+w+D4K6DkNf8MqoFnQnLyQHlALd+giCE9mS1SUS0YBBdXbGh/
+320cosPqvMrT16nxbTLz7rgGNYSvgS5tnFYIADv4AzvXZMOZ20VXkDNCiqG0Pqy5
+qAMvmNGJNpDfERebdQUoZpqPJysJYXmy2cKYm5cfsDCxmL9iGyPjHazU6FizC50M
+SJ+ZGtqVEB/0d4p4u/pHAZQJCFdxJszHqBbYfQDFJso9lAdkM/11Tq5NtBH3cTPi
+SfcFIWLSS4qu1RcRmURRtsZTr/4FOKcYWpmLcwIDAQABAoIBACLzzi3YsjuxT4tW
+KNQORtCmOQZDiYea9Rvzx+OfddSWAlpcy9XBkaC/Kfjbhy1+r97ghAUu7q9MUrlk
+fyF0nwYmpXuj5MzYoTUcNAzwGqT5bLx7wp5jX7QB+fvAWuNwoSBuoZLTmvmJ7geM
+KCfqHnBjadCmMTH1zL4wez1Onp0FvRDXGPGjERQGptpejTL8PBaarzF2Ufewb/0z
+2/Icl1RAGHNkJHJjedL2mgtKHzW/JTBLcMjN1+PL4pLMriXCTP3VZZlezx8RXrnW
+DTFWe6G8gcPhYh0ni3wtoI/ENvXORg+wFXa2B/FKRObTu+vyYyvDgUSB2TI5LebX
+XsuWEEECgYEA/f9gkab9+m9JDz7AYDF4f+YzECdZwA0ntAnA5Qb/zWnjbcbtOMMF
+lNEm+m9J9GoorSpO9e/4Z61dtEsuX9Vr2tyKSnamNQT2vI+WIUIbGMWFq/VNi390
+o0jQWhEead/xu5BFbLEBD651+NBQGBCQi8slzOAL6jqP8qEGeaYaauECgYEA1m06
+wdHM3U5wwCGsyzTloGZ0LtTFO6oKYPpU/MItEESqVY1grFh5Sqa6tyJEq0jZSdKM
+eXzlqSyJQbaHd85PJnDkVnJVpdeqRj1eMHtv9+s3A8kOzSww+FL7KJHUrnNBZ7MK
+J7wdPtzYBFL124NAhbTaR6+Kv1ZSUpkGFRCV9NMCgYBtMy5BcJog4Vd3xnLO6HX2
+BvJNL53Wg9FeBhN4Y9n2Zl/xAmVa0f3ETWeEo/QXsMxsJpRsCA+0A0UWDnyRlyAX
+qFmMShaLFOc/ijvxcIpVzBX8KCp+nv12dgedsV5yBmXXTd+LK05Zf5gYsPa+YeDD
+OUO3IVv+B897cN9nzZHuAQKBgGIC44ycXUv7AsaPne/0adF7gze0wcKX4s6ZHie6
+ieaZvFIGoV2lwytAMrBq1YCFd+yqdNNDJ6bAWKzUxe8ZOkyT5YsuD8ASaB5bBqaa
+hX+I4Ei2qjFWNbwMEgllPxXOUOMZj1bCQYvuXj77vK1tvRxgojWKI5150381uvX9
+8s1JAoGBAO73ig60VNqPTHg1KDZ7SdAW0KbNiAV+xojvW9pkH5M1vCllz+lpeW1l
+jZFbnL013r5UvzRgwqIuw4t+gZikfIZgPwP8Z2BGtIzNiIHy/RLzOawsPTTXczZA
+hHI2e54G9DgCi8h4LXhFavVykTkNTP62S6za4VTEjxERdWxIBnfL
+-----END RSA PRIVATE KEY-----
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/resources/org/apache/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/knife.rb
----------------------------------------------------------------------
diff --git a/software/base/src/test/resources/org/apache/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/knife.rb b/software/base/src/test/resources/org/apache/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/knife.rb
new file mode 100644
index 0000000..d52e492
--- /dev/null
+++ b/software/base/src/test/resources/org/apache/brooklyn/entity/chef/hosted-chef-brooklyn-credentials/knife.rb
@@ -0,0 +1,27 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#  http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+current_dir = File.dirname(__FILE__)
+log_level                :info
+log_location             STDOUT
+node_name                "brooklyn-tests"
+client_key               "#{current_dir}/brooklyn-tests.pem"
+validation_client_name   "brooklyn-validator"
+validation_key           "#{current_dir}/brooklyn-validator.pem"
+chef_server_url          "https://api.opscode.com/organizations/brooklyn"

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/resources/org/apache/brooklyn/entity/software/base/frogs.txt
----------------------------------------------------------------------
diff --git a/software/base/src/test/resources/org/apache/brooklyn/entity/software/base/frogs.txt b/software/base/src/test/resources/org/apache/brooklyn/entity/software/base/frogs.txt
new file mode 100644
index 0000000..a3f617a
--- /dev/null
+++ b/software/base/src/test/resources/org/apache/brooklyn/entity/software/base/frogs.txt
@@ -0,0 +1,27 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# The Frogs
+
+Frogs:
+> Brekekekex koax koax.
+
+Dionysus:
+> Go to hell with your koax
+> koax and nothing but koax!
+
+- Artistophanes, c. 400 BC

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/resources/org/apache/brooklyn/entity/software/base/template.yaml
----------------------------------------------------------------------
diff --git a/software/base/src/test/resources/org/apache/brooklyn/entity/software/base/template.yaml b/software/base/src/test/resources/org/apache/brooklyn/entity/software/base/template.yaml
new file mode 100644
index 0000000..4d2b29e
--- /dev/null
+++ b/software/base/src/test/resources/org/apache/brooklyn/entity/software/base/template.yaml
@@ -0,0 +1,23 @@
+[#ftl]
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#  http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+entity.hostname:
+    ${driver.hostname}
+entity.address:
+    ${driver.address}
+frogs: 12
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/resources/org/apache/brooklyn/entity/software/base/template_with_extra_substitutions.txt
----------------------------------------------------------------------
diff --git a/software/base/src/test/resources/org/apache/brooklyn/entity/software/base/template_with_extra_substitutions.txt b/software/base/src/test/resources/org/apache/brooklyn/entity/software/base/template_with_extra_substitutions.txt
new file mode 100644
index 0000000..8330e3e
--- /dev/null
+++ b/software/base/src/test/resources/org/apache/brooklyn/entity/software/base/template_with_extra_substitutions.txt
@@ -0,0 +1,18 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#  http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+${myname}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNode.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNode.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNode.java
index 9762d5c..94b03bf 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNode.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNode.java
@@ -22,16 +22,12 @@ import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
-
-import brooklyn.entity.java.UsesJava;
-import brooklyn.entity.java.UsesJavaMXBeans;
-import brooklyn.entity.java.UsesJmx;
-
+import org.apache.brooklyn.entity.java.UsesJava;
+import org.apache.brooklyn.entity.java.UsesJavaMXBeans;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.location.basic.PortRanges;
 import org.apache.brooklyn.sensor.core.AttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeDriver.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeDriver.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeDriver.java
index 708e0e8..de01b6b 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeDriver.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeDriver.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.entity.database.crate;
 
-import brooklyn.entity.java.JavaSoftwareProcessDriver;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessDriver;
 
 public interface CrateNodeDriver extends JavaSoftwareProcessDriver {
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeImpl.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeImpl.java
index 5cf4065..7e4f314 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeImpl.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeImpl.java
@@ -20,16 +20,15 @@ package org.apache.brooklyn.entity.database.crate;
 
 import org.apache.brooklyn.core.config.render.RendererHints;
 import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.java.JavaAppUtils;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.sensor.enricher.Enrichers;
 import org.apache.brooklyn.sensor.feed.http.HttpFeed;
 import org.apache.brooklyn.sensor.feed.http.HttpPollConfig;
 import org.apache.brooklyn.sensor.feed.http.HttpValueFunctions;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
 import org.apache.brooklyn.util.guava.Functionals;
 
-import brooklyn.entity.basic.SoftwareProcessImpl;
-import brooklyn.entity.java.JavaAppUtils;
-import brooklyn.event.feed.jmx.JmxFeed;
-
 public class CrateNodeImpl extends SoftwareProcessImpl implements CrateNode{
 
     private JmxFeed jmxFeed;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeSshDriver.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeSshDriver.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeSshDriver.java
index f72c071..fbfe9dd 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeSshDriver.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/crate/CrateNodeSshDriver.java
@@ -24,11 +24,10 @@ import java.util.List;
 
 import org.apache.brooklyn.api.internal.EntityLocal;
 import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
 
 import com.google.common.collect.ImmutableList;
 
-import brooklyn.entity.java.JavaSoftwareProcessSshDriver;
-
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.net.Urls;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbDriver.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbDriver.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbDriver.java
index 066a73b..05c097a 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbDriver.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbDriver.java
@@ -18,10 +18,9 @@
  */
 package org.apache.brooklyn.entity.database.mariadb;
 
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
-
 /**
  * The {@link SoftwareProcessDriver} for MariaDB.
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNode.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNode.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNode.java
index 5612b5b..a5a91f6 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNode.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNode.java
@@ -25,12 +25,10 @@ import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.core.config.MapConfigKey;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.database.DatabaseNode;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.location.basic.PortRanges;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNodeImpl.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNodeImpl.java
index 632e3f2..0b5becf 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNodeImpl.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbNodeImpl.java
@@ -20,10 +20,8 @@ package org.apache.brooklyn.entity.database.mariadb;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import org.apache.brooklyn.effector.core.EffectorBody;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.apache.brooklyn.location.basic.Locations;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.ssh.SshFeed;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbSshDriver.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbSshDriver.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbSshDriver.java
index 054e5fa..300cc35 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbSshDriver.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/mariadb/MariaDbSshDriver.java
@@ -33,17 +33,13 @@ import java.util.Map;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver;
-
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.database.DatastoreMixins;
-
-import brooklyn.entity.software.SshEffectorTasks;
-
+import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
 import org.apache.brooklyn.api.location.OsDetails;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.core.task.DynamicTasks;
 import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlDriver.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlDriver.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlDriver.java
index b11d22b..461369b 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlDriver.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlDriver.java
@@ -18,10 +18,9 @@
  */
 package org.apache.brooklyn.entity.database.mysql;
 
+import org.apache.brooklyn.entity.software.base.SoftwareProcessDriver;
 import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
 
-import brooklyn.entity.basic.SoftwareProcessDriver;
-
 /**
  * The {@link SoftwareProcessDriver} for MySQL.
  */

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNode.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNode.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNode.java
index b9e9f2c..be837c4 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNode.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNode.java
@@ -25,14 +25,12 @@ import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.core.config.MapConfigKey;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
 import org.apache.brooklyn.effector.core.MethodEffector;
 import org.apache.brooklyn.entity.annotation.Effector;
 import org.apache.brooklyn.entity.annotation.EffectorParam;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.database.DatastoreMixins.DatastoreCommon;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.location.basic.PortRanges;
 import org.apache.brooklyn.sensor.core.BasicAttributeSensorAndConfigKey;
 import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNodeImpl.java b/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNodeImpl.java
index 5d1462f..4f0ae7d 100644
--- a/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNodeImpl.java
+++ b/software/database/src/main/java/org/apache/brooklyn/entity/database/mysql/MySqlNodeImpl.java
@@ -22,11 +22,9 @@ import java.util.Map;
 
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.effector.core.EffectorBody;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
-import brooklyn.entity.basic.SoftwareProcessImpl;
-
 import org.apache.brooklyn.location.basic.Locations;
 import org.apache.brooklyn.location.basic.SshMachineLocation;
 import org.apache.brooklyn.sensor.feed.ssh.SshFeed;



[64/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynPersistenceUtils.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynPersistenceUtils.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynPersistenceUtils.java
deleted file mode 100644
index 55dc2f5..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/BrooklynPersistenceUtils.java
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import java.util.List;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.api.catalog.CatalogItem;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
-import org.apache.brooklyn.api.mgmt.ha.ManagementPlaneSyncRecord;
-import org.apache.brooklyn.api.mgmt.ha.MementoCopyMode;
-import org.apache.brooklyn.api.mgmt.rebind.PersistenceExceptionHandler;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.Memento;
-import org.apache.brooklyn.api.objs.BrooklynObject;
-import org.apache.brooklyn.api.objs.BrooklynObjectType;
-import org.apache.brooklyn.api.policy.Policy;
-import org.apache.brooklyn.api.sensor.Enricher;
-import org.apache.brooklyn.api.sensor.Feed;
-import org.apache.brooklyn.core.mgmt.ha.ManagementPlaneSyncRecordPersisterToObjectStore;
-import org.apache.brooklyn.core.mgmt.internal.LocalLocationManager;
-import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.core.mgmt.rebind.PersistenceExceptionHandlerImpl;
-import org.apache.brooklyn.core.mgmt.rebind.transformer.CompoundTransformer;
-import org.apache.brooklyn.core.mgmt.rebind.transformer.CompoundTransformerLoader;
-import org.apache.brooklyn.core.objs.BrooklynObjectInternal;
-import org.apache.brooklyn.core.server.BrooklynServerConfig;
-import org.apache.brooklyn.core.server.BrooklynServerPaths;
-import org.apache.brooklyn.entity.core.Entities;
-import org.apache.brooklyn.entity.core.EntityInternal;
-import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.util.core.ResourceUtils;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Stopwatch;
-import com.google.common.collect.ImmutableList;
-
-public class BrooklynPersistenceUtils {
-
-    private static final Logger log = LoggerFactory.getLogger(BrooklynPersistenceUtils.class);
-    
-    @Beta
-    public static final List<BrooklynObjectType> STANDARD_BROOKLYN_OBJECT_TYPE_PERSISTENCE_ORDER = ImmutableList.of( 
-        BrooklynObjectType.ENTITY, BrooklynObjectType.LOCATION, BrooklynObjectType.POLICY,
-        BrooklynObjectType.ENRICHER, BrooklynObjectType.FEED, BrooklynObjectType.CATALOG_ITEM);
-
-    /** Creates a {@link PersistenceObjectStore} for general-purpose use. */
-    public static PersistenceObjectStore newPersistenceObjectStore(ManagementContext managementContext,
-            String locationSpec, String locationContainer) {
-        
-        return newPersistenceObjectStore(managementContext, locationSpec, locationContainer,
-            PersistMode.AUTO, HighAvailabilityMode.STANDBY);
-    }
-    
-    /** Creates a {@link PersistenceObjectStore} for use with a specified set of modes. */
-    public static PersistenceObjectStore newPersistenceObjectStore(ManagementContext managementContext,
-            String locationSpec, String locationContainer, PersistMode persistMode, HighAvailabilityMode highAvailabilityMode) {
-        PersistenceObjectStore destinationObjectStore;
-        locationContainer = BrooklynServerPaths.newMainPersistencePathResolver(managementContext).location(locationSpec).dir(locationContainer).resolve();
-
-        Location location = null;
-        if (Strings.isBlank(locationSpec)) {
-            location = managementContext.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class)
-                .configure(LocalLocationManager.CREATE_UNMANAGED, true));
-        } else {
-            location = managementContext.getLocationRegistry().resolve(locationSpec, false, null).get();
-            if (!(location instanceof LocationWithObjectStore)) {
-                throw new IllegalArgumentException("Destination location "+location+" does not offer a persistent store");
-            }
-        }
-        destinationObjectStore = ((LocationWithObjectStore)location).newPersistenceObjectStore(locationContainer);
-        
-        destinationObjectStore.injectManagementContext(managementContext);
-        destinationObjectStore.prepareForSharedUse(persistMode, highAvailabilityMode);
-        return destinationObjectStore;
-    }
-
-    public static void writeMemento(ManagementContext managementContext, BrooklynMementoRawData memento,
-            PersistenceObjectStore destinationObjectStore) {
-        BrooklynMementoPersisterToObjectStore persister = new BrooklynMementoPersisterToObjectStore(
-            destinationObjectStore,
-            ((ManagementContextInternal)managementContext).getBrooklynProperties(),
-            managementContext.getCatalogClassLoader());
-        PersistenceExceptionHandler exceptionHandler = PersistenceExceptionHandlerImpl.builder().build();
-        persister.enableWriteAccess();
-        persister.checkpoint(memento, exceptionHandler);
-    }
-
-    public static void writeManagerMemento(ManagementContext managementContext, ManagementPlaneSyncRecord optionalPlaneRecord,
-            PersistenceObjectStore destinationObjectStore) {
-        if (optionalPlaneRecord != null) {
-            ManagementPlaneSyncRecordPersisterToObjectStore managementPersister = new ManagementPlaneSyncRecordPersisterToObjectStore(
-                    managementContext, destinationObjectStore, managementContext.getCatalogClassLoader());
-            managementPersister.checkpoint(optionalPlaneRecord);
-        }
-    }
-
-    public static CompoundTransformer loadTransformer(ResourceUtils resources, String transformationsFileUrl) {
-        if (Strings.isBlank(transformationsFileUrl)) {
-            return CompoundTransformer.NOOP; 
-        } else {
-            String contents = resources.getResourceAsString(transformationsFileUrl);
-            return CompoundTransformerLoader.load(contents);
-        }
-    }
-
-    public static Memento newObjectMemento(BrooklynObject instance) {
-        return ((BrooklynObjectInternal)instance).getRebindSupport().getMemento();
-    }
-    
-    public static BrooklynMementoRawData newStateMemento(ManagementContext mgmt, MementoCopyMode source) {
-        switch (source) {
-        case LOCAL: 
-            return newStateMementoFromLocal(mgmt); 
-        case REMOTE: 
-            return mgmt.getRebindManager().retrieveMementoRawData(); 
-        case AUTO: 
-            throw new IllegalStateException("Copy mode AUTO not supported here");
-        }
-        throw new IllegalStateException("Should not come here, unknown mode "+source);
-    }
-    
-    public static ManagementPlaneSyncRecord newManagerMemento(ManagementContext mgmt, MementoCopyMode source) {
-        switch (source) {
-        case LOCAL: 
-            return mgmt.getHighAvailabilityManager().getLastManagementPlaneSyncRecord();
-        case REMOTE: 
-            return mgmt.getHighAvailabilityManager().loadManagementPlaneSyncRecord(true);
-        case AUTO: 
-            throw new IllegalStateException("Copy mode AUTO not supported here");
-        }
-        throw new IllegalStateException("Should not come here, unknown mode "+source);
-    }
-    
-
-    private static BrooklynMementoRawData newStateMementoFromLocal(ManagementContext mgmt) {
-        BrooklynMementoRawData.Builder result = BrooklynMementoRawData.builder();
-        MementoSerializer<Object> rawSerializer = new XmlMementoSerializer<Object>(mgmt.getClass().getClassLoader());
-        RetryingMementoSerializer<Object> serializer = new RetryingMementoSerializer<Object>(rawSerializer, 1);
-        
-        for (Location instance: mgmt.getLocationManager().getLocations())
-            result.location(instance.getId(), serializer.toString(newObjectMemento(instance)));
-        for (Entity instance: mgmt.getEntityManager().getEntities()) {
-            instance = Entities.deproxy(instance);
-            result.entity(instance.getId(), serializer.toString(newObjectMemento(instance)));
-            for (Feed instanceAdjunct: ((EntityInternal)instance).feeds().getFeeds())
-                result.feed(instanceAdjunct.getId(), serializer.toString(newObjectMemento(instanceAdjunct)));
-            for (Enricher instanceAdjunct: instance.getEnrichers())
-                result.enricher(instanceAdjunct.getId(), serializer.toString(newObjectMemento(instanceAdjunct)));
-            for (Policy instanceAdjunct: instance.getPolicies())
-                result.policy(instanceAdjunct.getId(), serializer.toString(newObjectMemento(instanceAdjunct)));
-        }
-        for (CatalogItem<?,?> instance: mgmt.getCatalog().getCatalogItems())
-            result.catalogItem(instance.getId(), serializer.toString(newObjectMemento(instance)));
-        
-        return result.build();
-    }
-
-    /** generates and writes mementos for the given mgmt context to the given targetStore;
-     * this may be taken from {@link MementoCopyMode#LOCAL} current state 
-     * or {@link MementoCopyMode#REMOTE} persisted state, or the default {@link MementoCopyMode#AUTO} detected
-     */
-    public static void writeMemento(ManagementContext mgmt, PersistenceObjectStore targetStore, MementoCopyMode source) {
-        if (source==null || source==MementoCopyMode.AUTO) 
-            source = (mgmt.getHighAvailabilityManager().getNodeState()==ManagementNodeState.MASTER ? MementoCopyMode.LOCAL : MementoCopyMode.REMOTE);
-
-        Stopwatch timer = Stopwatch.createStarted();
-        
-        BrooklynMementoRawData dataRecord = newStateMemento(mgmt, source); 
-        ManagementPlaneSyncRecord mgmtRecord = newManagerMemento(mgmt, source);
-
-        writeMemento(mgmt, dataRecord, targetStore);
-        writeManagerMemento(mgmt, mgmtRecord, targetStore);
-        
-        log.debug("Wrote full memento to "+targetStore+" in "+Time.makeTimeStringRounded(Duration.of(timer)));
-    }
-
-    public static enum CreateBackupMode { PROMOTION, DEMOTION, CUSTOM;
-        @Override public String toString() { return super.toString().toLowerCase(); }
-    }
-    
-    public static void createBackup(ManagementContext managementContext, CreateBackupMode mode, MementoCopyMode source) {
-        if (source==null || source==MementoCopyMode.AUTO) {
-            switch (mode) {
-            case PROMOTION: source = MementoCopyMode.REMOTE; break;
-            case DEMOTION: source = MementoCopyMode.LOCAL; break;
-            default:
-                throw new IllegalArgumentException("Cannot detect copy mode for "+mode+"/"+source);
-            }
-        }
-        BrooklynMementoRawData memento = null;
-        ManagementPlaneSyncRecord planeState = null;
-        
-        try {
-            log.debug("Loading persisted state on "+mode+" for backup purposes");
-            memento = newStateMemento(managementContext, source);
-            try {
-                planeState = newManagerMemento(managementContext, source);
-            } catch (Exception e) {
-                Exceptions.propagateIfFatal(e);
-                log.warn("Unable to access management plane sync state on "+mode+" (ignoring): "+e, e);
-            }
-        
-            PersistenceObjectStore destinationObjectStore = null;
-            String backupSpec = managementContext.getConfig().getConfig(BrooklynServerConfig.PERSISTENCE_BACKUPS_LOCATION_SPEC);
-            String nonBackupSpec = managementContext.getConfig().getConfig(BrooklynServerConfig.PERSISTENCE_LOCATION_SPEC);
-            try {
-                String backupContainer = BrooklynServerPaths.newBackupPersistencePathResolver(managementContext)
-                    .location(backupSpec).nonBackupLocation(nonBackupSpec).resolveWithSubpathFor(managementContext, mode.toString());
-                destinationObjectStore = BrooklynPersistenceUtils.newPersistenceObjectStore(managementContext, backupSpec, backupContainer);
-                log.debug("Backing up persisted state on "+mode+", to "+destinationObjectStore.getSummaryName());
-                BrooklynPersistenceUtils.writeMemento(managementContext, memento, destinationObjectStore);
-                BrooklynPersistenceUtils.writeManagerMemento(managementContext, planeState, destinationObjectStore);
-                if (!memento.isEmpty()) {
-                    log.info("Back-up of persisted state created on "+mode+", in "+destinationObjectStore.getSummaryName());
-                } else {
-                    log.debug("Back-up of (empty) persisted state created on "+mode+", in "+destinationObjectStore.getSummaryName());
-                }
-                
-            } catch (Exception e) {
-                Exceptions.propagateIfFatal(e);
-                PersistenceObjectStore failedStore = destinationObjectStore;
-                if (!Strings.isBlank(backupSpec) && !"localhost".equals(backupSpec)) {
-                    String failedSpec = backupSpec;
-                    backupSpec = "localhost";
-                    String backupContainer = BrooklynServerPaths.newBackupPersistencePathResolver(managementContext)
-                        .location(backupSpec).nonBackupLocation(nonBackupSpec).resolveWithSubpathFor(managementContext, mode.toString());
-                    destinationObjectStore = BrooklynPersistenceUtils.newPersistenceObjectStore(managementContext, backupSpec, backupContainer);
-                    log.warn("Persisted state back-up to "+(failedStore!=null ? failedStore.getSummaryName() : failedSpec)
-                        +" failed with "+e, e);
-                    
-                    log.debug("Backing up persisted state on "+mode+", locally because remote failed, to "+destinationObjectStore.getSummaryName());
-                    BrooklynPersistenceUtils.writeMemento(managementContext, memento, destinationObjectStore);
-                    BrooklynPersistenceUtils.writeManagerMemento(managementContext, planeState, destinationObjectStore);
-                    log.info("Back-up of persisted state created on "+mode+", locally because remote failed, in "+destinationObjectStore.getSummaryName());
-                }
-            }
-        } catch (Exception e) {
-            Exceptions.propagateIfFatal(e);
-            log.warn("Unable to backup management plane sync state on "+mode+" (ignoring): "+e, e);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/CatalogItemLibrariesConverter.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/CatalogItemLibrariesConverter.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/CatalogItemLibrariesConverter.java
deleted file mode 100644
index 1e53b41..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/CatalogItemLibrariesConverter.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.apache.brooklyn.api.catalog.CatalogItem.CatalogBundle;
-import org.apache.brooklyn.api.catalog.CatalogItem.CatalogItemLibraries;
-import org.apache.brooklyn.core.catalog.internal.CatalogBundleDto;
-
-import com.thoughtworks.xstream.converters.Converter;
-import com.thoughtworks.xstream.converters.MarshallingContext;
-import com.thoughtworks.xstream.converters.UnmarshallingContext;
-import com.thoughtworks.xstream.io.HierarchicalStreamReader;
-import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
-
-/**
- *  Convert old-style rebind file formats to the latest version.
- *  The code is needed only during transition to the new version, can be removed after a while.
- */
-@Deprecated
-public class CatalogItemLibrariesConverter implements Converter {
-
-    @Override
-    public boolean canConvert(@SuppressWarnings("rawtypes") Class type) {
-        return CatalogItemLibraries.class.isAssignableFrom(type) ||
-                Collection.class.isAssignableFrom(type);
-    }
-
-    @Override
-    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
-        context.convertAnother(source);
-    }
-
-    @Override
-    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
-        Object obj = context.convertAnother(context.currentObject(), context.getRequiredType());
-        if (CatalogItemLibraries.class.isAssignableFrom(context.getRequiredType())) {
-            CatalogItemLibraries libs = (CatalogItemLibraries)obj;
-            Collection<String> bundles = libs.getBundles();
-            Collection<CatalogBundle> libraries = new ArrayList<CatalogBundle>(bundles.size());
-            for (String url : bundles) {
-                libraries.add(new CatalogBundleDto(null, null, url));
-            }
-            return libraries;
-        } else {
-            return obj;
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/FileBasedObjectStore.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/FileBasedObjectStore.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/FileBasedObjectStore.java
deleted file mode 100644
index bd83387..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/FileBasedObjectStore.java
+++ /dev/null
@@ -1,425 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import static java.lang.String.format;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.io.IOException;
-import java.text.SimpleDateFormat;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.annotation.Nullable;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.core.server.BrooklynServerConfig;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.internal.ssh.process.ProcessTool;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.exceptions.FatalConfigurationRuntimeException;
-import org.apache.brooklyn.util.io.FileUtil;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.os.Os.DeletionResult;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Function;
-import com.google.common.base.Objects;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.FluentIterable;
-import com.google.common.collect.ImmutableList;
-import com.google.common.io.Files;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-
-/**
- * @author Andrea Turli
- */
-public class FileBasedObjectStore implements PersistenceObjectStore {
-
-    private static final Logger log = LoggerFactory.getLogger(FileBasedObjectStore.class);
-
-    private static final int SHUTDOWN_TIMEOUT_MS = 10*1000;
-
-    private final File basedir;
-    private final ListeningExecutorService executor;
-    private ManagementContext mgmt;
-    private boolean prepared = false;
-    private boolean deferredBackupNeeded = false;
-    private AtomicBoolean doneFirstContentiousWrite = new AtomicBoolean(false);
-
-    /**
-     * @param basedir
-     */
-    public FileBasedObjectStore(File basedir) {
-        this.basedir = checkPersistenceDirPlausible(basedir);
-        this.executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
-        log.debug("File-based objectStore will use directory {}", basedir);
-        // don't check accessible yet, we do that when we prepare
-    }
-
-    @Override
-    public String getSummaryName() {
-        return getBaseDir().getAbsolutePath();
-    }
-    
-    public File getBaseDir() {
-        return basedir;
-    }
-    
-    public void prepareForMasterUse() {
-        if (doneFirstContentiousWrite.get())
-            return;
-        synchronized (this) {
-            if (doneFirstContentiousWrite.get())
-                return;
-            try {
-                if (deferredBackupNeeded) {
-                    // defer backup and path creation until first write
-                    // this way if node is standby or auto, the backup is not created superfluously
-
-                    File backup = backupDirByCopying(basedir);
-                    log.info("Persistence deferred backup, directory "+basedir+" backed up to "+backup.getAbsolutePath());
-
-                    deferredBackupNeeded = false;
-                }
-            } catch (Exception e) {
-                throw Exceptions.propagate(e);
-            }
-            doneFirstContentiousWrite.getAndSet(true);
-        }
-    }
-    
-    @Override
-    public void createSubPath(String subPath) {
-        if (!prepared) throw new IllegalStateException("Not yet prepared: "+this);
-        
-        File dir = new File(getBaseDir(), subPath);
-        if (dir.mkdir()) {
-            try {
-                FileUtil.setFilePermissionsTo700(dir);
-            } catch (IOException e) {
-                log.warn("Unable to set sub-directory permissions to 700 (continuing): "+dir);
-            }
-        } else {
-            if (!dir.exists())
-                throw new IllegalStateException("Cannot create "+dir+"; call returned false");
-        }
-        checkPersistenceDirAccessible(dir);
-    }
-
-    @Override
-    public StoreObjectAccessor newAccessor(String path) {
-        if (!prepared) throw new IllegalStateException("Not yet prepared: "+this);
-        
-        String tmpExt = ".tmp";
-        if (mgmt!=null && mgmt.getManagementNodeId()!=null) tmpExt = "."+mgmt.getManagementNodeId()+tmpExt;
-        return new FileBasedStoreObjectAccessor(new File(Os.mergePaths(getBaseDir().getAbsolutePath(), path)), tmpExt);
-    }
-
-    @Override
-    public List<String> listContentsWithSubPath(final String parentSubPath) {
-        if (!prepared) throw new IllegalStateException("Not yet prepared: "+this);
-        
-        Preconditions.checkNotNull(parentSubPath);
-        File subPathDir = new File(basedir, parentSubPath);
-
-        FileFilter fileFilter = new FileFilter() {
-            @Override public boolean accept(File file) {
-                // An inclusion filter would be safer than exclusion
-                return !file.getName().endsWith(".tmp") && !file.getName().endsWith(".swp");
-            }
-        };
-        File[] subPathDirFiles = subPathDir.listFiles(fileFilter);
-        if (subPathDirFiles==null) return ImmutableList.<String>of();
-        return FluentIterable.from(Arrays.asList(subPathDirFiles))
-                .transform(new Function<File, String>() {
-                    @Nullable
-                    @Override
-                    public String apply(@Nullable File input) {
-                        return format("%s/%s", parentSubPath, input.getName());
-                    }
-                }).toList();
-    }
-
-    @Override
-    public void close() {
-        executor.shutdown();
-        try {
-            executor.awaitTermination(SHUTDOWN_TIMEOUT_MS, TimeUnit.MILLISECONDS);
-        } catch (InterruptedException e) {
-            throw Exceptions.propagate(e);
-        }
-    }
-
-    @Override
-    public String toString() {
-        return Objects.toStringHelper(this).add("basedir", basedir).toString();
-    }
-
-    @Override
-    public void injectManagementContext(ManagementContext mgmt) {
-        if (this.mgmt!=null && !this.mgmt.equals(mgmt))
-            throw new IllegalStateException("Cannot change mgmt context of "+this);
-        this.mgmt = mgmt;
-    }
-    
-    @Override
-    public void prepareForSharedUse(@Nullable PersistMode persistMode, HighAvailabilityMode haMode) {
-        if (mgmt==null) throw new NullPointerException("Must inject ManagementContext before preparing "+this);
-        
-        if (persistMode==null || persistMode==PersistMode.DISABLED) {
-            // TODO is this check needed? shouldn't come here now without persistence on.
-            prepared = true;
-            return;
-        }
-        
-        @SuppressWarnings("deprecation")
-        Boolean backups = mgmt.getConfig().getConfig(BrooklynServerConfig.PERSISTENCE_BACKUPS_REQUIRED);
-        if (Boolean.TRUE.equals(backups)) {
-            log.warn("Using legacy backup for "+this+"; functionality will be removed in future versions, in favor of promotion/demotion-specific backups to a configurable backup location.");
-        }
-        // default backups behaviour here changed to false, Nov 2014, because these backups are now legacy;
-        // we prefer the made when persistence is enabled, using routines in BrooklynPersistenceUtils
-        if (backups==null) backups = false; 
-
-        File dir = getBaseDir();
-        try {
-            String persistencePath = dir.getAbsolutePath();
-
-            switch (persistMode) {
-            case CLEAN:
-                if (dir.exists()) {
-                    checkPersistenceDirAccessible(dir);
-                    try {
-                        if (backups) {
-                            File old = backupDirByMoving(dir);
-                            log.info("Persistence mode CLEAN, directory "+persistencePath+" backed up to "+old.getAbsolutePath());
-                        } else {
-                            deleteCompletely();
-                            log.info("Persistence mode CLEAN, directory "+persistencePath+" deleted");
-                        }
-                    } catch (IOException e) {
-                        throw new FatalConfigurationRuntimeException("Error using existing persistence directory "+dir.getAbsolutePath(), e);
-                    }
-                } else {
-                    log.debug("Persistence mode CLEAN, directory "+persistencePath+", no previous state");
-                }
-                break;
-            case REBIND:
-                checkPersistenceDirAccessible(dir);
-                checkPersistenceDirNonEmpty(dir);
-                try {
-                    if (backups) {
-                        if (haMode==HighAvailabilityMode.MASTER) {
-                            File backup = backupDirByCopying(dir);
-                            log.info("Persistence mode REBIND, directory "+persistencePath+" backed up to "+backup.getAbsolutePath());                            
-                        } else {
-                            deferredBackupNeeded = true;
-                        }
-                    }
-                } catch (IOException e) {
-                    throw new FatalConfigurationRuntimeException("Error backing up persistence directory "+dir.getAbsolutePath(), e);
-                }
-                break;
-            case AUTO:
-                if (dir.exists()) {
-                    checkPersistenceDirAccessible(dir);
-                }
-                if (dir.exists() && !isMementoDirExistButEmpty(dir)) {
-                    try {
-                        if (backups) {
-                            if (haMode==HighAvailabilityMode.MASTER) {
-                                File backup = backupDirByCopying(dir);
-                                log.info("Persistence mode REBIND, directory "+persistencePath+" backed up to "+backup.getAbsolutePath());                            
-                            } else {
-                                deferredBackupNeeded = true;
-                            }
-                        }
-                    } catch (IOException e) {
-                        throw new FatalConfigurationRuntimeException("Error backing up persistence directory "+dir.getAbsolutePath(), e);
-                    }
-                } else {
-                    log.debug("Persistence mode AUTO, directory "+persistencePath+", no previous state");
-                }
-                break;
-            default:
-                throw new FatalConfigurationRuntimeException("Unexpected persist mode "+persistMode+"; modified during initialization?!");
-            };
-
-            if (!dir.exists()) {
-                boolean success = dir.mkdirs();
-                if (success) {
-                    FileUtil.setFilePermissionsTo700(dir);
-                } else {
-                    throw new FatalConfigurationRuntimeException("Failed to create persistence directory "+dir);
-                }
-            }
-
-        } catch (Exception e) {
-            throw Exceptions.propagate(e);
-        }
-        
-        prepared = true;        
-    }
-
-    protected File checkPersistenceDirPlausible(File dir) {
-        checkNotNull(dir, "directory");
-        if (!dir.exists()) return dir;
-        if (dir.isFile()) throw new FatalConfigurationRuntimeException("Invalid persistence directory" + dir + ": must not be a file");
-        if (!(dir.canRead() && dir.canWrite())) throw new FatalConfigurationRuntimeException("Invalid persistence directory" + dir + ": " +
-                (!dir.canRead() ? "not readable" :
-                        (!dir.canWrite() ? "not writable" : "unknown reason")));
-        return dir;
-    }
-
-    protected void checkPersistenceDirAccessible(File dir) {
-        if (!(dir.exists() && dir.isDirectory() && dir.canRead() && dir.canWrite())) {
-            FatalConfigurationRuntimeException problem = new FatalConfigurationRuntimeException("Invalid persistence directory " + dir + ": " +
-                    (!dir.exists() ? "does not exist" :
-                            (!dir.isDirectory() ? "not a directory" :
-                                    (!dir.canRead() ? "not readable" :
-                                            (!dir.canWrite() ? "not writable" : "unknown reason")))));
-            log.debug("Invalid persistence directory "+dir+" (rethrowing): "+problem, problem);
-        } else {
-            log.debug("Created dir {} for {}", dir, this);
-        }
-    }
-
-    protected void checkPersistenceDirNonEmpty(File persistenceDir) {
-        FatalConfigurationRuntimeException problem;
-        if (!persistenceDir.exists()) {
-            problem = new FatalConfigurationRuntimeException("Invalid persistence directory "+persistenceDir+" because directory does not exist");
-            log.debug("Invalid persistence directory "+persistenceDir+" (rethrowing): "+problem, problem);
-            throw problem;
-        } if (isMementoDirExistButEmpty(persistenceDir)) {
-            problem = new FatalConfigurationRuntimeException("Invalid persistence directory "+persistenceDir+" because directory is empty");
-            log.debug("Invalid persistence directory "+persistenceDir+" (rethrowing): "+problem, problem);
-            throw problem;
-        }
-    }
-
-    protected File backupDirByCopying(File dir) throws IOException, InterruptedException {
-        File parentDir = dir.getParentFile();
-        String simpleName = dir.getName();
-        String timestamp = new SimpleDateFormat("yyyyMMdd-hhmmssSSS").format(new Date());
-        File backupDir = new File(parentDir, simpleName+"."+timestamp+".bak");
-        
-        FileUtil.copyDir(dir, backupDir);
-        FileUtil.setFilePermissionsTo700(backupDir);
-        
-        return backupDir;
-    }
-
-    protected File backupDirByMoving(File dir) throws InterruptedException, IOException {
-        File parentDir = dir.getParentFile();
-        String simpleName = dir.getName();
-        String timestamp = new SimpleDateFormat("yyyyMMdd-hhmmssSSS").format(new Date());
-        File newDir = new File(parentDir, simpleName+"."+timestamp+".bak");
-
-        FileUtil.moveDir(dir, newDir);
-        return newDir;
-    }
-
-    private static boolean WARNED_ON_NON_ATOMIC_FILE_UPDATES = false; 
-    /** 
-     * Attempts an fs level atomic move then fall back to pure java rename.
-     * Assumes files are on same mount point.
-     * <p>
-     * TODO Java 7 gives an atomic Files.move() which would be preferred.
-     */
-    static void moveFile(File srcFile, File destFile) throws IOException, InterruptedException {
-        // Try rename first - it is a *much* cheaper call than invoking a system call in Java. 
-        // However, rename is not guaranteed cross platform to succeed if the destination exists,
-        // and not guaranteed to be atomic, but it usually seems to do the right thing...
-        boolean result;
-        result = srcFile.renameTo(destFile);
-        if (result) {
-            if (log.isTraceEnabled()) log.trace("java rename of {} to {} completed", srcFile, destFile);
-            return;
-        }
-        
-        if (!Os.isMicrosoftWindows()) {
-            // this command, if it succeeds, is guaranteed to be atomic, and it will usually overwrite
-            String cmd = "mv '"+srcFile.getAbsolutePath()+"' '"+destFile.getAbsolutePath()+"'";
-            
-            int exitStatus = new ProcessTool().execCommands(MutableMap.<String,String>of(), MutableList.of(cmd), null);
-            // prefer the above to the below because it wraps it in the appropriate bash
-//            Process proc = Runtime.getRuntime().exec(cmd);
-//            result = proc.waitFor();
-            
-            if (log.isTraceEnabled()) log.trace("FS move of {} to {} completed, code {}", new Object[] { srcFile, destFile, exitStatus });
-            if (exitStatus == 0) return;
-        }
-        
-        // finally try a delete - but explicitly warn this is not going to be atomic
-        // so if another node reads it might see no master
-        if (!WARNED_ON_NON_ATOMIC_FILE_UPDATES) {
-            WARNED_ON_NON_ATOMIC_FILE_UPDATES = true;
-            log.warn("Unable to perform atomic file update ("+srcFile+" to "+destFile+"); file system not recommended for production HA/DR");
-        }
-        destFile.delete();
-        result = srcFile.renameTo(destFile);
-        if (log.isTraceEnabled()) log.trace("java delete and rename of {} to {} completed, code {}", new Object[] { srcFile, destFile, result });
-        if (result) 
-            return;
-        Files.copy(srcFile, destFile);
-        srcFile.delete();
-        throw new IOException("Could not move "+destFile+" to "+srcFile);
-    }
-    
-    /**
-     * True if directory exists, but is entirely empty, or only contains empty directories.
-     */
-    static boolean isMementoDirExistButEmpty(String dir) {
-        return isMementoDirExistButEmpty(new File(dir));
-    }
-    
-    static boolean isMementoDirExistButEmpty(File dir) {
-        if (!dir.exists()) return false;
-        File[] contents = dir.listFiles();
-        if (contents == null) return false;
-        
-        for (File sub : contents) {
-            if (sub.isFile()) return false;
-            if (sub.isDirectory() && sub.listFiles().length > 0) return false;
-        }
-        return true;
-    }
-
-    @Override
-    public void deleteCompletely() {
-        deleteCompletely(getBaseDir());
-    }
-    
-    public static void deleteCompletely(File d) {
-        DeletionResult result = Os.deleteRecursively(d);
-        if (!result.wasSuccessful())
-            log.warn("Unable to delete persistence dir "+d);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/FileBasedStoreObjectAccessor.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/FileBasedStoreObjectAccessor.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/FileBasedStoreObjectAccessor.java
deleted file mode 100644
index 55af3bc..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/FileBasedStoreObjectAccessor.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Date;
-
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.io.FileUtil;
-import org.apache.brooklyn.util.text.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Charsets;
-import com.google.common.base.Objects;
-import com.google.common.base.Throwables;
-import com.google.common.io.Files;
-
-/**
- * Reads/writes to a file. This impl does it immediately, with no synchronisation.
- * Callers should wrap in {@link StoreObjectAccessorLocking} if multiple threads may be accessing this.
- *
- * @author aled
- */
-public class FileBasedStoreObjectAccessor implements PersistenceObjectStore.StoreObjectAccessor {
-    private static final Logger LOG = LoggerFactory.getLogger(FileBasedStoreObjectAccessor.class);
-
-    public FileBasedStoreObjectAccessor(File file, String tmpExtension) {
-        this.file = file;
-        this.tmpFile = new File(file.getParentFile(), file.getName()+(Strings.isBlank(tmpExtension) ? ".tmp" : tmpExtension));
-    }
-
-    private final File file;
-    private final File tmpFile;
-    
-    @Override
-    public String get() {
-        try {
-            if (!exists()) return null;
-            return Files.asCharSource(file, Charsets.UTF_8).read();
-        } catch (IOException e) {
-            throw Throwables.propagate(e);
-        }
-    }
-
-    @Override
-    public byte[] getBytes() {
-        try {
-            if (!exists()) return null;
-            return Files.asByteSource(file).read();
-        } catch (IOException e) {
-            throw Throwables.propagate(e);
-        }
-    }
-
-    @Override
-    public boolean exists() {
-        return file.exists();
-    }
-
-    // Setting permissions to 600 reduces objectAccessor.put performance from about 5000 per second to 3000 per second
-    // in java 6. With Java 7's Files.setPosixFilePermissions, this might well improve.
-    @Override
-    public void put(String val) {
-        try {
-            if (val==null) val = "";
-            FileUtil.setFilePermissionsTo600(tmpFile);
-            Files.write(val, tmpFile, Charsets.UTF_8);
-            FileBasedObjectStore.moveFile(tmpFile, file);
-        } catch (IOException e) {
-            throw Exceptions.propagate(e);
-        } catch (InterruptedException e) {
-            throw Exceptions.propagate(e);
-        }
-    }
-
-    @Override
-    public void append(String val) {
-        try {
-            if (val==null) val = "";
-            FileUtil.setFilePermissionsTo600(file);
-            Files.append(val, file, Charsets.UTF_8);
-            
-        } catch (IOException e) {
-            throw Exceptions.propagate(e);
-        }
-    }
-
-    @Override
-    public void delete() {
-        if (!file.delete()) {
-            if (!file.exists()) {
-                LOG.debug("Unable to delete " + file.getAbsolutePath() + ". Probably did not exist.");
-            } else {
-                LOG.warn("Unable to delete " + file.getAbsolutePath() + ". Probably still locked.");
-            }
-        }
-        if (tmpFile.exists() && !tmpFile.delete()) {
-            // tmpFile is probably already deleted, so don't even log debug if it does not exist
-            LOG.warn("Unable to delete " + tmpFile.getAbsolutePath() + ". Probably still locked.");
-        }
-    }
-
-    @Override
-    public Date getLastModifiedDate() {
-        long result = file.lastModified();
-        if (result==0) return null;
-        return new Date(result);
-    }
-    
-    @Override
-    public String toString() {
-        return Objects.toStringHelper(this).add("file", file).toString();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/LocationWithObjectStore.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/LocationWithObjectStore.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/LocationWithObjectStore.java
deleted file mode 100644
index a3fcab2..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/LocationWithObjectStore.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-/** Marker interface for locations which can create a {@link PersistenceObjectStore} */
-public interface LocationWithObjectStore {
-
-    /** Creates a {@link PersistenceObjectStore} pointed at the given container/directory. */
-    public PersistenceObjectStore newPersistenceObjectStore(String container);
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/MementoSerializer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/MementoSerializer.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/MementoSerializer.java
deleted file mode 100644
index 54680c6..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/MementoSerializer.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import org.apache.brooklyn.api.mgmt.ha.ManagementNodeSyncRecord;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMemento;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoPersister.LookupContext;
-
-/** Serializes the given object; it is often used with {@link BrooklynMemento} for persisting and restoring,
- * though it can be used for any object (and is also used for the {@link ManagementNodeSyncRecord} instances) */
-public interface MementoSerializer<T> {
-    
-    public static final MementoSerializer<String> NOOP = new MementoSerializer<String>() {
-        @Override
-        public String toString(String memento) {
-            return memento;
-        }
-        @Override
-        public String fromString(String string) {
-            return string;
-        }
-        @Override
-        public void setLookupContext(LookupContext lookupContext) {
-            // no-op
-        }
-        @Override
-        public void unsetLookupContext() {
-            // no-op
-        }
-    };
-    
-    String toString(T memento);
-    T fromString(String string);
-    void setLookupContext(LookupContext lookupContext);
-    void unsetLookupContext();
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/PersistMode.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/PersistMode.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/PersistMode.java
deleted file mode 100644
index 0056bd2..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/PersistMode.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-public enum PersistMode {
-    DISABLED,
-    AUTO,
-    REBIND,
-    CLEAN;
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/PersistenceActivityMetrics.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/PersistenceActivityMetrics.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/PersistenceActivityMetrics.java
deleted file mode 100644
index 8c36a79..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/PersistenceActivityMetrics.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.time.Duration;
-
-public class PersistenceActivityMetrics {
-    
-    final static int MAX_ERRORS = 200;
-    
-    long count=0, failureCount=0;
-    Long lastSuccessTime, lastDuration, lastFailureTime;
-    List<Map<String,Object>> errorMessages = MutableList.of();
-
-    public void noteSuccess(Duration duration) {
-        count++;
-        lastSuccessTime = System.currentTimeMillis();
-        lastDuration = duration.toMilliseconds();
-    }
-    
-    public void noteFailure(Duration duration) {
-        count++;
-        failureCount++;
-        lastFailureTime = System.currentTimeMillis();
-        lastDuration = duration!=null ? duration.toMilliseconds() : -1;
-    }
-
-    public void noteError(String error) {
-        noteErrorObject(error);
-    }
-    
-    public void noteError(List<?> error) {
-        noteErrorObject(error);
-    }
-    
-    /** error should be json-serializable; exceptions can be problematic */
-    protected synchronized void noteErrorObject(Object error) {
-        errorMessages.add(0, MutableMap.<String,Object>of("error", error, "timestamp", System.currentTimeMillis()));
-        while (errorMessages.size() > MAX_ERRORS) {
-            errorMessages.remove(errorMessages.size()-1);
-        }
-    }
-    
-    public synchronized Map<String,Object> asMap() {
-        Map<String,Object> result = MutableMap.of();
-        result.put("count", count);
-        result.put("lastSuccessTimeUtc", lastSuccessTime);
-        result.put("lastSuccessTimeMillisSince", since(lastSuccessTime));
-        result.put("lastDuration", lastDuration);
-        result.put("failureCount", failureCount);
-        result.put("lastFailureTimeUtc", lastFailureTime);
-        result.put("lastFailureTimeMillisSince", since(lastFailureTime));
-        result.put("errorMessages", MutableList.copyOf(errorMessages));
-        return result;
-    }
-
-    private Long since(Long time) {
-        if (time==null) return null;
-        return System.currentTimeMillis() - time;
-    }
-    
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/PersistenceObjectStore.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/PersistenceObjectStore.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/PersistenceObjectStore.java
deleted file mode 100644
index 16bf543..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/PersistenceObjectStore.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import java.util.Date;
-import java.util.List;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.locks.ReadWriteLock;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.util.time.Duration;
-
-import com.google.common.annotations.Beta;
-
-/**
- * Interface for working with persistence targets, including file system and jclouds object stores.
- * @author Andrea Turli
- */
-public interface PersistenceObjectStore {
-
-    /** accessor to an object/item in a {@link PersistenceObjectStore} */
-    public interface StoreObjectAccessor {
-        /** gets the object, or null if not found */
-        String get();
-        byte[] getBytes();
-        boolean exists();
-        void put(String contentsToReplaceOrCreate);
-        void append(String contentsToAppendOrCreate);
-        void delete();
-        // NB: creation date is available for many blobstores but 
-        // not on java.io.File and filesystems, so it is not included here 
-        /** last modified date, null if not supported or does not exist */
-        Date getLastModifiedDate();
-    }
-    public interface StoreObjectAccessorWithLock extends StoreObjectAccessor {
-        /** waits for all currently scheduled write lock operations (puts, appends, and deletes) to complete;
-         * but does not wait on or prevent subsequent modifications.
-         * this is suitable for a model where the caller is managing synchronization.
-         * <p> 
-         * for more complex uses, readers should <code>getLockObject().readLock().lockInterruptibly()</code> 
-         * and ensure they subsequently <code>unlock()</code> it of course. see {@link #getLockObject()}. */
-        void waitForCurrentWrites(Duration timeout) throws InterruptedException, TimeoutException;
-        
-        /** returns the underlying lock in case callers need more complex synchronization control */ 
-        ReadWriteLock getLockObject();
-    }
-
-    /** human-readable name of this object store */
-    public String getSummaryName();
-    
-    /**
-     * Allows a way for an object store to be created ahead of time, and a mgmt context injected.
-     * Currently subsequent changes are not permitted.
-     * <p>
-     * A {@link ManagementContext} must be supplied via constructor or this method before invoking other methods.
-     */
-    @Beta
-    public void injectManagementContext(ManagementContext managementContext);
-    
-    /**
-     * Prepares the persistence store for read use and non-contentious write use,
-     * in particular detecting whether we should clean or register a need for backup etc.
-     * Typically called early in the setup lifecycle, after {@link #injectManagementContext(ManagementContext)},
-     * but before {@link #prepareForMasterUse()}.
-     * <p>
-     * See {@link #prepareForMasterUse()} for discussion of "contentious writes".
-     */
-    @Beta
-    public void prepareForSharedUse(PersistMode persistMode, HighAvailabilityMode highAvailabilityMode);
-
-    /** 
-     * Prepares the persistence store for "contentious writes".
-     * These are defined as those writes which might overwrite important information.
-     * Implementations usually perform backup/versioning of the store if required.
-     * <p>
-     * Caller must call {@link #prepareForSharedUse(PersistMode, HighAvailabilityMode)} first
-     * (and {@link #injectManagementContext(ManagementContext)} before that).
-     * <p>
-     * This is typically invoked "at the last moment" e.g. before the any such write,
-     * mainly in order to prevent backups being made unnecessarily (e.g. if a node is standby,
-     * or if it tries to become master but is not capable),
-     * but also to prevent simultaneous backups which can cause problems with some stores
-     * (only a mgmt who knows he is the master should invoke this).
-     **/
-    @Beta
-    public void prepareForMasterUse();
-    
-    /**
-     * For reading/writing data to the item at the given path.
-     * Note that the accessor is not generally thread safe, usually does not support blocking,
-     * and multiple instances may conflict with each other.
-     * <p>
-     * Clients should wrap in a dedicated {@link StoreObjectAccessorLocking} and share
-     * if multiple threads may be accessing the store.
-     * This method may be changed in future to allow access to a shared locking accessor.
-     */
-    @Beta
-    // TODO requiring clients to wrap and cache accessors is not very nice API, 
-    // better would be to do caching here probably,
-    // but we've already been doing it this way above for now (Jun 2014)
-    StoreObjectAccessor newAccessor(String path);
-
-    /** create the directory at the given subPath relative to the base of this store */
-    void createSubPath(String subPath);
-
-    /**
-     * Lists the paths of objects contained at the given path, including the subpath.
-     * For example, if a file-based ObjectStore is configured to write to file://path/to/root/
-     * then parentSubPath=entities would return the contents of /path/to/root/entities/, such as
-     * [entities/e1, entities/e2, entities/e3].
-     * The returned paths values are usable in calls to {@link #newAccessor(String)}.
-     */
-    List<String> listContentsWithSubPath(String subPath);
-
-    /** Entirely delete the contents of this persistence location.
-     * Use with care, primarily in tests. This will recursively wipe the indicated location. */ 
-    public void deleteCompletely();
-    
-    /**
-     * Closes all resources used by this ObjectStore. No subsequent calls should be made to the ObjectStore;
-     * behaviour of such calls is undefined but likely to throw exceptions.
-     */
-    void close();
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/RetryingMementoSerializer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/RetryingMementoSerializer.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/RetryingMementoSerializer.java
deleted file mode 100644
index 86fc359..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/RetryingMementoSerializer.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoPersister.LookupContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class RetryingMementoSerializer<T> implements MementoSerializer<T> {
-    
-    private static final Logger LOG = LoggerFactory.getLogger(RetryingMementoSerializer.class);
-    
-    private final MementoSerializer<T> delegate;
-    private final int maxAttempts;
-    
-    public RetryingMementoSerializer(MementoSerializer<T> delegate, int maxAttempts) {
-        this.delegate = checkNotNull(delegate, "delegate");
-        this.maxAttempts = maxAttempts;
-        if (maxAttempts < 1) throw new IllegalArgumentException("Max attempts must be at least 1, but was "+maxAttempts);
-    }
-    
-    @Override
-    public String toString(T memento) {
-        RuntimeException lastException = null;
-        int attempt = 0;
-        do {
-            attempt++;
-            try {
-                String result = delegate.toString(memento);
-                if (attempt>1) 
-                    LOG.info("Success following previous serialization error");
-                return result;
-            } catch (RuntimeException e) {
-                LOG.warn("Error serializing memento (attempt "+attempt+" of "+maxAttempts+") for "+memento+
-                        "; expected sometimes if attribute value modified", e);
-                lastException = e;
-            }
-        } while (attempt < maxAttempts);
-        
-        throw lastException;
-    }
-    
-    @Override
-    public T fromString(String string) {
-        if (string==null)
-            return null;
-        
-        RuntimeException lastException = null;
-        int attempt = 0;
-        do {
-            attempt++;
-            try {
-                T result = delegate.fromString(string);
-                if (attempt>1)
-                    LOG.info("Success following previous deserialization error, got: "+result);
-                return result;
-            } catch (RuntimeException e) {
-                // trying multiple times only makes sense for a few errors (namely ConcModExceptions); perhaps deprecate that strategy?
-                LOG.warn("Error deserializing memento (attempt "+attempt+" of "+maxAttempts+"): "+e, e);
-                if (attempt==1) LOG.debug("Memento which was not deserialized is:\n"+string);
-                lastException = e;
-            }
-        } while (attempt < maxAttempts);
-        
-        throw lastException;
-    }
-
-    @Override
-    public void setLookupContext(LookupContext lookupContext) {
-        delegate.setLookupContext(lookupContext);
-    }
-
-    @Override
-    public void unsetLookupContext() {
-        delegate.unsetLookupContext();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/StoreObjectAccessorLocking.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/StoreObjectAccessorLocking.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/StoreObjectAccessorLocking.java
deleted file mode 100644
index a8517e3..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/persister/StoreObjectAccessorLocking.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.mgmt.rebind.persister;
-
-import java.util.Comparator;
-import java.util.Date;
-import java.util.Set;
-import java.util.concurrent.ConcurrentSkipListSet;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-import org.apache.brooklyn.core.mgmt.rebind.persister.PersistenceObjectStore.StoreObjectAccessor;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.javalang.JavaClassNames;
-import org.apache.brooklyn.util.time.Duration;
-
-/** Wraps access to an object (the delegate {@link StoreObjectAccessor} 
- * in a guarded read-write context such that callers will be blocked if another thread
- * is accessing the object in an incompatible way (e.g. trying to read when someone is writing).
- * See {@link ReadWriteLock}.
- * <p>
- * This has no visibility or control over other access to the delegate or underlying object, of course.
- * It can only affect callers coming through this wrapper instance.  Thus callers must share instances
- * of this class for a given item.
- * <p>
- * No locking is done with respect to {@link #getLastModifiedDate()}. 
- **/
-public class StoreObjectAccessorLocking implements PersistenceObjectStore.StoreObjectAccessorWithLock {
-
-    protected static class ThreadComparator implements Comparator<Thread> {
-        @Override
-        public int compare(Thread o1, Thread o2) {
-            if (o1.getId()<o2.getId()) return -1;
-            if (o1.getId()>o2.getId()) return 1;
-            return 0;
-        }
-    }
-    
-    ReadWriteLock lock = new ReentrantReadWriteLock(true);
-    Set<Thread> queuedReaders = new ConcurrentSkipListSet<Thread>(new ThreadComparator());
-    Set<Thread> queuedWriters = new ConcurrentSkipListSet<Thread>(new ThreadComparator());
-    
-    final PersistenceObjectStore.StoreObjectAccessor delegate;
-    
-    public StoreObjectAccessorLocking(PersistenceObjectStore.StoreObjectAccessor delegate) {
-        this.delegate = delegate;
-    }
-    
-    @Override
-    public String get() {
-        try {
-            queuedReaders.add(Thread.currentThread());
-            lock.readLock().lockInterruptibly();
-            try {
-                return delegate.get();
-                
-            } finally {
-                lock.readLock().unlock();
-            }
-        } catch (InterruptedException e) {
-            throw Exceptions.propagate(e);
-        } finally {
-            queuedReaders.remove(Thread.currentThread());
-        }
-    }
-
-    @Override
-    public byte[] getBytes() {
-        try {
-            queuedReaders.add(Thread.currentThread());
-            lock.readLock().lockInterruptibly();
-            try {
-                return delegate.getBytes();
-                
-            } finally {
-                lock.readLock().unlock();
-            }
-        } catch (InterruptedException e) {
-            throw Exceptions.propagate(e);
-        } finally {
-            queuedReaders.remove(Thread.currentThread());
-        }
-    }
-
-    @Override
-    public boolean exists() {
-        try {
-            queuedReaders.add(Thread.currentThread());
-            lock.readLock().lockInterruptibly();
-            try {
-                return delegate.exists();
-                
-            } finally {
-                lock.readLock().unlock();
-            }
-        } catch (InterruptedException e) {
-            throw Exceptions.propagate(e);
-        } finally {
-            queuedReaders.remove(Thread.currentThread());
-        }
-    }
-
-    protected boolean hasScheduledPutOrDeleteWithNoRead() {
-        // skip write if there is another write queued and no reader waiting
-        return (!queuedWriters.isEmpty() && queuedReaders.isEmpty());
-    }
-    
-    @Override
-    public void put(String val) {
-        try {
-            queuedWriters.add(Thread.currentThread());
-            lock.writeLock().lockInterruptibly();
-            try {
-                queuedWriters.remove(Thread.currentThread());
-                if (hasScheduledPutOrDeleteWithNoRead()) 
-                    // don't bother writing if someone will write after us and no one is reading
-                    return;
-                delegate.put(val);
-                
-            } finally {
-                lock.writeLock().unlock();
-            }
-        } catch (InterruptedException e) {
-            throw Exceptions.propagate(e);
-        } finally {
-            queuedWriters.remove(Thread.currentThread());
-        }
-    }
-    
-    @Override
-    public void append(String val) {
-        try {
-            lock.writeLock().lockInterruptibly();
-            try {
-                if (hasScheduledPutOrDeleteWithNoRead())
-                    // don't bother appending if someone will write after us and no one is reading
-                    return;
-                
-                delegate.append(val);
-                
-            } finally {
-                lock.writeLock().unlock();
-            }
-        } catch (InterruptedException e) {
-            throw Exceptions.propagate(e);
-        }
-    }
-    
-    @Override
-    public void delete() {
-        try {
-            queuedWriters.add(Thread.currentThread());
-            lock.writeLock().lockInterruptibly();
-            try {
-                queuedWriters.remove(Thread.currentThread());
-                if (hasScheduledPutOrDeleteWithNoRead()) {
-                    // don't bother deleting if someone will write after us and no one is reading
-                    return;
-                }
-                delegate.delete();
-                
-            } finally {
-                lock.writeLock().unlock();
-            }
-        } catch (InterruptedException e) {
-            throw Exceptions.propagate(e);
-        } finally {
-            queuedWriters.remove(Thread.currentThread());
-        }
-    }
-    
-    @Override
-    public void waitForCurrentWrites(Duration timeout) throws InterruptedException, TimeoutException {
-        try {
-            boolean locked = lock.readLock().tryLock(timeout.toMillisecondsRoundingUp(), TimeUnit.MILLISECONDS);
-            if (locked) {
-                lock.readLock().unlock();
-            } else {
-                throw new TimeoutException("Timeout waiting for writes of "+delegate+" after "+timeout);
-            }
-        } catch (InterruptedException e) {
-            throw Exceptions.propagate(e);
-        }
-    }
-    
-    @Override
-    public Date getLastModifiedDate() {
-        return delegate.getLastModifiedDate();
-    }
-
-    @Override
-    public ReadWriteLock getLockObject() {
-        return lock;
-    }
-
-    @Override
-    public String toString() {
-        return JavaClassNames.simpleClassName(this)+":"+delegate.toString();
-    }
-}


[57/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process)

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/BasicLocationRegistry.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/BasicLocationRegistry.java b/core/src/main/java/org/apache/brooklyn/location/core/BasicLocationRegistry.java
new file mode 100644
index 0000000..329c38e
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/BasicLocationRegistry.java
@@ -0,0 +1,489 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.ServiceLoader;
+import java.util.Set;
+
+import org.apache.brooklyn.api.catalog.BrooklynCatalog;
+import org.apache.brooklyn.api.catalog.CatalogItem;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationDefinition;
+import org.apache.brooklyn.api.location.LocationRegistry;
+import org.apache.brooklyn.api.location.LocationResolver;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.config.ConfigMap;
+import org.apache.brooklyn.core.catalog.CatalogPredicates;
+import org.apache.brooklyn.core.config.ConfigPredicates;
+import org.apache.brooklyn.core.config.ConfigUtils;
+import org.apache.brooklyn.core.mgmt.internal.LocalLocationManager;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.guava.Maybe;
+import org.apache.brooklyn.util.guava.Maybe.Absent;
+import org.apache.brooklyn.util.javalang.JavaClassNames;
+import org.apache.brooklyn.util.text.Identifiers;
+import org.apache.brooklyn.util.text.StringEscapes.JavaStringEscapes;
+import org.apache.brooklyn.util.text.WildcardGlobs;
+import org.apache.brooklyn.util.text.WildcardGlobs.PhraseTreatment;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Suppliers;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Sets;
+
+/**
+ * See {@link LocationRegistry} for general description.
+ * <p>
+ * TODO The relationship between the catalog and the location registry is a bit messy.
+ * For all existing code, the location registry is the definitive way to resolve
+ * locations. 
+ * <p>
+ * Any location item added to the catalog must therefore be registered here.
+ * Whenever an item is added to the catalog, it will automatically call 
+ * {@link #updateDefinedLocation(CatalogItem)}. Similarly, when a location
+ * is deleted from the catalog it will call {@link #removeDefinedLocation(CatalogItem)}.
+ * <p>
+ * However, the location item in the catalog has an unparsed blob of YAML, which contains
+ * important things like the type and the config of the location. This is only parsed when 
+ * {@link BrooklynCatalog#createSpec(CatalogItem)} is called. We therefore jump through 
+ * some hoops to wire together the catalog and the registry.
+ * <p>
+ * To add a location to the catalog, and then to resolve a location that is in the catalog, 
+ * it goes through the following steps:
+ * 
+ * <ol>
+ *   <li>Call {@link BrooklynCatalog#addItems(String)}
+ *     <ol>
+ *       <li>This automatically calls {@link #updateDefinedLocation(CatalogItem)}
+ *       <li>A LocationDefinition is creating, using as its id the {@link CatalogItem#getSymbolicName()}.
+ *           The definition's spec is {@code brooklyn.catalog:<symbolicName>:<version>},
+ *     </ol>
+ *   <li>A blueprint can reference the catalog item using its symbolic name, 
+ *       such as the YAML {@code location: my-new-location}.
+ *       (this feels similar to the "named locations").
+ *     <ol>
+ *       <li>This automatically calls {@link #resolve(String)}.
+ *       <li>The LocationDefinition is found by lookig up this name.
+ *       <li>The {@link LocationDefiniton.getSpec()} is retrieved; the right {@link LocationResolver} is
+ *           found for it.
+ *       <li>This uses the {@link CatalogLocationResolver}, because the spec starts with {@code brooklyn.catalog:}.
+ *       <li>This resolver extracts from the spec the <symobolicName>:<version>, and looks up the 
+ *           catalog item using {@link BrooklynCatalog#getCatalogItem(String, String)}.
+ *       <li>It then creates a {@link LocationSpec} by calling {@link BrooklynCatalog#createSpec(CatalogItem)}.
+ *         <ol>
+ *           <li>This first tries to use the type (that is in the YAML) as a simple Java class.
+ *           <li>If that fails, it will resolve the type using {@link #resolve(String, Boolean, Map)}, which
+ *               returns an actual location object.
+ *           <li>It extracts from that location object the appropriate metadata to create a {@link LocationSpec},
+ *               returns the spec and discards the location object.
+ *         </ol>
+ *       <li>The resolver creates the {@link Location} from the {@link LocationSpec}
+ *     </ol>
+ * </ol>
+ * 
+ * There is no concept of a location version in this registry. The version
+ * in the catalog is generally ignored.
+ */
+@SuppressWarnings({"rawtypes","unchecked"})
+public class BasicLocationRegistry implements LocationRegistry {
+
+    // TODO save / serialize
+    // (we persist live locations, ie those in the LocationManager, but not "catalog" locations, ie those in this Registry)
+    
+    public static final Logger log = LoggerFactory.getLogger(BasicLocationRegistry.class);
+
+    /**
+     * Splits a comma-separated list of locations (names or specs) into an explicit list.
+     * The splitting is very careful to handle commas embedded within specs, to split correctly.
+     */
+    public static List<String> expandCommaSeparateLocations(String locations) {
+        return WildcardGlobs.getGlobsAfterBraceExpansion("{"+locations+"}", false, PhraseTreatment.INTERIOR_NOT_EXPANDABLE, PhraseTreatment.INTERIOR_NOT_EXPANDABLE);
+        // don't do this, it tries to expand commas inside parentheses which is not good!
+//        QuotedStringTokenizer.builder().addDelimiterChars(",").buildList((String)id);
+    }
+
+    private final ManagementContext mgmt;
+    /** map of defined locations by their ID */
+    private final Map<String,LocationDefinition> definedLocations = new LinkedHashMap<String, LocationDefinition>();
+
+    protected final Map<String,LocationResolver> resolvers = new LinkedHashMap<String, LocationResolver>();
+
+    private final Set<String> specsWarnedOnException = Sets.newConcurrentHashSet();
+
+    public BasicLocationRegistry(ManagementContext mgmt) {
+        this.mgmt = checkNotNull(mgmt, "mgmt");
+        findServices();
+        updateDefinedLocations();
+    }
+
+    protected void findServices() {
+        ServiceLoader<LocationResolver> loader = ServiceLoader.load(LocationResolver.class, mgmt.getCatalogClassLoader());
+        MutableList<LocationResolver> loadedResolvers;
+        try {
+            loadedResolvers = MutableList.copyOf(loader);
+        } catch (Throwable e) {
+            log.warn("Error loading resolvers (rethrowing): "+e);
+            throw Exceptions.propagate(e);
+        }
+        
+        for (LocationResolver r: loadedResolvers) {
+            registerResolver(r);
+        }
+        if (log.isDebugEnabled()) log.debug("Location resolvers are: "+resolvers);
+        if (resolvers.isEmpty()) log.warn("No location resolvers detected: is src/main/resources correctly included?");
+    }
+
+    /** Registers the given resolver, invoking {@link LocationResolver#init(ManagementContext)} on the argument
+     * and returning true, unless the argument indicates false for {@link LocationResolver.EnableableLocationResolver#isEnabled()} */
+    public boolean registerResolver(LocationResolver r) {
+        r.init(mgmt);
+        if (r instanceof LocationResolver.EnableableLocationResolver) {
+            if (!((LocationResolver.EnableableLocationResolver)r).isEnabled()) {
+                return false;
+            }
+        }
+        resolvers.put(r.getPrefix(), r);
+        return true;
+    }
+    
+    @Override
+    public Map<String,LocationDefinition> getDefinedLocations() {
+        synchronized (definedLocations) {
+            return ImmutableMap.<String,LocationDefinition>copyOf(definedLocations);
+        }
+    }
+    
+    @Override
+    public LocationDefinition getDefinedLocationById(String id) {
+        return definedLocations.get(id);
+    }
+
+    @Override
+    public LocationDefinition getDefinedLocationByName(String name) {
+        synchronized (definedLocations) {
+            for (LocationDefinition l: definedLocations.values()) {
+                if (l.getName().equals(name)) return l;
+            }
+            return null;
+        }
+    }
+
+    @Override
+    public void updateDefinedLocation(LocationDefinition l) {
+        synchronized (definedLocations) { 
+            definedLocations.put(l.getId(), l); 
+        }
+    }
+
+    /**
+     * Converts the given item from the catalog into a LocationDefinition, and adds it
+     * to the registry (overwriting anything already registered with the id
+     * {@link CatalogItem#getCatalogItemId()}.
+     */
+    public void updateDefinedLocation(CatalogItem<Location, LocationSpec<?>> item) {
+        String id = item.getCatalogItemId();
+        String symbolicName = item.getSymbolicName();
+        String spec = CatalogLocationResolver.NAME + ":" + id;
+        Map<String, Object> config = ImmutableMap.<String, Object>of();
+        BasicLocationDefinition locDefinition = new BasicLocationDefinition(symbolicName, symbolicName, spec, config);
+        
+        updateDefinedLocation(locDefinition);
+    }
+
+    public void removeDefinedLocation(CatalogItem<Location, LocationSpec<?>> item) {
+        removeDefinedLocation(item.getSymbolicName());
+    }
+    
+    @Override
+    public void removeDefinedLocation(String id) {
+        LocationDefinition removed;
+        synchronized (definedLocations) { 
+            removed = definedLocations.remove(id);
+        }
+        if (removed == null && log.isDebugEnabled()) {
+            log.debug("{} was asked to remove location with id {} but no such location was registered", this, id);
+        }
+    }
+    
+    public void updateDefinedLocations() {
+        synchronized (definedLocations) {
+            // first read all properties starting  brooklyn.location.named.xxx
+            // (would be nice to move to a better way, e.g. yaml, then deprecate this approach, but first
+            // we need ability/format for persisting named locations, and better support for adding+saving via REST/GUI)
+            int count = 0; 
+            String NAMED_LOCATION_PREFIX = "brooklyn.location.named.";
+            ConfigMap namedLocationProps = mgmt.getConfig().submap(ConfigPredicates.startingWith(NAMED_LOCATION_PREFIX));
+            for (String k: namedLocationProps.asMapWithStringKeys().keySet()) {
+                String name = k.substring(NAMED_LOCATION_PREFIX.length());
+                // If has a dot, then is a sub-property of a named location (e.g. brooklyn.location.named.prod1.user=bob)
+                if (!name.contains(".")) {
+                    // this is a new named location
+                    String spec = (String) namedLocationProps.asMapWithStringKeys().get(k);
+                    // make up an ID
+                    String id = Identifiers.makeRandomId(8);
+                    Map<String, Object> config = ConfigUtils.filterForPrefixAndStrip(namedLocationProps.asMapWithStringKeys(), k+".");
+                    definedLocations.put(id, new BasicLocationDefinition(id, name, spec, config));
+                    count++;
+                }
+            }
+            if (log.isDebugEnabled())
+                log.debug("Found "+count+" defined locations from properties (*.named.* syntax): "+definedLocations.values());
+            if (getDefinedLocationByName("localhost")==null && !BasicOsDetails.Factory.newLocalhostInstance().isWindows()
+                    && LocationConfigUtils.isEnabled(mgmt, "brooklyn.location.localhost")) {
+                log.debug("Adding a defined location for localhost");
+                // add 'localhost' *first*
+                ImmutableMap<String, LocationDefinition> oldDefined = ImmutableMap.copyOf(definedLocations);
+                definedLocations.clear();
+                String id = Identifiers.makeRandomId(8);
+                definedLocations.put(id, localhost(id));
+                definedLocations.putAll(oldDefined);
+            }
+            
+            for (CatalogItem<Location, LocationSpec<?>> item : mgmt.getCatalog().getCatalogItems(CatalogPredicates.IS_LOCATION)) {
+                updateDefinedLocation(item);
+                count++;
+            }
+        }
+    }
+    
+    @VisibleForTesting
+    void disablePersistence() {
+        // persistence isn't enabled yet anyway (have to manually save things,
+        // defining the format and file etc)
+    }
+
+    protected static BasicLocationDefinition localhost(String id) {
+        return new BasicLocationDefinition(id, "localhost", "localhost", null);
+    }
+    
+    /** to catch circular references */
+    protected ThreadLocal<Set<String>> specsSeen = new ThreadLocal<Set<String>>();
+    
+    @Override @Deprecated
+    public boolean canMaybeResolve(String spec) {
+        return getSpecResolver(spec) != null;
+    }
+
+    @Override
+    public final Location resolve(String spec) {
+        return resolve(spec, true, null).get();
+    }
+    
+    @Override @Deprecated
+    public final Location resolveIfPossible(String spec) {
+        if (!canMaybeResolve(spec)) return null;
+        return resolve(spec, null, null).orNull();
+    }
+    
+    @Deprecated /** since 0.7.0 not used */
+    public final Maybe<Location> resolve(String spec, boolean manage) {
+        return resolve(spec, manage, null);
+    }
+    
+    public Maybe<Location> resolve(String spec, Boolean manage, Map locationFlags) {
+        try {
+            locationFlags = MutableMap.copyOf(locationFlags);
+            if (manage!=null) {
+                locationFlags.put(LocalLocationManager.CREATE_UNMANAGED, !manage);
+            }
+            
+            Set<String> seenSoFar = specsSeen.get();
+            if (seenSoFar==null) {
+                seenSoFar = new LinkedHashSet<String>();
+                specsSeen.set(seenSoFar);
+            }
+            if (seenSoFar.contains(spec))
+                return Maybe.absent(Suppliers.ofInstance(new IllegalStateException("Circular reference in definition of location '"+spec+"' ("+seenSoFar+")")));
+            seenSoFar.add(spec);
+            
+            LocationResolver resolver = getSpecResolver(spec);
+
+            if (resolver != null) {
+                try {
+                    return Maybe.of(resolver.newLocationFromString(locationFlags, spec, this));
+                } catch (RuntimeException e) {
+                    return Maybe.absent(Suppliers.ofInstance(e));
+                }
+            }
+
+            // problem: but let's ensure that classpath is sane to give better errors in common IDE bogus case;
+            // and avoid repeated logging
+            String errmsg;
+            if (spec == null || specsWarnedOnException.add(spec)) {
+                if (resolvers.get("id")==null || resolvers.get("named")==null) {
+                    log.error("Standard location resolvers not installed, location resolution will fail shortly. "
+                            + "This usually indicates a classpath problem, such as when running from an IDE which "
+                            + "has not properly copied META-INF/services from src/main/resources. "
+                            + "Known resolvers are: "+resolvers.keySet());
+                    errmsg = "Unresolvable location '"+spec+"': "
+                            + "Problem detected with location resolver configuration; "
+                            + resolvers.keySet()+" are the only available location resolvers. "
+                            + "More information can be found in the logs.";
+                } else {
+                    log.debug("Location resolution failed for '"+spec+"' (if this is being loaded it will fail shortly): known resolvers are: "+resolvers.keySet());
+                    errmsg = "Unknown location '"+spec+"': "
+                            + "either this location is not recognised or there is a problem with location resolver configuration.";
+                }
+            } else {
+                // For helpful log message construction: assumes classpath will not suddenly become wrong; might happen with OSGi though!
+                if (log.isDebugEnabled()) log.debug("Location resolution failed again for '"+spec+"' (throwing)");
+                errmsg = "Unknown location '"+spec+"': "
+                        + "either this location is not recognised or there is a problem with location resolver configuration.";
+            }
+
+            return Maybe.absent(Suppliers.ofInstance(new NoSuchElementException(errmsg)));
+
+        } finally {
+            specsSeen.remove();
+        }
+    }
+
+    @Override
+    public final Location resolve(String spec, Map locationFlags) {
+        return resolve(spec, null, locationFlags).get();
+    }
+
+    protected LocationResolver getSpecResolver(String spec) {
+        int colonIndex = spec.indexOf(':');
+        int bracketIndex = spec.indexOf("(");
+        int dividerIndex = (colonIndex < 0) ? bracketIndex : (bracketIndex < 0 ? colonIndex : Math.min(bracketIndex, colonIndex));
+        String prefix = dividerIndex >= 0 ? spec.substring(0, dividerIndex) : spec;
+        LocationResolver resolver = resolvers.get(prefix);
+       
+        if (resolver == null)
+            resolver = getSpecDefaultResolver(spec);
+        
+        return resolver;
+    }
+    
+    protected LocationResolver getSpecDefaultResolver(String spec) {
+        return getSpecFirstResolver(spec, "id", "named", "jclouds");
+    }
+    protected LocationResolver getSpecFirstResolver(String spec, String ...resolversToCheck) {
+        for (String resolverId: resolversToCheck) {
+            LocationResolver resolver = resolvers.get(resolverId);
+            if (resolver!=null && resolver.accepts(spec, this))
+                return resolver;
+        }
+        return null;
+    }
+
+    /** providers default impl for RegistryLocationResolver.accepts */
+    public static boolean isResolverPrefixForSpec(LocationResolver resolver, String spec, boolean argumentRequired) {
+        if (spec==null) return false;
+        if (spec.startsWith(resolver.getPrefix()+":")) return true;
+        if (!argumentRequired && spec.equals(resolver.getPrefix())) return true;
+        return false;
+    }
+
+    @Override
+    public List<Location> resolve(Iterable<?> spec) {
+        List<Location> result = new ArrayList<Location>();
+        for (Object id : spec) {
+            if (id instanceof String) {
+                result.add(resolve((String) id));
+            } else if (id instanceof Location) {
+                result.add((Location) id);
+            } else {
+                if (id instanceof Iterable)
+                    throw new IllegalArgumentException("Cannot resolve '"+id+"' to a location; collections of collections not allowed"); 
+                throw new IllegalArgumentException("Cannot resolve '"+id+"' to a location; unsupported type "+
+                        (id == null ? "null" : id.getClass().getName())); 
+            }
+        }
+        return result;
+    }
+    
+    public List<Location> resolveList(Object l) {
+        if (l==null) l = Collections.emptyList();
+        if (l instanceof String) l = JavaStringEscapes.unwrapJsonishListIfPossible((String)l);
+        if (l instanceof Iterable) return resolve((Iterable<?>)l);
+        throw new IllegalArgumentException("Location list must be supplied as a collection or a string, not "+
+            JavaClassNames.simpleClassName(l)+"/"+l);
+    }
+    
+    @Override
+    public Location resolve(LocationDefinition ld) {
+        return resolve(ld, null, null).get();
+    }
+
+    @Override @Deprecated
+    public Location resolveForPeeking(LocationDefinition ld) {
+        // TODO should clean up how locations are stored, figuring out whether they are shared or not;
+        // or maybe better, the API calls to this might just want to get the LocationSpec objects back
+        
+        // for now we use a 'CREATE_UNMANGED' flag to prevent management (leaks and logging)
+        return resolve(ld, ConfigBag.newInstance().configure(LocalLocationManager.CREATE_UNMANAGED, true).getAllConfig());
+    }
+
+    @Override @Deprecated
+    public Location resolve(LocationDefinition ld, Map<?,?> flags) {
+        return resolveLocationDefinition(ld, flags, null);
+    }
+    
+    /** @deprecated since 0.7.0 not used (and optionalName was ignored anyway) */
+    @Deprecated
+    public Location resolveLocationDefinition(LocationDefinition ld, Map locationFlags, String optionalName) {
+        return resolve(ld, null, locationFlags).get();
+    }
+    
+    public Maybe<Location> resolve(LocationDefinition ld, Boolean manage, Map locationFlags) {
+        ConfigBag newLocationFlags = ConfigBag.newInstance(ld.getConfig())
+            .putAll(locationFlags)
+            .putIfAbsentAndNotNull(LocationInternal.NAMED_SPEC_NAME, ld.getName())
+            .putIfAbsentAndNotNull(LocationInternal.ORIGINAL_SPEC, ld.getName());
+        Maybe<Location> result = resolve(ld.getSpec(), manage, newLocationFlags.getAllConfigRaw());
+        if (result.isPresent()) 
+            return result;
+        throw new IllegalStateException("Cannot instantiate location '"+ld+"' pointing at "+ld.getSpec()+": "+
+            Exceptions.collapseText( ((Absent<?>)result).getException() ));
+    }
+
+    @Override
+    public Map getProperties() {
+        return mgmt.getConfig().asMapWithStringKeys();
+    }
+
+    @VisibleForTesting
+    public static void setupLocationRegistryForTesting(ManagementContext mgmt) {
+        // ensure localhost is added (even on windows)
+        LocationDefinition l = mgmt.getLocationRegistry().getDefinedLocationByName("localhost");
+        if (l==null) mgmt.getLocationRegistry().updateDefinedLocation(
+                BasicLocationRegistry.localhost(Identifiers.makeRandomId(8)) );
+        
+        ((BasicLocationRegistry)mgmt.getLocationRegistry()).disablePersistence();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/BasicMachineDetails.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/BasicMachineDetails.java b/core/src/main/java/org/apache/brooklyn/location/core/BasicMachineDetails.java
new file mode 100644
index 0000000..0c323ed
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/BasicMachineDetails.java
@@ -0,0 +1,183 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+import javax.annotation.Nonnull;
+import javax.annotation.concurrent.Immutable;
+
+import org.apache.brooklyn.api.location.HardwareDetails;
+import org.apache.brooklyn.api.location.MachineDetails;
+import org.apache.brooklyn.api.location.OsDetails;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.util.core.ResourceUtils;
+import org.apache.brooklyn.util.core.task.DynamicTasks;
+import org.apache.brooklyn.util.core.task.TaskTags;
+import org.apache.brooklyn.util.core.task.ssh.internal.PlainSshExecTaskFactory;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.apache.brooklyn.util.stream.Streams;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.CharMatcher;
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
+import com.google.common.base.Objects;
+import com.google.common.base.Splitter;
+import com.google.common.base.Throwables;
+import com.google.common.collect.Maps;
+import com.google.common.io.CharStreams;
+
+@Immutable
+public class BasicMachineDetails implements MachineDetails {
+
+    public static final Logger LOG = LoggerFactory.getLogger(BasicMachineDetails.class);
+
+    private final HardwareDetails hardwareDetails;
+    private final OsDetails osDetails;
+
+    public BasicMachineDetails(HardwareDetails hardwareDetails, OsDetails osDetails) {
+        this.hardwareDetails = checkNotNull(hardwareDetails, "hardwareDetails");
+        this.osDetails = checkNotNull(osDetails, "osDetails");
+    }
+
+    @Nonnull
+    @Override
+    public HardwareDetails getHardwareDetails() {
+        return hardwareDetails;
+    }
+
+    @Nonnull
+    @Override
+    public OsDetails getOsDetails() {
+        return osDetails;
+    }
+
+    @Override
+    public String toString() {
+        return Objects.toStringHelper(MachineDetails.class)
+                .add("os", osDetails)
+                .add("hardware", hardwareDetails)
+                .toString();
+    }
+
+    /**
+     * Creates a MachineDetails for the given location by SSHing to the machine and
+     * running a Bash script to gather data. Should only be called from within a
+     * task context. If this might not be the case then use {@link
+     * #taskForSshMachineLocation(SshMachineLocation)} instead.
+     */
+    @Beta
+    public static BasicMachineDetails forSshMachineLocationLive(SshMachineLocation location) {
+        return TaskTags.markInessential(DynamicTasks.queueIfPossible(taskForSshMachineLocation(location))
+                .orSubmitAsync()
+                .asTask())
+                .getUnchecked();
+    }
+
+    /**
+     * @return A task that gathers machine details by SSHing to the machine and running
+     *         a Bash script to gather data.
+     */
+    public static Task<BasicMachineDetails> taskForSshMachineLocation(SshMachineLocation location) {
+        BufferedReader reader = new BufferedReader(Streams.reader(
+                new ResourceUtils(BasicMachineDetails.class).getResourceFromUrl(
+                        "classpath://org/apache/brooklyn/location/basic/os-details.sh")));
+        List<String> script;
+        try {
+            script = CharStreams.readLines(reader);
+        } catch (IOException e) {
+            LOG.error("Error reading os-details script", e);
+            throw Throwables.propagate(e);
+        } finally {
+            try {
+                reader.close();
+            } catch (IOException e) {
+                // Not rethrowing e because it might obscure an exception caught by the first catch
+                LOG.error("Error closing os-details script reader", e);
+            }
+        }
+        Task<BasicMachineDetails> task = new PlainSshExecTaskFactory<String>(location, script)
+                .summary("Getting machine details for: " + location)
+                .requiringZeroAndReturningStdout()
+                .returning(taskToMachineDetailsFunction(location))
+                .newTask()
+                .asTask();
+
+        return task;
+    }
+
+    private static Function<ProcessTaskWrapper<?>, BasicMachineDetails> taskToMachineDetailsFunction(final SshMachineLocation location) {
+        return new Function<ProcessTaskWrapper<?>, BasicMachineDetails>() {
+            @Override
+            public BasicMachineDetails apply(ProcessTaskWrapper<?> input) {
+                if (input.getExitCode() != 0) {
+                    LOG.warn("Non-zero exit code when fetching machine details for {}; guessing anonymous linux", location);
+                    return new BasicMachineDetails(new BasicHardwareDetails(null, null),
+                            BasicOsDetails.Factory.ANONYMOUS_LINUX);
+                }
+
+                String stdout = input.getStdout();
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("Found following details at {}: {}", location, stdout);
+                }
+
+                Map<String,String> details = Maps.newHashMap(Splitter.on(CharMatcher.anyOf("\r\n"))
+                        .omitEmptyStrings()
+                        .withKeyValueSeparator(":")
+                        .split(stdout));
+
+                String name = details.remove("name");
+                String version = details.remove("version");
+                String architecture = details.remove("architecture");
+                Integer ram = intOrNull(details, "ram");
+                Integer cpuCount = intOrNull(details, "cpus");
+                if (!details.isEmpty()) {
+                    LOG.debug("Unused keys from os-details script: " + Joiner.on(", ").join(details.keySet()));
+                }
+
+                OsDetails osDetails = new BasicOsDetails(name, architecture, version);
+                HardwareDetails hardwareDetails = new BasicHardwareDetails(cpuCount, ram);
+                BasicMachineDetails machineDetails = new BasicMachineDetails(hardwareDetails, osDetails);
+
+                if (LOG.isDebugEnabled())
+                    LOG.debug("Machine details for {}: {}", location, machineDetails);
+
+                return machineDetails;
+            }
+
+            private Integer intOrNull(Map<String, String> details, String key) {
+                try {
+                    return Integer.valueOf(details.remove(key));
+                } catch (NumberFormatException e) {
+                    return null;
+                }
+            }
+        };
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/BasicMachineMetadata.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/BasicMachineMetadata.java b/core/src/main/java/org/apache/brooklyn/location/core/BasicMachineMetadata.java
new file mode 100644
index 0000000..37b61ee
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/BasicMachineMetadata.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import com.google.common.base.Objects;
+
+import org.apache.brooklyn.api.location.MachineManagementMixins;
+
+public class BasicMachineMetadata implements MachineManagementMixins.MachineMetadata {
+
+    final String id, name, primaryIp;
+    final Boolean isRunning;
+    final Object originalMetadata;
+    
+    public BasicMachineMetadata(String id, String name, String primaryIp, Boolean isRunning, Object originalMetadata) {
+        super();
+        this.id = id;
+        this.name = name;
+        this.primaryIp = primaryIp;
+        this.isRunning = isRunning;
+        this.originalMetadata = originalMetadata;
+    }
+
+    public String getId() {
+        return id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public String getPrimaryIp() {
+        return primaryIp;
+    }
+
+    public Boolean isRunning() {
+        return isRunning;
+    }
+
+    public Object getOriginalMetadata() {
+        return originalMetadata;
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hashCode(id, isRunning, name, originalMetadata, primaryIp);
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) return true;
+        if (obj == null) return false;
+        if (getClass() != obj.getClass()) return false;
+        BasicMachineMetadata other = (BasicMachineMetadata) obj;
+        if (!Objects.equal(id, other.id)) return false;
+        if (!Objects.equal(name, other.name)) return false;
+        if (!Objects.equal(primaryIp, other.primaryIp)) return false;
+        if (!Objects.equal(isRunning, other.isRunning)) return false;
+        if (!Objects.equal(originalMetadata, other.originalMetadata)) return false;
+        return true;
+    }
+
+    @Override
+    public String toString() {
+        return Objects.toStringHelper(this).add("id", id).add("name", name).add("originalMetadata", originalMetadata).toString();
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/BasicOsDetails.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/BasicOsDetails.java b/core/src/main/java/org/apache/brooklyn/location/core/BasicOsDetails.java
new file mode 100644
index 0000000..089df03
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/BasicOsDetails.java
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import java.util.regex.Pattern;
+
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.Immutable;
+
+import com.google.common.base.Objects;
+
+import org.apache.brooklyn.api.location.OsDetails;
+
+@Immutable
+public class BasicOsDetails implements OsDetails {
+
+    final String name, arch, version;
+    final boolean is64bit;
+    // (?i) forces matches to be case insensitive
+    public static final String UNIX_OS_NAME_PATTERNS = "(?i).*linux.*|centos|debian|fedora|gentoo|rhel|slackware|solaris|suse|ubuntu|coreos";
+
+    /** Sets is64Bit according to value of arch parameter. */
+    public BasicOsDetails(String name, String arch, String version) {
+       this(name, arch, version, arch != null && arch.contains("64"));
+    }
+
+    public BasicOsDetails(String name, String arch, String version, boolean is64Bit) {
+        this.name = name; this.arch = arch; this.version = version; this.is64bit = is64Bit;
+    }
+    
+    // TODO: Should be replaced with an enum like Jclouds' OsFamily and isX methods should
+    // switch against known cases
+    @Nullable
+    @Override
+    public String getName() {
+        return name;
+    }
+
+    @Nullable
+    @Override
+    public String getArch() {
+        return arch;
+    }
+
+    @Nullable
+    @Override
+    public String getVersion() {
+        return version;
+    }
+
+    @Override
+    public boolean isWindows() {
+        //TODO confirm
+        return getName()!=null && getName().toLowerCase().contains("microsoft");
+    }
+
+    @Override
+    public boolean isLinux() {
+        return getName() != null && Pattern.matches(UNIX_OS_NAME_PATTERNS, getName());
+    }
+
+    @Override
+    public boolean isMac() {
+        return getName()!=null && getName().equals(OsNames.MAC_OS_X);
+    }
+
+    @Override
+    public boolean is64bit() {
+        return is64bit;
+    }
+
+    @Override
+    public String toString() {
+        return Objects.toStringHelper(OsDetails.class)
+                .omitNullValues()
+                .add("name", name)
+                .add("version", version)
+                .add("arch", arch)
+                .toString();
+    }
+
+    public static class OsNames {
+        public static final String MAC_OS_X = "Mac OS X";
+    }
+    
+    public static class OsArchs {
+        public static final String X_86_64 = "x86_64";
+//        public static final String X_86 = "x86";
+//        // is this standard?  or do we ever need the above?
+        public static final String I386 = "i386";
+    }
+
+    public static class OsVersions {
+        public static final String MAC_10_8 = "10.8";
+        public static final String MAC_10_9 = "10.9";
+    }
+    
+    public static class Factory {
+        public static OsDetails newLocalhostInstance() {
+            return new BasicOsDetails(System.getProperty("os.name"), System.getProperty("os.arch"), System.getProperty("os.version"));
+        }
+        
+        public static final OsDetails ANONYMOUS_LINUX = new BasicOsDetails("linux", OsArchs.I386, "unknown");
+        public static final OsDetails ANONYMOUS_LINUX_64 = new BasicOsDetails("linux", OsArchs.X_86_64, "unknown");
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/CatalogLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/CatalogLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/core/CatalogLocationResolver.java
new file mode 100644
index 0000000..a907a49
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/CatalogLocationResolver.java
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.api.catalog.CatalogItem;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationRegistry;
+import org.apache.brooklyn.api.location.LocationResolver;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.catalog.internal.CatalogUtils;
+
+/**
+ * Given a location spec in the form {@code brooklyn.catalog:<symbolicName>:<version>}, 
+ * looks up the catalog to get its definition and creates such a location.
+ */
+public class CatalogLocationResolver implements LocationResolver {
+
+    @SuppressWarnings("unused")
+    private static final Logger log = LoggerFactory.getLogger(CatalogLocationResolver.class);
+
+    public static final String NAME = "brooklyn.catalog";
+
+    private ManagementContext managementContext;
+
+    @Override
+    public void init(ManagementContext managementContext) {
+        this.managementContext = checkNotNull(managementContext, "managementContext");
+    }
+    
+    @Override
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
+        String id = spec.substring(NAME.length()+1);
+        CatalogItem<?, ?> item = CatalogUtils.getCatalogItemOptionalVersion(managementContext, id);
+        LocationSpec<?> origLocSpec = managementContext.getCatalog().createSpec((CatalogItem<Location, LocationSpec<?>>)item);
+        LocationSpec<?> locSpec = LocationSpec.create(origLocSpec)
+                .configure(locationFlags);
+        return managementContext.getLocationManager().createLocation(locSpec);
+    }
+
+    @Override
+    public String getPrefix() {
+        return NAME;
+    }
+    
+    /**
+     * accepts anything that looks like it will be a YAML catalog item (e.g. starting "brooklyn.locations")
+     */
+    @Override
+    public boolean accepts(String spec, LocationRegistry registry) {
+        if (BasicLocationRegistry.isResolverPrefixForSpec(this, spec, false)) return true;
+        if (registry.getDefinedLocationByName(spec)!=null) return true;
+        return false;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/DefinedLocationByIdResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/DefinedLocationByIdResolver.java b/core/src/main/java/org/apache/brooklyn/location/core/DefinedLocationByIdResolver.java
new file mode 100644
index 0000000..efe0aff
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/DefinedLocationByIdResolver.java
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.util.Map;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationDefinition;
+import org.apache.brooklyn.api.location.LocationRegistry;
+import org.apache.brooklyn.api.location.LocationResolver;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * looks up based on ID in DefinedLocations map
+ */
+public class DefinedLocationByIdResolver implements LocationResolver {
+
+    public static final Logger log = LoggerFactory.getLogger(DefinedLocationByIdResolver.class);
+
+    public static final String ID = "id";
+    
+    private volatile ManagementContext managementContext;
+
+    @Override
+    public void init(ManagementContext managementContext) {
+        this.managementContext = checkNotNull(managementContext, "managementContext");
+    }
+    
+    @SuppressWarnings({ "rawtypes" })
+    @Override
+    public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
+        String id = spec;
+        if (spec.toLowerCase().startsWith(ID+":")) {
+            id = spec.substring( (ID+":").length() );
+        }
+        LocationDefinition ld = registry.getDefinedLocationById(id);
+        ld.getSpec();
+        return ((BasicLocationRegistry)registry).resolveLocationDefinition(ld, locationFlags, null);
+    }
+
+    @Override
+    public String getPrefix() {
+        return ID;
+    }
+    
+    /** accepts anything starting  id:xxx  or just   xxx where xxx is a defined location ID */
+    @Override
+    public boolean accepts(String spec, LocationRegistry registry) {
+        if (BasicLocationRegistry.isResolverPrefixForSpec(this, spec, false)) return true;
+        if (registry.getDefinedLocationById(spec)!=null) return true;
+        return false;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/DeprecatedKeysMappingBuilder.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/DeprecatedKeysMappingBuilder.java b/core/src/main/java/org/apache/brooklyn/location/core/DeprecatedKeysMappingBuilder.java
new file mode 100644
index 0000000..ad98f04
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/DeprecatedKeysMappingBuilder.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import java.util.Map;
+
+import org.apache.brooklyn.config.ConfigKey;
+import org.slf4j.Logger;
+
+import com.google.common.base.CaseFormat;
+import com.google.common.collect.ImmutableMap;
+
+/**
+* @deprecated since 0.6; for use only in converting deprecated flags; will be deleted in future version.
+*/
+public class DeprecatedKeysMappingBuilder {
+    private final ImmutableMap.Builder<String,String> builder = new ImmutableMap.Builder<String,String>();
+    private final Logger logger;
+    
+    public DeprecatedKeysMappingBuilder(Logger logger) {
+        this.logger = logger;
+    }
+
+    public DeprecatedKeysMappingBuilder camelToHyphen(ConfigKey<?> key) {
+        return camelToHyphen(key.getName());
+    }
+    
+    public DeprecatedKeysMappingBuilder camelToHyphen(String key) {
+        String hyphen = toHyphen(key);
+        if (key.equals(hyphen)) {
+            logger.warn("Invalid attempt to convert camel-case key {} to deprecated hyphen-case: both the same", hyphen);
+        } else {
+            builder.put(hyphen, key);
+        }
+        return this;
+    }
+    
+    public DeprecatedKeysMappingBuilder putAll(Map<String,String> vals) {
+        builder.putAll(vals);
+        return this;
+    }
+
+    public Map<String,String> build() {
+        return builder.build();
+    }
+    
+    private String toHyphen(String word) {
+        return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, word);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/HasSubnetHostname.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/HasSubnetHostname.java b/core/src/main/java/org/apache/brooklyn/location/core/HasSubnetHostname.java
new file mode 100644
index 0000000..604d5ef
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/HasSubnetHostname.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import com.google.common.annotations.Beta;
+
+@Beta
+public interface HasSubnetHostname {
+
+    /** returns a hostname for use internally within a subnet / VPC */
+    @Beta
+    String getSubnetHostname();
+
+    /** returns an IP for use internally within a subnet / VPC */
+    String getSubnetIp();
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/LocationConfigKeys.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/LocationConfigKeys.java b/core/src/main/java/org/apache/brooklyn/location/core/LocationConfigKeys.java
new file mode 100644
index 0000000..689a1d7
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/LocationConfigKeys.java
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import java.io.File;
+import java.util.Set;
+
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.BasicConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.util.os.Os;
+
+import com.google.common.base.CaseFormat;
+import com.google.common.reflect.TypeToken;
+
+public class LocationConfigKeys {
+
+    public static final ConfigKey<String> LOCATION_ID = ConfigKeys.newStringConfigKey("id");
+    public static final ConfigKey<String> DISPLAY_NAME = ConfigKeys.newStringConfigKey("displayName");
+    public static final ConfigKey<Boolean> ENABLED = ConfigKeys.newBooleanConfigKey("enabled", "Whether the location is enabled for listing and use "
+        + "(only supported for selected locations)", true);
+    
+    public static final ConfigKey<String> ACCESS_IDENTITY = ConfigKeys.newStringConfigKey("identity"); 
+    public static final ConfigKey<String> ACCESS_CREDENTIAL = ConfigKeys.newStringConfigKey("credential"); 
+
+    public static final ConfigKey<Double> LATITUDE = new BasicConfigKey<Double>(Double.class, "latitude"); 
+    public static final ConfigKey<Double> LONGITUDE = new BasicConfigKey<Double>(Double.class, "longitude"); 
+
+    public static final ConfigKey<String> CLOUD_PROVIDER = ConfigKeys.newStringConfigKey("provider");
+    public static final ConfigKey<String> CLOUD_ENDPOINT = ConfigKeys.newStringConfigKey("endpoint");
+    public static final ConfigKey<String> CLOUD_REGION_ID = ConfigKeys.newStringConfigKey("region");
+    public static final ConfigKey<String> CLOUD_AVAILABILITY_ZONE_ID = ConfigKeys.newStringConfigKey("availabilityZone");
+
+    @SuppressWarnings("serial")
+    public static final ConfigKey<Set<String>> ISO_3166 = ConfigKeys.newConfigKey(new TypeToken<Set<String>>() {}, "iso3166", "ISO-3166 or ISO-3166-2 location codes"); 
+
+    public static final ConfigKey<String> USER = ConfigKeys.newStringConfigKey("user", 
+            "user account for normal access to the remote machine, defaulting to local user", System.getProperty("user.name"));
+    
+    public static final ConfigKey<String> PASSWORD = ConfigKeys.newStringConfigKey("password", "password to use for ssh; note some images do not allow password-based ssh access");
+    public static final ConfigKey<String> PUBLIC_KEY_FILE = ConfigKeys.newStringConfigKey("publicKeyFile", "ssh public key file to use; if blank will infer from privateKeyFile by appending \".pub\"");
+    public static final ConfigKey<String> PUBLIC_KEY_DATA = ConfigKeys.newStringConfigKey("publicKeyData", "ssh public key string to use (takes precedence over publicKeyFile)");
+    public static final ConfigKey<String> PRIVATE_KEY_FILE = ConfigKeys.newStringConfigKey("privateKeyFile", "a '" + File.pathSeparator + "' separated list of ssh private key files; uses first in list that can be read",
+                                                                                           Os.fromHome(".ssh/id_rsa") + File.pathSeparator + Os.fromHome(".ssh/id_dsa"));
+    public static final ConfigKey<String> PRIVATE_KEY_DATA = ConfigKeys.newStringConfigKey("privateKeyData", "ssh private key string to use (takes precedence over privateKeyFile)");
+    public static final ConfigKey<String> PRIVATE_KEY_PASSPHRASE = ConfigKeys.newStringConfigKey("privateKeyPassphrase");
+
+    /** @deprecated since 0.6.0; included here so it gets picked up in auto-detect routines */ @Deprecated
+    public static final ConfigKey<String> LEGACY_PUBLIC_KEY_FILE = ConfigKeys.convert(PUBLIC_KEY_FILE, CaseFormat.LOWER_CAMEL, CaseFormat.LOWER_HYPHEN);
+    /** @deprecated since 0.6.0; included here so it gets picked up in auto-detect routines */ @Deprecated
+    public static final ConfigKey<String> LEGACY_PUBLIC_KEY_DATA = ConfigKeys.convert(PUBLIC_KEY_DATA, CaseFormat.LOWER_CAMEL, CaseFormat.LOWER_HYPHEN);
+    /** @deprecated since 0.6.0; included here so it gets picked up in auto-detect routines */ @Deprecated
+    public static final ConfigKey<String> LEGACY_PRIVATE_KEY_FILE = ConfigKeys.convert(PRIVATE_KEY_FILE, CaseFormat.LOWER_CAMEL, CaseFormat.LOWER_HYPHEN);
+    /** @deprecated since 0.6.0; included here so it gets picked up in auto-detect routines */ @Deprecated
+    public static final ConfigKey<String> LEGACY_PRIVATE_KEY_DATA = ConfigKeys.convert(PRIVATE_KEY_DATA, CaseFormat.LOWER_CAMEL, CaseFormat.LOWER_HYPHEN);
+    /** @deprecated since 0.6.0; included here so it gets picked up in auto-detect routines */ @Deprecated
+    public static final ConfigKey<String> LEGACY_PRIVATE_KEY_PASSPHRASE = ConfigKeys.convert(PRIVATE_KEY_PASSPHRASE, CaseFormat.LOWER_CAMEL, CaseFormat.LOWER_HYPHEN);
+
+    public static final ConfigKey<Object> CALLER_CONTEXT = new BasicConfigKey<Object>(Object.class, "callerContext",
+            "An object whose toString is used for logging, to indicate wherefore a VM is being created");
+    public static final ConfigKey<String> CLOUD_MACHINE_NAMER_CLASS = ConfigKeys.newStringConfigKey("cloudMachineNamer", "fully qualified class name of a class that extends CloudMachineNamer and has a single-parameter constructor that takes a ConfigBag");
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/core/LocationConfigUtils.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/location/core/LocationConfigUtils.java b/core/src/main/java/org/apache/brooklyn/location/core/LocationConfigUtils.java
new file mode 100644
index 0000000..80879b9
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/location/core/LocationConfigUtils.java
@@ -0,0 +1,559 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.location.core;
+
+import static org.apache.brooklyn.util.JavaGroovyEquivalents.groovyTruth;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.security.KeyPair;
+import java.security.PublicKey;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.internal.BrooklynFeatureEnablement;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.brooklyn.location.cloud.CloudLocationConfig;
+import org.apache.brooklyn.location.core.internal.LocationInternal;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.collections.MutableSet;
+import org.apache.brooklyn.util.core.ResourceUtils;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.crypto.SecureKeys;
+import org.apache.brooklyn.util.core.crypto.SecureKeys.PassphraseProblem;
+import org.apache.brooklyn.util.crypto.AuthorizedKeysParser;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.text.StringFunctions;
+import org.apache.brooklyn.util.text.Strings;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Objects;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+
+public class LocationConfigUtils {
+
+    private static final Logger log = LoggerFactory.getLogger(LocationConfigUtils.class);
+
+    /** Creates an instance of {@link OsCredential} by inspecting {@link LocationConfigKeys#PASSWORD}; 
+     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE};
+     * {@link LocationConfigKeys#PRIVATE_KEY_PASSPHRASE} if needed, and
+     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE}
+     * (defaulting to the private key file + ".pub"). 
+     **/
+    public static OsCredential getOsCredential(ConfigBag config) {
+        return OsCredential.newInstance(config);
+    }
+    
+    /** Convenience class for holding private/public keys and passwords, inferring from config keys.
+     * See {@link LocationConfigUtils#getOsCredential(ConfigBag)}. */
+    @Beta // would be nice to replace with a builder pattern 
+    public static class OsCredential {
+        private final ConfigBag config;
+        private boolean preferPassword = false;
+        private boolean tryDefaultKeys = true;
+        private boolean requirePublicKey = true;
+        private boolean doKeyValidation = BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_VALIDATE_LOCATION_SSH_KEYS);
+        private boolean warnOnErrors = true;
+        private boolean throwOnErrors = false;
+        
+        private boolean dirty = true;;
+        
+        private String privateKeyData;
+        private String publicKeyData;
+        private String password;
+        
+        private OsCredential(ConfigBag config) {
+            this.config = config;
+        }
+
+        /** throws if there are any problems */
+        public OsCredential checkNotEmpty() {
+            checkNoErrors();
+            
+            if (!hasKey() && !hasPassword()) {
+                if (warningMessages.size()>0)
+                    throw new IllegalStateException("Could not find credentials: "+warningMessages);
+                else 
+                    throw new IllegalStateException("Could not find credentials");
+            }
+            return this;
+        }
+
+        /** throws if there were errors resolving (e.g. explicit keys, none of which were found/valid, or public key required and not found) 
+         * @return */
+        public OsCredential checkNoErrors() {
+            throwOnErrors(true);
+            dirty();
+            infer();
+            return this;
+        }
+        
+        public OsCredential logAnyWarnings() {
+            if (!warningMessages.isEmpty())
+                log.warn("When reading credentials: "+warningMessages);
+            return this;
+        }
+
+        public Set<String> getWarningMessages() {
+            return warningMessages;
+        }
+        
+        /** returns either the key or password or null; if both a key and a password this prefers the key unless otherwise set
+         * via {@link #preferPassword()} */
+        public synchronized String getPreferredCredential() {
+            infer();
+            
+            if (isUsingPassword()) return password;
+            if (hasKey()) return privateKeyData;
+            return null;
+        }
+
+        /** if there is no credential (ignores public key) */
+        public boolean isEmpty() {
+            return !hasKey() && !hasPassword();
+        }
+        public boolean hasKey() {
+            infer();
+            // key has stricter non-blank check than password
+            return Strings.isNonBlank(privateKeyData);
+        }
+        public boolean hasPassword() {
+            infer();
+            // blank, even empty passwords are allowed
+            return password!=null;
+        }
+        /** if a password is available, and either this is preferred over a key or there is no key */
+        public boolean isUsingPassword() {
+            return hasPassword() && (!hasKey() || preferPassword);
+        }
+        
+        public String getPrivateKeyData() {
+            infer();
+            return privateKeyData;
+        }
+        public String getPublicKeyData() {
+            infer();
+            return publicKeyData;
+        }
+        public String getPassword() {
+            infer();
+            return password;
+        }
+        
+        /** if both key and password supplied, prefer the key; the default */
+        public OsCredential preferKey() { preferPassword = false; return dirty(); }
+        /** if both key and password supplied, prefer the password; see {@link #preferKey()} */
+        public OsCredential preferPassword() { preferPassword = true; return dirty(); }
+        
+        /** if false, do not mind if there is no public key corresponding to any private key;
+         * defaults to true; only applies if a private key is set */
+        public OsCredential requirePublicKey(boolean requirePublicKey) {
+            this.requirePublicKey = requirePublicKey;
+            return dirty(); 
+        }
+        /** whether to check the private/public keys and passphrase are coherent; default true */
+        public OsCredential doKeyValidation(boolean doKeyValidation) {
+            this.doKeyValidation = doKeyValidation;
+            return dirty();
+        }
+        /** if true (the default) this will look at default locations set on keys */
+        public OsCredential useDefaultKeys(boolean tryDefaultKeys) {
+            this.tryDefaultKeys = tryDefaultKeys;
+            return dirty(); 
+        }
+        /** whether to log warnings on problems */
+        public OsCredential warnOnErrors(boolean warnOnErrors) {
+            this.warnOnErrors = warnOnErrors;
+            return dirty(); 
+        }
+        /** whether to throw on problems */
+        public OsCredential throwOnErrors(boolean throwOnErrors) {
+            this.throwOnErrors = throwOnErrors;
+            return dirty(); 
+        }
+        
+        private OsCredential dirty() { dirty = true; return this; }
+            
+        public static OsCredential newInstance(ConfigBag config) {
+            return new OsCredential(config);
+        }
+        
+        private synchronized void infer() {
+            if (!dirty) return;
+            warningMessages.clear(); 
+            
+            log.debug("Inferring OS credentials");
+            privateKeyData = config.get(LocationConfigKeys.PRIVATE_KEY_DATA);
+            password = config.get(LocationConfigKeys.PASSWORD);
+            publicKeyData = getKeyDataFromDataKeyOrFileKey(config, LocationConfigKeys.PUBLIC_KEY_DATA, LocationConfigKeys.PUBLIC_KEY_FILE);
+
+            KeyPair privateKey = null;
+            
+            if (Strings.isBlank(privateKeyData)) {
+                // look up private key files
+                String privateKeyFiles = null;
+                boolean privateKeyFilesExplicitlySet = config.containsKey(LocationConfigKeys.PRIVATE_KEY_FILE);
+                if (privateKeyFilesExplicitlySet || (tryDefaultKeys && password==null)) 
+                    privateKeyFiles = config.get(LocationConfigKeys.PRIVATE_KEY_FILE);
+                if (Strings.isNonBlank(privateKeyFiles)) {
+                    Iterator<String> fi = Arrays.asList(privateKeyFiles.split(File.pathSeparator)).iterator();
+                    while (fi.hasNext()) {
+                        String file = fi.next();
+                        if (Strings.isNonBlank(file)) {
+                            try {
+                                // real URL's won't actual work, due to use of path separator above 
+                                // not real important, but we get it for free if "files" is a list instead.
+                                // using ResourceUtils is useful for classpath resources
+                                if (file!=null)
+                                    privateKeyData = ResourceUtils.create().getResourceAsString(file);
+                                // else use data already set
+                                
+                                privateKey = getValidatedPrivateKey(file);
+                                
+                                if (privateKeyData==null) {
+                                    // was cleared due to validation error
+                                } else if (Strings.isNonBlank(publicKeyData)) {
+                                    log.debug("Loaded private key data from "+file+" (public key data explicitly set)");
+                                    break;
+                                } else {
+                                    String publicKeyFile = (file!=null ? file+".pub" : "(data)");
+                                    try {
+                                        publicKeyData = ResourceUtils.create().getResourceAsString(publicKeyFile);
+                                        
+                                        log.debug("Loaded private key data from "+file+
+                                            " and public key data from "+publicKeyFile);
+                                        break;
+                                    } catch (Exception e) {
+                                        Exceptions.propagateIfFatal(e);
+                                        log.debug("No public key file "+publicKeyFile+"; will try extracting from private key");
+                                        publicKeyData = AuthorizedKeysParser.encodePublicKey(privateKey.getPublic());
+                                        
+                                        if (publicKeyData==null) {
+                                            if (requirePublicKey) {
+                                                addWarning("Unable to find or extract public key for "+file, "skipping");
+                                            } else {
+                                                log.debug("Loaded private key data from "+file+" (public key data not found but not required)");
+                                                break;
+                                            }
+                                        } else {
+                                            log.debug("Loaded private key data from "+file+" (public key data extracted)");
+                                            break;
+                                        }
+                                        privateKeyData = null;
+                                    }
+                                }
+
+                            } catch (Exception e) {
+                                Exceptions.propagateIfFatal(e);
+                                String message = "Missing/invalid private key file "+file;
+                                if (privateKeyFilesExplicitlySet) addWarning(message, (!fi.hasNext() ? "no more files to try" : "trying next file")+": "+e);
+                            }
+                        }
+                    }
+                    if (privateKeyFilesExplicitlySet && Strings.isBlank(privateKeyData))
+                        error("No valid private keys found", ""+warningMessages);
+                }
+            } else {
+                privateKey = getValidatedPrivateKey("(data)");
+            }
+            
+            if (privateKeyData!=null) {
+                if (requirePublicKey && Strings.isBlank(publicKeyData)) {
+                    if (privateKey!=null) {
+                        publicKeyData = AuthorizedKeysParser.encodePublicKey(privateKey.getPublic());
+                    }
+                    if (Strings.isBlank(publicKeyData)) {
+                        error("If explicit "+LocationConfigKeys.PRIVATE_KEY_DATA.getName()+" is supplied, then "
+                            + "the corresponding "+LocationConfigKeys.PUBLIC_KEY_DATA.getName()+" must also be supplied.", null);
+                    } else {
+                        log.debug("Public key data extracted");
+                    }
+                }
+                if (doKeyValidation && privateKey!=null && privateKey.getPublic()!=null && Strings.isNonBlank(publicKeyData)) {
+                    PublicKey decoded = null;
+                    try {
+                        decoded = AuthorizedKeysParser.decodePublicKey(publicKeyData);
+                    } catch (Exception e) {
+                        Exceptions.propagateIfFatal(e);
+                        addWarning("Invalid public key: "+decoded);
+                    }
+                    if (decoded!=null && !privateKey.getPublic().equals( decoded )) {
+                        error("Public key inferred from does not match public key extracted from private key", null);
+                    }
+                }
+            }
+
+            log.debug("OS credential inference: "+this);
+            dirty = false;
+        }
+
+        private KeyPair getValidatedPrivateKey(String label) {
+            KeyPair privateKey = null;
+            String passphrase = config.get(CloudLocationConfig.PRIVATE_KEY_PASSPHRASE);
+            try {
+                privateKey = SecureKeys.readPem(new ByteArrayInputStream(privateKeyData.getBytes()), passphrase);
+                if (passphrase!=null) {
+                    // get the unencrypted key data for our internal use (jclouds requires this)
+                    privateKeyData = SecureKeys.toPem(privateKey);
+                }
+            } catch (PassphraseProblem e) {
+                if (doKeyValidation) {
+                    log.debug("Encountered error handling key "+label+": "+e, e);
+                    if (Strings.isBlank(passphrase))
+                        addWarning("Passphrase required for key '"+label+"'");
+                    else
+                        addWarning("Invalid passphrase for key '"+label+"'");
+                    privateKeyData = null;
+                }
+            } catch (Exception e) {
+                Exceptions.propagateIfFatal(e);
+                if (doKeyValidation) {
+                    addWarning("Unable to parse private key from '"+label+"': unknown format");
+                    privateKeyData = null;
+                }
+            }
+            return privateKey;
+        }
+        
+        Set<String> warningMessages = MutableSet.of();
+        
+        private void error(String msg, String logExtension) {
+            addWarning(msg);
+            if (warnOnErrors) log.warn(msg+(logExtension==null ? "" : ": "+logExtension));
+            if (throwOnErrors) throw new IllegalStateException(msg+(logExtension==null ? "" : "; "+logExtension));
+        }
+
+        private void addWarning(String msg) {
+            addWarning(msg, null);
+        }
+        private void addWarning(String msg, String debugExtension) {
+            log.debug(msg+(debugExtension==null ? "" : "; "+debugExtension));
+            warningMessages.add(msg);
+        }
+
+        @Override
+        public String toString() {
+            return getClass().getSimpleName()+"["+
+                (Strings.isNonBlank(publicKeyData) ? publicKeyData : "no-public-key")+";"+
+                (Strings.isNonBlank(privateKeyData) ? "private-key-present" : "no-private-key")+","+
+                (password!=null ? "password(len="+password.length()+")" : "no-password")+"]";
+        }
+    }
+
+    /** @deprecated since 0.7.0, use #getOsCredential(ConfigBag) */ @Deprecated
+    public static String getPrivateKeyData(ConfigBag config) {
+        return getKeyData(config, LocationConfigKeys.PRIVATE_KEY_DATA, LocationConfigKeys.PRIVATE_KEY_FILE);
+    }
+    
+    /** @deprecated since 0.7.0, use #getOsCredential(ConfigBag) */ @Deprecated
+    public static String getPublicKeyData(ConfigBag config) {
+        String data = getKeyData(config, LocationConfigKeys.PUBLIC_KEY_DATA, LocationConfigKeys.PUBLIC_KEY_FILE);
+        if (groovyTruth(data)) return data;
+        
+        String privateKeyFile = config.get(LocationConfigKeys.PRIVATE_KEY_FILE);
+        if (groovyTruth(privateKeyFile)) {
+            List<String> privateKeyFiles = Arrays.asList(privateKeyFile.split(File.pathSeparator));
+            List<String> publicKeyFiles = ImmutableList.copyOf(Iterables.transform(privateKeyFiles, StringFunctions.append(".pub")));
+            List<String> publicKeyFilesTidied = tidyFilePaths(publicKeyFiles);
+            
+            String fileData = getFileContents(publicKeyFilesTidied);
+            if (groovyTruth(fileData)) {
+                if (log.isDebugEnabled()) log.debug("Loaded "+LocationConfigKeys.PUBLIC_KEY_DATA.getName()+" from inferred files, based on "+LocationConfigKeys.PRIVATE_KEY_FILE.getName() + ": used " + publicKeyFilesTidied + " for "+config.getDescription());
+                config.put(LocationConfigKeys.PUBLIC_KEY_DATA, fileData);
+                return fileData;
+            } else {
+                log.info("Not able to load "+LocationConfigKeys.PUBLIC_KEY_DATA.getName()+" from inferred files, based on "+LocationConfigKeys.PRIVATE_KEY_FILE.getName() + ": tried " + publicKeyFilesTidied + " for "+config.getDescription());
+            }
+        }
+        
+        return null;
+    }
+
+    /** @deprecated since 0.7.0, use #getOsCredential(ConfigBag) */ @Deprecated
+    public static String getKeyData(ConfigBag config, ConfigKey<String> dataKey, ConfigKey<String> fileKey) {
+        return getKeyDataFromDataKeyOrFileKey(config, dataKey, fileKey);
+    }
+    
+    private static String getKeyDataFromDataKeyOrFileKey(ConfigBag config, ConfigKey<String> dataKey, ConfigKey<String> fileKey) {
+        boolean unused = config.isUnused(dataKey);
+        String data = config.get(dataKey);
+        if (groovyTruth(data) && !unused) {
+            return data;
+        }
+        
+        String file = config.get(fileKey);
+        if (groovyTruth(file)) {
+            List<String> files = Arrays.asList(file.split(File.pathSeparator));
+            List<String> filesTidied = tidyFilePaths(files);
+            String fileData = getFileContents(filesTidied);
+            if (fileData == null) {
+                log.warn("Invalid file" + (files.size() > 1 ? "s" : "") + " for " + fileKey + " (given " + files + 
+                        (files.equals(filesTidied) ? "" : "; converted to " + filesTidied) + ") " +
+                        "may fail provisioning " + config.getDescription());
+            } else if (groovyTruth(data)) {
+                if (!fileData.trim().equals(data.trim()))
+                    log.warn(dataKey.getName()+" and "+fileKey.getName()+" both specified; preferring the former");
+            } else {
+                data = fileData;
+                config.put(dataKey, data);
+                config.get(dataKey);
+            }
+        }
+        
+        return data;
+    }
+    
+    /**
+     * Reads the given file(s) in-order, returning the contents of the first file that can be read.
+     * Returns the file contents, or null if none of the files can be read.
+     *  
+     * @param files             list of file paths
+     */
+    private static String getFileContents(Iterable<String> files) {
+        Iterator<String> fi = files.iterator();
+        while (fi.hasNext()) {
+            String file = fi.next();
+            if (groovyTruth(file)) {
+                try {
+                    // see comment above
+                    String result = ResourceUtils.create().getResourceAsString(file);
+                    if (result!=null) return result;
+                    log.debug("Invalid file "+file+" ; " + (!fi.hasNext() ? "no more files to try" : "trying next file")+" (null)");
+                } catch (Exception e) {
+                    Exceptions.propagateIfFatal(e);
+                    log.debug("Invalid file "+file+" ; " + (!fi.hasNext() ? "no more files to try" : "trying next file"), e);
+                }
+            }
+        }
+        return null;
+    }
+
+    private static List<String> tidyFilePaths(Iterable<String> files) {
+        List<String> result = Lists.newArrayList();
+        for (String file : files) {
+            result.add(Os.tidyPath(file));
+        }
+        return result;
+    }
+
+    /** @deprecated since 0.6.0 use configBag.getWithDeprecation */
+    @Deprecated
+    @SuppressWarnings("unchecked")
+    public static <T> T getConfigCheckingDeprecatedAlternatives(ConfigBag configBag, ConfigKey<T> preferredKey,
+            ConfigKey<?> ...deprecatedKeys) {
+        T value1 = (T) configBag.getWithDeprecation(preferredKey, deprecatedKeys);
+        T value2 = getConfigCheckingDeprecatedAlternativesInternal(configBag, preferredKey, deprecatedKeys);
+        if (!Objects.equal(value1, value2)) {
+            // points to a bug in one of the get-with-deprecation methods
+            log.warn("Deprecated getConfig with deprecated keys "+Arrays.toString(deprecatedKeys)+" gets different value with " +
+                    "new strategy "+preferredKey+" ("+value1+") and old ("+value2+"); preferring old value for now, but this behaviour will change");
+            return value2;
+        }
+        return value1;
+    }
+    
+    @SuppressWarnings("unchecked")
+    private static <T> T getConfigCheckingDeprecatedAlternativesInternal(ConfigBag configBag, ConfigKey<T> preferredKey,
+            ConfigKey<?> ...deprecatedKeys) {
+        ConfigKey<?> keyProvidingValue = null;
+        T value = null;
+        boolean found = false;
+        if (configBag.containsKey(preferredKey)) {
+            value = configBag.get(preferredKey);
+            found = true;
+            keyProvidingValue = preferredKey;
+        }
+        
+        for (ConfigKey<?> deprecatedKey: deprecatedKeys) {
+            T altValue = null;
+            boolean altFound = false;
+            if (configBag.containsKey(deprecatedKey)) {
+                altValue = (T) configBag.get(deprecatedKey);
+                altFound = true;
+                
+                if (altFound) {
+                    if (found) {
+                        if (Objects.equal(value, altValue)) {
+                            // fine -- nothing
+                        } else {
+                            log.warn("Detected deprecated key "+deprecatedKey+" with value "+altValue+" used in addition to "+keyProvidingValue+" " +
+                                    "with value "+value+" for "+configBag.getDescription()+"; ignoring");
+                            configBag.remove(deprecatedKey);
+                        }
+                    } else {
+                        log.warn("Detected deprecated key "+deprecatedKey+" with value "+altValue+" used instead of recommended "+preferredKey+"; " +
+                                "promoting to preferred key status; will not be supported in future versions");
+                        configBag.put(preferredKey, altValue);
+                        configBag.remove(deprecatedKey);
+                        value = altValue;
+                        found = true;
+                        keyProvidingValue = deprecatedKey;
+                    }
+                }
+            }
+        }
+        
+        if (found) {
+            return value;
+        } else {
+            return configBag.get(preferredKey); // get the default
+        }
+    }
+
+    public static Map<ConfigKey<String>,String> finalAndOriginalSpecs(String finalSpec, Object ...sourcesForOriginalSpec) {
+        // yuck!: TODO should clean up how these things get passed around
+        Map<ConfigKey<String>,String> result = MutableMap.of();
+        if (finalSpec!=null) 
+            result.put(LocationInternal.FINAL_SPEC, finalSpec);
+        
+        String originalSpec = null;
+        for (Object source: sourcesForOriginalSpec) {
+            if (source instanceof CharSequence) originalSpec = source.toString();
+            else if (source instanceof Map) {
+                if (originalSpec==null) originalSpec = Strings.toString( ((Map<?,?>)source).get(LocationInternal.ORIGINAL_SPEC) );
+                if (originalSpec==null) originalSpec = Strings.toString( ((Map<?,?>)source).get(LocationInternal.ORIGINAL_SPEC.getName()) );
+            }
+            if (originalSpec!=null) break; 
+        }
+        if (originalSpec==null) originalSpec = finalSpec;
+        if (originalSpec!=null)
+            result.put(LocationInternal.ORIGINAL_SPEC, originalSpec);
+        
+        return result;
+    }
+
+    public static boolean isEnabled(ManagementContext mgmt, String prefix) {
+        ConfigKey<Boolean> key = ConfigKeys.newConfigKeyWithPrefix(prefix+".", LocationConfigKeys.ENABLED);
+        Boolean enabled = mgmt.getConfig().getConfig(key);
+        if (enabled!=null) return enabled.booleanValue();
+        return true;
+    }
+    
+
+}


[38/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core


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

Branch: refs/heads/master
Commit: 64c2b2e5a31c86b44c08d77012b200595d46728c
Parents: d326759
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Tue Aug 18 22:12:56 2015 +0100
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Wed Aug 19 00:52:54 2015 +0100

----------------------------------------------------------------------
 .../brooklyn/sensor/core/HttpRequestSensor.java |  99 ++
 .../brooklyn/sensor/core/StaticSensor.java      |  72 ++
 .../sensor/core/HttpRequestSensorTest.java      |  85 ++
 .../brooklyn/sensor/core/StaticSensorTest.java  |  55 ++
 .../brooklyn/demo/CumulusRDFApplication.java    |   8 +-
 .../brooklyn/demo/ResilientMongoDbApp.java      |   4 +-
 .../brooklyn/demo/NodeJsTodoApplication.java    |   3 +-
 .../demo/WebClusterDatabaseExample.java         |   2 +-
 .../demo/WebClusterDatabaseExampleApp.java      |   4 +-
 ...lusterDatabaseExampleAppIntegrationTest.java |   4 +-
 .../basic/AbstractSoftwareProcessDriver.java    | 516 ----------
 .../basic/AbstractSoftwareProcessSshDriver.java | 658 -------------
 .../AbstractSoftwareProcessWinRmDriver.java     | 193 ----
 .../entity/basic/AbstractVanillaProcess.java    |  35 -
 .../entity/basic/EmptySoftwareProcess.java      |  28 -
 .../basic/EmptySoftwareProcessDriver.java       |  22 -
 .../entity/basic/EmptySoftwareProcessImpl.java  |  39 -
 .../basic/EmptySoftwareProcessSshDriver.java    |  83 --
 .../SameServerDriverLifecycleEffectorTasks.java | 171 ----
 .../brooklyn/entity/basic/SameServerEntity.java |  71 --
 .../entity/basic/SameServerEntityImpl.java      | 129 ---
 .../brooklyn/entity/basic/SoftwareProcess.java  | 362 -------
 .../entity/basic/SoftwareProcessDriver.java     |  75 --
 ...wareProcessDriverLifecycleEffectorTasks.java | 262 -----
 .../entity/basic/SoftwareProcessImpl.java       | 651 -------------
 .../entity/basic/VanillaSoftwareProcess.java    |  62 --
 .../basic/VanillaSoftwareProcessDriver.java     |  23 -
 .../basic/VanillaSoftwareProcessImpl.java       |  37 -
 .../basic/VanillaSoftwareProcessSshDriver.java  | 164 ----
 .../entity/basic/VanillaWindowsProcess.java     |  64 --
 .../basic/VanillaWindowsProcessDriver.java      |  23 -
 .../entity/basic/VanillaWindowsProcessImpl.java |  47 -
 .../basic/VanillaWindowsProcessWinRmDriver.java |  84 --
 .../basic/lifecycle/NaiveScriptRunner.java      |  43 -
 .../entity/basic/lifecycle/ScriptHelper.java    | 436 ---------
 .../entity/basic/lifecycle/ScriptPart.java      |  82 --
 .../entity/brooklynnode/BrooklynCluster.java    |  71 --
 .../brooklynnode/BrooklynClusterImpl.java       | 116 ---
 .../brooklynnode/BrooklynEntityMirror.java      |  68 --
 .../brooklynnode/BrooklynEntityMirrorImpl.java  | 194 ----
 .../entity/brooklynnode/BrooklynNode.java       | 313 ------
 .../entity/brooklynnode/BrooklynNodeDriver.java |  27 -
 .../entity/brooklynnode/BrooklynNodeImpl.java   | 524 ----------
 .../brooklynnode/BrooklynNodeSshDriver.java     | 395 --------
 .../entity/brooklynnode/EntityHttpClient.java   |  93 --
 .../brooklynnode/EntityHttpClientImpl.java      | 162 ----
 .../entity/brooklynnode/LocalBrooklynNode.java  |  37 -
 .../brooklynnode/LocalBrooklynNodeImpl.java     |  46 -
 .../brooklynnode/RemoteEffectorBuilder.java     |  85 --
 .../BrooklynClusterUpgradeEffectorBody.java     | 207 ----
 .../BrooklynNodeUpgradeEffectorBody.java        | 230 -----
 .../effector/SelectMasterEffectorBody.java      | 175 ----
 .../SetHighAvailabilityModeEffectorBody.java    |  64 --
 ...SetHighAvailabilityPriorityEffectorBody.java |  55 --
 .../brooklyn/entity/chef/ChefAttributeFeed.java | 410 --------
 .../entity/chef/ChefAttributePollConfig.java    |  53 --
 .../brooklyn/entity/chef/ChefBashCommands.java  |  42 -
 .../java/brooklyn/entity/chef/ChefConfig.java   |  98 --
 .../java/brooklyn/entity/chef/ChefConfigs.java  | 102 --
 .../java/brooklyn/entity/chef/ChefEntity.java   |  27 -
 .../brooklyn/entity/chef/ChefEntityImpl.java    |  38 -
 .../entity/chef/ChefLifecycleEffectorTasks.java | 362 -------
 .../brooklyn/entity/chef/ChefServerTasks.java   |  97 --
 .../brooklyn/entity/chef/ChefSoloDriver.java    |  87 --
 .../brooklyn/entity/chef/ChefSoloTasks.java     |  71 --
 .../java/brooklyn/entity/chef/ChefTasks.java    | 154 ---
 .../entity/chef/KnifeConvergeTaskFactory.java   | 246 -----
 .../brooklyn/entity/chef/KnifeTaskFactory.java  | 240 -----
 .../java/brooklyn/entity/java/JavaAppUtils.java | 264 -----
 .../brooklyn/entity/java/JavaEntityMethods.java |  30 -
 .../entity/java/JavaSoftwareProcessDriver.java  |  30 -
 .../java/JavaSoftwareProcessSshDriver.java      | 444 ---------
 .../java/brooklyn/entity/java/JmxSupport.java   | 359 -------
 .../brooklyn/entity/java/JmxmpSslSupport.java   | 134 ---
 .../java/brooklyn/entity/java/UsesJava.java     |  68 --
 .../brooklyn/entity/java/UsesJavaMXBeans.java   |  77 --
 .../main/java/brooklyn/entity/java/UsesJmx.java | 190 ----
 .../brooklyn/entity/java/VanillaJavaApp.java    |  78 --
 .../entity/java/VanillaJavaAppDriver.java       |  26 -
 .../entity/java/VanillaJavaAppImpl.java         | 113 ---
 .../entity/java/VanillaJavaAppSshDriver.java    | 212 -----
 .../entity/machine/MachineAttributes.java       |  87 --
 .../brooklyn/entity/machine/MachineEntity.java  |  60 --
 .../entity/machine/MachineEntityImpl.java       | 184 ----
 .../java/brooklyn/entity/pool/ServerPool.java   | 111 ---
 .../brooklyn/entity/pool/ServerPoolImpl.java    | 432 ---------
 .../entity/pool/ServerPoolLocation.java         |  82 --
 .../entity/pool/ServerPoolLocationResolver.java | 138 ---
 .../entity/service/EntityLaunchListener.java    | 111 ---
 .../entity/service/InitdServiceInstaller.java   | 137 ---
 .../entity/service/SystemServiceEnricher.java   | 154 ---
 .../entity/service/SystemServiceInstaller.java  |  25 -
 .../service/SystemServiceInstallerFactory.java  |  28 -
 .../entity/software/MachineInitTasks.java       | 172 ----
 .../software/MachineLifecycleEffectorTasks.java | 949 ------------------
 .../software/ProvidesProvisioningFlags.java     |  34 -
 .../entity/software/SshEffectorTasks.java       | 336 -------
 .../brooklyn/entity/software/StaticSensor.java  |  72 --
 .../entity/software/http/HttpRequestSensor.java |  99 --
 .../software/java/JmxAttributeSensor.java       | 123 ---
 .../entity/software/ssh/SshCommandEffector.java | 104 --
 .../entity/software/ssh/SshCommandSensor.java   | 143 ---
 .../winrm/WindowsPerformanceCounterSensors.java |  73 --
 .../event/feed/jmx/JmxAttributePollConfig.java  |  74 --
 .../java/brooklyn/event/feed/jmx/JmxFeed.java   | 437 ---------
 .../java/brooklyn/event/feed/jmx/JmxHelper.java | 725 --------------
 .../event/feed/jmx/JmxNotificationFilters.java  |  64 --
 .../jmx/JmxNotificationSubscriptionConfig.java  |  95 --
 .../event/feed/jmx/JmxOperationPollConfig.java  | 121 ---
 .../event/feed/jmx/JmxValueFunctions.java       |  95 --
 .../entity/brooklynnode/BrooklynCluster.java    |  70 ++
 .../brooklynnode/BrooklynClusterImpl.java       | 115 +++
 .../brooklynnode/BrooklynEntityMirror.java      |  67 ++
 .../brooklynnode/BrooklynEntityMirrorImpl.java  | 194 ++++
 .../entity/brooklynnode/BrooklynNode.java       | 312 ++++++
 .../entity/brooklynnode/BrooklynNodeDriver.java |  27 +
 .../entity/brooklynnode/BrooklynNodeImpl.java   | 522 ++++++++++
 .../brooklynnode/BrooklynNodeSshDriver.java     | 394 ++++++++
 .../entity/brooklynnode/EntityHttpClient.java   |  93 ++
 .../brooklynnode/EntityHttpClientImpl.java      | 162 ++++
 .../entity/brooklynnode/LocalBrooklynNode.java  |  37 +
 .../brooklynnode/LocalBrooklynNodeImpl.java     |  46 +
 .../brooklynnode/RemoteEffectorBuilder.java     |  84 ++
 .../BrooklynClusterUpgradeEffectorBody.java     | 206 ++++
 .../BrooklynNodeUpgradeEffectorBody.java        | 229 +++++
 .../effector/SelectMasterEffectorBody.java      | 174 ++++
 .../SetHighAvailabilityModeEffectorBody.java    |  63 ++
 ...SetHighAvailabilityPriorityEffectorBody.java |  54 ++
 .../brooklyn/entity/chef/ChefAttributeFeed.java | 410 ++++++++
 .../entity/chef/ChefAttributePollConfig.java    |  53 ++
 .../brooklyn/entity/chef/ChefBashCommands.java  |  42 +
 .../apache/brooklyn/entity/chef/ChefConfig.java |  98 ++
 .../brooklyn/entity/chef/ChefConfigs.java       | 102 ++
 .../apache/brooklyn/entity/chef/ChefEntity.java |  26 +
 .../brooklyn/entity/chef/ChefEntityImpl.java    |  38 +
 .../entity/chef/ChefLifecycleEffectorTasks.java | 360 +++++++
 .../brooklyn/entity/chef/ChefServerTasks.java   |  97 ++
 .../brooklyn/entity/chef/ChefSoloDriver.java    |  85 ++
 .../brooklyn/entity/chef/ChefSoloTasks.java     |  70 ++
 .../apache/brooklyn/entity/chef/ChefTasks.java  | 153 +++
 .../entity/chef/KnifeConvergeTaskFactory.java   | 246 +++++
 .../brooklyn/entity/chef/KnifeTaskFactory.java  | 240 +++++
 .../brooklyn/entity/java/JavaAppUtils.java      | 263 +++++
 .../brooklyn/entity/java/JavaEntityMethods.java |  30 +
 .../entity/java/JavaSoftwareProcessDriver.java  |  30 +
 .../java/JavaSoftwareProcessSshDriver.java      | 443 +++++++++
 .../entity/java/JmxAttributeSensor.java         | 121 +++
 .../apache/brooklyn/entity/java/JmxSupport.java | 357 +++++++
 .../brooklyn/entity/java/JmxmpSslSupport.java   | 134 +++
 .../apache/brooklyn/entity/java/UsesJava.java   |  68 ++
 .../brooklyn/entity/java/UsesJavaMXBeans.java   |  77 ++
 .../apache/brooklyn/entity/java/UsesJmx.java    | 190 ++++
 .../brooklyn/entity/java/VanillaJavaApp.java    |  77 ++
 .../entity/java/VanillaJavaAppDriver.java       |  26 +
 .../entity/java/VanillaJavaAppImpl.java         | 112 +++
 .../entity/java/VanillaJavaAppSshDriver.java    | 211 ++++
 .../entity/machine/MachineAttributes.java       |  87 ++
 .../brooklyn/entity/machine/MachineEntity.java  |  59 ++
 .../entity/machine/MachineEntityImpl.java       | 182 ++++
 .../entity/machine/MachineInitTasks.java        | 172 ++++
 .../machine/ProvidesProvisioningFlags.java      |  35 +
 .../entity/machine/pool/ServerPool.java         | 109 +++
 .../entity/machine/pool/ServerPoolImpl.java     | 432 +++++++++
 .../entity/machine/pool/ServerPoolLocation.java |  82 ++
 .../pool/ServerPoolLocationResolver.java        | 138 +++
 .../base/AbstractSoftwareProcessDriver.java     | 516 ++++++++++
 .../base/AbstractSoftwareProcessSshDriver.java  | 657 +++++++++++++
 .../AbstractSoftwareProcessWinRmDriver.java     | 193 ++++
 .../software/base/AbstractVanillaProcess.java   |  35 +
 .../software/base/EmptySoftwareProcess.java     |  28 +
 .../base/EmptySoftwareProcessDriver.java        |  22 +
 .../software/base/EmptySoftwareProcessImpl.java |  39 +
 .../base/EmptySoftwareProcessSshDriver.java     |  83 ++
 .../SameServerDriverLifecycleEffectorTasks.java | 170 ++++
 .../entity/software/base/SameServerEntity.java  |  71 ++
 .../software/base/SameServerEntityImpl.java     | 128 +++
 .../entity/software/base/SoftwareProcess.java   | 362 +++++++
 .../software/base/SoftwareProcessDriver.java    |  75 ++
 ...wareProcessDriverLifecycleEffectorTasks.java | 261 +++++
 .../software/base/SoftwareProcessImpl.java      | 651 +++++++++++++
 .../software/base/VanillaSoftwareProcess.java   |  62 ++
 .../base/VanillaSoftwareProcessDriver.java      |  23 +
 .../base/VanillaSoftwareProcessImpl.java        |  37 +
 .../base/VanillaSoftwareProcessSshDriver.java   | 162 ++++
 .../software/base/VanillaWindowsProcess.java    |  64 ++
 .../base/VanillaWindowsProcessDriver.java       |  23 +
 .../base/VanillaWindowsProcessImpl.java         |  47 +
 .../base/VanillaWindowsProcessWinRmDriver.java  |  84 ++
 .../MachineLifecycleEffectorTasks.java          | 951 +++++++++++++++++++
 .../base/lifecycle/NaiveScriptRunner.java       |  43 +
 .../software/base/lifecycle/ScriptHelper.java   | 436 +++++++++
 .../software/base/lifecycle/ScriptPart.java     |  82 ++
 .../system_service/EntityLaunchListener.java    | 111 +++
 .../system_service/InitdServiceInstaller.java   | 135 +++
 .../system_service/SystemServiceEnricher.java   | 152 +++
 .../system_service/SystemServiceInstaller.java  |  25 +
 .../SystemServiceInstallerFactory.java          |  28 +
 .../sensor/feed/jmx/JmxAttributePollConfig.java |  74 ++
 .../brooklyn/sensor/feed/jmx/JmxFeed.java       | 436 +++++++++
 .../brooklyn/sensor/feed/jmx/JmxHelper.java     | 724 ++++++++++++++
 .../sensor/feed/jmx/JmxNotificationFilters.java |  64 ++
 .../jmx/JmxNotificationSubscriptionConfig.java  |  95 ++
 .../sensor/feed/jmx/JmxOperationPollConfig.java | 121 +++
 .../sensor/feed/jmx/JmxValueFunctions.java      |  95 ++
 .../brooklyn/sensor/ssh/SshCommandEffector.java | 102 ++
 .../brooklyn/sensor/ssh/SshCommandSensor.java   | 142 +++
 .../brooklyn/sensor/ssh/SshEffectorTasks.java   | 334 +++++++
 .../winrm/WindowsPerformanceCounterSensors.java |  73 ++
 .../entity/brooklynnode/brooklyn-cluster.yaml   |  33 -
 .../brooklyn-node-persisting-to-tmp.yaml        |  27 -
 .../entity/brooklynnode/brooklyn-node.yaml      |  35 -
 .../brooklyn/entity/service/service.sh          |  51 -
 .../entity/brooklynnode/brooklyn-cluster.yaml   |  33 +
 .../brooklyn-node-persisting-to-tmp.yaml        |  27 +
 .../entity/brooklynnode/brooklyn-node.yaml      |  35 +
 .../brooklyn/entity/system_service/service.sh   |  51 +
 .../brooklyn/entity/AbstractEc2LiveTest.java    | 139 ---
 .../entity/AbstractGoogleComputeLiveTest.java   | 137 ---
 .../entity/AbstractSoftlayerLiveTest.java       | 115 ---
 ...ctSoftwareProcessRestartIntegrationTest.java |  97 --
 .../entity/basic/DoNothingSoftwareProcess.java  |  32 -
 .../basic/DoNothingSoftwareProcessDriver.java   |  68 --
 .../basic/DoNothingSoftwareProcessImpl.java     |  37 -
 .../entity/basic/SameServerEntityTest.java      |  83 --
 .../basic/SoftwareProcessEntityLatchTest.java   | 162 ----
 .../basic/SoftwareProcessEntityRebindTest.java  | 181 ----
 .../entity/basic/SoftwareProcessEntityTest.java | 793 ----------------
 ...SoftwareProcessSshDriverIntegrationTest.java | 385 --------
 .../basic/SoftwareProcessSubclassTest.java      | 166 ----
 ...ftwareProcessAndChildrenIntegrationTest.java | 196 ----
 .../entity/basic/lifecycle/MyEntity.java        |  28 -
 .../entity/basic/lifecycle/MyEntityApp.java     |  26 -
 .../entity/basic/lifecycle/MyEntityImpl.java    | 126 ---
 .../basic/lifecycle/NaiveScriptRunnerTest.java  | 252 -----
 .../basic/lifecycle/ScriptHelperTest.java       | 159 ----
 .../basic/lifecycle/StartStopSshDriverTest.java | 170 ----
 .../BrooklynClusterIntegrationTest.java         |  97 --
 .../BrooklynNodeIntegrationTest.java            | 630 ------------
 .../entity/brooklynnode/BrooklynNodeTest.java   | 138 ---
 .../brooklynnode/CallbackEntityHttpClient.java  | 101 --
 .../entity/brooklynnode/MockBrooklynNode.java   |  71 --
 .../brooklynnode/SameBrooklynNodeImpl.java      |  96 --
 .../brooklynnode/SelectMasterEffectorTest.java  | 257 -----
 .../brooklyn/entity/chef/ChefConfigsTest.java   |  50 -
 .../entity/chef/ChefLiveTestSupport.java        |  98 --
 .../chef/ChefServerTasksIntegrationTest.java    | 124 ---
 .../AbstractChefToyMySqlEntityLiveTest.java     |  42 -
 .../ChefSoloDriverMySqlEntityLiveTest.java      |  50 -
 .../mysql/ChefSoloDriverToyMySqlEntity.java     |  90 --
 ...micChefAutodetectToyMySqlEntityLiveTest.java |  43 -
 ...DynamicChefServerToyMySqlEntityLiveTest.java |  51 -
 .../DynamicChefSoloToyMySqlEntityLiveTest.java  |  43 -
 .../chef/mysql/DynamicToyMySqlEntityChef.java   |  82 --
 .../chef/mysql/TypedToyMySqlEntityChef.java     |  56 --
 .../brooklyn/entity/driver/MockSshDriver.java   |  74 --
 ...rWithAvailabilityZonesMultiLocationTest.java | 117 ---
 .../brooklyn/entity/java/EntityPollingTest.java | 206 ----
 .../entity/java/ExampleVanillaMain.java         |  26 -
 .../java/ExampleVanillaMainCpuHungry.java       |  41 -
 .../java/brooklyn/entity/java/JavaOptsTest.java | 357 -------
 ...SoftwareProcessSshDriverIntegrationTest.java | 174 ----
 .../brooklyn/entity/java/JmxSupportTest.java    | 135 ---
 .../brooklyn/entity/java/SslKeyConfigTest.java  |  53 --
 .../entity/java/VanillaJavaAppRebindTest.java   | 173 ----
 .../entity/java/VanillaJavaAppTest.java         | 350 -------
 .../machine/MachineEntityEc2LiveTest.java       |  57 --
 .../entity/machine/MachineEntityRebindTest.java |  45 -
 .../entity/pool/AbstractServerPoolTest.java     | 146 ---
 .../entity/pool/ServerPoolLiveTest.java         |  97 --
 .../pool/ServerPoolLocationResolverTest.java    |  89 --
 .../entity/pool/ServerPoolRebindTest.java       | 108 ---
 .../brooklyn/entity/pool/ServerPoolTest.java    | 174 ----
 .../service/SystemServiceEnricherTest.java      |  96 --
 .../entity/software/AbstractDockerLiveTest.java |  99 --
 .../MachineLifecycleEffectorTasksTest.java      | 140 ---
 .../entity/software/SoftwareEffectorTest.java   | 142 ---
 .../entity/software/SshEffectorTasksTest.java   | 263 -----
 .../entity/software/StaticSensorTest.java       |  54 --
 .../software/http/HttpRequestSensorTest.java    |  84 --
 .../mysql/AbstractToyMySqlEntityTest.java       | 109 ---
 .../mysql/DynamicToyMySqlEntityBuilder.java     | 191 ----
 .../mysql/DynamicToyMySqlEntityTest.java        |  58 --
 .../software/ssh/SshCommandIntegrationTest.java | 124 ---
 .../PortAttributeSensorAndConfigKeyTest.java    |  88 --
 .../brooklyn/event/feed/jmx/JmxFeedTest.java    | 418 --------
 .../brooklyn/event/feed/jmx/JmxHelperTest.java  | 311 ------
 .../event/feed/jmx/RebindJmxFeedTest.java       | 148 ---
 .../usage/ApplicationUsageTrackingTest.java     | 224 -----
 .../usage/LocationUsageTrackingTest.java        | 212 -----
 .../usage/RecordingLegacyUsageListener.java     |  70 --
 .../usage/RecordingUsageListener.java           |  67 --
 .../management/usage/UsageListenerTest.java     | 142 ---
 .../brooklyn/test/GeneralisedDynamicMBean.java  | 146 ---
 .../src/test/java/brooklyn/test/JmxService.java | 173 ----
 .../brooklyn/entity/AbstractEc2LiveTest.java    | 139 +++
 .../entity/AbstractGoogleComputeLiveTest.java   | 137 +++
 .../entity/AbstractSoftlayerLiveTest.java       | 115 +++
 .../BrooklynClusterIntegrationTest.java         |  97 ++
 .../BrooklynNodeIntegrationTest.java            | 632 ++++++++++++
 .../entity/brooklynnode/BrooklynNodeTest.java   | 141 +++
 .../brooklynnode/CallbackEntityHttpClient.java  | 100 ++
 .../entity/brooklynnode/MockBrooklynNode.java   |  72 ++
 .../brooklynnode/SameBrooklynNodeImpl.java      |  97 ++
 .../brooklynnode/SelectMasterEffectorTest.java  | 259 +++++
 .../brooklyn/entity/chef/ChefConfigsTest.java   |  52 +
 .../entity/chef/ChefLiveTestSupport.java        |  99 ++
 .../chef/ChefServerTasksIntegrationTest.java    | 126 +++
 .../AbstractChefToyMySqlEntityLiveTest.java     |  40 +
 .../ChefSoloDriverMySqlEntityLiveTest.java      |  49 +
 .../mysql/ChefSoloDriverToyMySqlEntity.java     |  89 ++
 ...micChefAutodetectToyMySqlEntityLiveTest.java |  43 +
 ...DynamicChefServerToyMySqlEntityLiveTest.java |  50 +
 .../DynamicChefSoloToyMySqlEntityLiveTest.java  |  43 +
 .../chef/mysql/DynamicToyMySqlEntityChef.java   |  81 ++
 .../chef/mysql/TypedToyMySqlEntityChef.java     |  55 ++
 .../brooklyn/entity/java/EntityPollingTest.java | 206 ++++
 .../entity/java/ExampleVanillaMain.java         |  26 +
 .../java/ExampleVanillaMainCpuHungry.java       |  41 +
 .../brooklyn/entity/java/JavaOptsTest.java      | 361 +++++++
 ...SoftwareProcessSshDriverIntegrationTest.java | 173 ++++
 .../brooklyn/entity/java/JmxSupportTest.java    | 135 +++
 .../brooklyn/entity/java/SslKeyConfigTest.java  |  53 ++
 .../entity/java/VanillaJavaAppRebindTest.java   | 173 ++++
 .../entity/java/VanillaJavaAppTest.java         | 352 +++++++
 .../machine/MachineEntityEc2LiveTest.java       |  57 ++
 .../entity/machine/MachineEntityRebindTest.java |  44 +
 .../machine/pool/AbstractServerPoolTest.java    | 145 +++
 .../entity/machine/pool/ServerPoolLiveTest.java |  97 ++
 .../pool/ServerPoolLocationResolverTest.java    |  90 ++
 .../machine/pool/ServerPoolRebindTest.java      | 109 +++
 .../entity/machine/pool/ServerPoolTest.java     | 175 ++++
 .../software/base/AbstractDockerLiveTest.java   |  99 ++
 ...ctSoftwareProcessRestartIntegrationTest.java |  96 ++
 .../software/base/DoNothingSoftwareProcess.java |  33 +
 .../base/DoNothingSoftwareProcessDriver.java    |  69 ++
 .../base/DoNothingSoftwareProcessImpl.java      |  38 +
 .../base/MachineLifecycleEffectorTasksTest.java | 140 +++
 .../software/base/SameServerEntityTest.java     |  84 ++
 .../software/base/SoftwareEffectorTest.java     | 141 +++
 .../base/SoftwareProcessEntityLatchTest.java    | 161 ++++
 .../base/SoftwareProcessEntityRebindTest.java   | 179 ++++
 .../base/SoftwareProcessEntityTest.java         | 798 ++++++++++++++++
 ...SoftwareProcessSshDriverIntegrationTest.java | 389 ++++++++
 .../base/SoftwareProcessSubclassTest.java       | 169 ++++
 ...ftwareProcessAndChildrenIntegrationTest.java | 197 ++++
 .../software/base/lifecycle/MyEntity.java       |  27 +
 .../software/base/lifecycle/MyEntityApp.java    |  26 +
 .../software/base/lifecycle/MyEntityImpl.java   | 125 +++
 .../base/lifecycle/NaiveScriptRunnerTest.java   | 254 +++++
 .../base/lifecycle/ScriptHelperTest.java        | 157 +++
 .../base/lifecycle/StartStopSshDriverTest.java  | 168 ++++
 .../usage/ApplicationUsageTrackingTest.java     | 224 +++++
 .../mgmt/usage/LocationUsageTrackingTest.java   | 210 ++++
 .../usage/RecordingLegacyUsageListener.java     |  70 ++
 .../core/mgmt/usage/RecordingUsageListener.java |  67 ++
 .../test/core/mgmt/usage/UsageListenerTest.java | 142 +++
 .../base/test/driver/MockSshDriver.java         |  72 ++
 ...rWithAvailabilityZonesMultiLocationTest.java | 115 +++
 .../base/test/jmx/GeneralisedDynamicMBean.java  | 146 +++
 .../software/base/test/jmx/JmxService.java      | 172 ++++
 .../location/MachineDetailsEc2LiveTest.java     |  70 ++
 .../MachineDetailsGoogleComputeLiveTest.java    |  67 ++
 .../location/WinRmMachineLocationLiveTest.java  |  92 ++
 .../test/location/WinRmMachineLocationTest.java |  44 +
 .../test/mysql/AbstractToyMySqlEntityTest.java  | 107 +++
 .../mysql/DynamicToyMySqlEntityBuilder.java     | 189 ++++
 .../test/mysql/DynamicToyMySqlEntityTest.java   |  58 ++
 .../PortAttributeSensorAndConfigKeyTest.java    |  86 ++
 .../test/ssh/SshCommandIntegrationTest.java     | 126 +++
 .../SystemServiceEnricherTest.java              |  95 ++
 .../basic/MachineDetailsEc2LiveTest.java        |  68 --
 .../MachineDetailsGoogleComputeLiveTest.java    |  65 --
 .../basic/WinRmMachineLocationLiveTest.java     |  92 --
 .../basic/WinRmMachineLocationTest.java         |  43 -
 .../brooklyn/sensor/feed/jmx/JmxFeedTest.java   | 422 ++++++++
 .../brooklyn/sensor/feed/jmx/JmxHelperTest.java | 311 ++++++
 .../sensor/feed/jmx/RebindJmxFeedTest.java      | 148 +++
 .../sensor/ssh/SshEffectorTasksTest.java        | 264 +++++
 .../resources/brooklyn/entity/basic/frogs.txt   |  27 -
 .../brooklyn/entity/basic/template.yaml         |  23 -
 .../basic/template_with_extra_substitutions.txt |  18 -
 .../brooklyn-tests.pem                          |  27 -
 .../brooklyn-validator.pem                      |  27 -
 .../hosted-chef-brooklyn-credentials/knife.rb   |  27 -
 .../brooklyn-tests.pem                          |  27 +
 .../brooklyn-validator.pem                      |  27 +
 .../hosted-chef-brooklyn-credentials/knife.rb   |  27 +
 .../brooklyn/entity/software/base/frogs.txt     |  27 +
 .../brooklyn/entity/software/base/template.yaml |  23 +
 .../base/template_with_extra_substitutions.txt  |  18 +
 .../entity/database/crate/CrateNode.java        |  12 +-
 .../entity/database/crate/CrateNodeDriver.java  |   2 +-
 .../entity/database/crate/CrateNodeImpl.java    |   7 +-
 .../database/crate/CrateNodeSshDriver.java      |   3 +-
 .../entity/database/mariadb/MariaDbDriver.java  |   3 +-
 .../entity/database/mariadb/MariaDbNode.java    |   4 +-
 .../database/mariadb/MariaDbNodeImpl.java       |   4 +-
 .../database/mariadb/MariaDbSshDriver.java      |   8 +-
 .../entity/database/mysql/MySqlDriver.java      |   3 +-
 .../entity/database/mysql/MySqlNode.java        |   4 +-
 .../entity/database/mysql/MySqlNodeImpl.java    |   4 +-
 .../entity/database/mysql/MySqlSshDriver.java   |   8 +-
 .../database/postgresql/PostgreSqlDriver.java   |   5 +-
 .../database/postgresql/PostgreSqlNode.java     |   4 +-
 .../PostgreSqlNodeChefImplFromScratch.java      |  10 +-
 .../database/postgresql/PostgreSqlNodeImpl.java |   3 +-
 .../database/postgresql/PostgreSqlSpecs.java    |   5 +-
 .../postgresql/PostgreSqlSshDriver.java         |   9 +-
 .../entity/database/rubyrep/RubyRepDriver.java  |   2 +-
 .../entity/database/rubyrep/RubyRepNode.java    |   4 +-
 .../database/rubyrep/RubyRepNodeImpl.java       |   3 +-
 .../database/rubyrep/RubyRepSshDriver.java      |   4 +-
 .../brooklyn/entity/database/mssql/mssql.yaml   |   2 +-
 .../database/mariadb/MariaDbLiveEc2Test.java    |   4 +-
 .../database/mysql/MySqlClusterLiveEc2Test.java |   4 +-
 .../mysql/MySqlClusterLiveSoftlayerTest.java    |   4 +-
 .../entity/database/mysql/MySqlLiveEc2Test.java |   4 +-
 .../entity/database/mysql/MySqlLiveGceTest.java |   4 +-
 .../mysql/MySqlRestartIntegrationTest.java      |   5 +-
 .../database/mysql/MysqlDockerLiveTest.java     |   3 +-
 .../postgresql/PostgreSqDockerLiveTest.java     |   3 +-
 .../database/postgresql/PostgreSqlChefTest.java |   8 +-
 .../postgresql/PostgreSqlEc2LiveTest.java       |   4 +-
 .../postgresql/PostgreSqlGceLiveTest.java       |   4 +-
 .../PostgreSqlRestartIntegrationTest.java       |   5 +-
 .../database/rubyrep/RubyRepEc2LiveTest.java    |   4 +-
 .../messaging/activemq/ActiveMQBroker.java      |   6 +-
 .../messaging/activemq/ActiveMQBrokerImpl.java  |   9 +-
 .../activemq/ActiveMQDestinationImpl.java       |   5 +-
 .../messaging/activemq/ActiveMQDriver.java      |   2 +-
 .../messaging/activemq/ActiveMQQueueImpl.java   |   5 +-
 .../messaging/activemq/ActiveMQSshDriver.java   |   3 +-
 .../entity/messaging/jms/JMSBroker.java         |   2 +-
 .../entity/messaging/jms/JMSBrokerImpl.java     |   4 +-
 .../kafka/AbstractfKafkaSshDriver.java          |   4 +-
 .../brooklyn/entity/messaging/kafka/Kafka.java  |   3 +-
 .../entity/messaging/kafka/KafkaBroker.java     |   6 +-
 .../messaging/kafka/KafkaBrokerDriver.java      |   2 +-
 .../entity/messaging/kafka/KafkaBrokerImpl.java |  11 +-
 .../messaging/kafka/KafkaBrokerSshDriver.java   |   6 +-
 .../entity/messaging/kafka/KafkaZooKeeper.java  |   4 +-
 .../messaging/kafka/KafkaZooKeeperDriver.java   |   2 +-
 .../entity/messaging/qpid/QpidBroker.java       |   6 +-
 .../entity/messaging/qpid/QpidBrokerImpl.java   |  11 +-
 .../messaging/qpid/QpidDestinationImpl.java     |   9 +-
 .../entity/messaging/qpid/QpidDriver.java       |   2 +-
 .../entity/messaging/qpid/QpidQueueImpl.java    |   5 +-
 .../entity/messaging/qpid/QpidSshDriver.java    |   4 +-
 .../entity/messaging/rabbit/RabbitBroker.java   |   4 +-
 .../messaging/rabbit/RabbitBrokerImpl.java      |   3 +-
 .../entity/messaging/rabbit/RabbitDriver.java   |   2 +-
 .../messaging/rabbit/RabbitSshDriver.java       |   5 +-
 .../brooklyn/entity/messaging/storm/Storm.java  |   6 +-
 .../entity/messaging/storm/StormDriver.java     |   2 +-
 .../entity/messaging/storm/StormImpl.java       |  11 +-
 .../entity/messaging/storm/StormSshDriver.java  |   6 +-
 .../entity/zookeeper/AbstractZooKeeperImpl.java |  11 +-
 .../entity/zookeeper/ZooKeeperDriver.java       |   2 +-
 .../entity/zookeeper/ZooKeeperNode.java         |   3 +-
 .../entity/zookeeper/ZooKeeperSshDriver.java    |   4 +-
 .../messaging/activemq/ActiveMQEc2LiveTest.java |   3 +-
 .../activemq/ActiveMQGoogleComputeLiveTest.java |   3 +-
 .../activemq/ActiveMQIntegrationTest.java       |   5 +-
 .../entity/messaging/kafka/KafkaLiveTest.java   |   3 +-
 .../entity/messaging/qpid/QpidEc2LiveTest.java  |   3 +-
 .../messaging/qpid/QpidIntegrationTest.java     |   3 +-
 .../messaging/rabbit/RabbitEc2LiveTest.java     |   4 +-
 .../messaging/storm/StormEc2LiveTest.java       |   4 +-
 .../zookeeper/ZooKeeperEc2LiveTest.java         |   4 +-
 .../entity/monitoring/monit/MonitDriver.java    |   2 +-
 .../entity/monitoring/monit/MonitNode.java      |   3 +-
 .../entity/monitoring/monit/MonitNodeImpl.java  |   3 +-
 .../entity/monitoring/monit/MonitSshDriver.java |   5 +-
 .../monitoring/monit/MonitIntegrationTest.java  |   5 +-
 .../entity/network/bind/BindDnsServer.java      |   4 +-
 .../network/bind/BindDnsServerDriver.java       |   4 +-
 .../entity/network/bind/BindDnsServerImpl.java  |   3 +-
 .../network/bind/BindDnsServerSshDriver.java    |   3 +-
 .../network/bind/BindDnsServerEc2LiveTest.java  |   4 +-
 .../bind/BindDnsServerIntegrationTest.java      |   3 +-
 .../network/bind/BindDnsServerLiveTest.java     |   5 +-
 .../bind/BindDnsServerSoftlayerLiveTest.java    |   4 +-
 .../bind/DoNothingSoftwareProcessDriver.java    |   6 +-
 .../entity/nosql/cassandra/CassandraNode.java   |  10 +-
 .../nosql/cassandra/CassandraNodeDriver.java    |   3 +-
 .../nosql/cassandra/CassandraNodeImpl.java      |  14 +-
 .../nosql/cassandra/CassandraNodeSshDriver.java |   8 +-
 .../nosql/couchbase/CouchbaseClusterImpl.java   |   4 +-
 .../entity/nosql/couchbase/CouchbaseNode.java   |   3 +-
 .../nosql/couchbase/CouchbaseNodeDriver.java    |   3 +-
 .../nosql/couchbase/CouchbaseNodeImpl.java      |   4 +-
 .../nosql/couchbase/CouchbaseNodeSshDriver.java |   6 +-
 .../nosql/couchbase/CouchbaseSyncGateway.java   |   3 +-
 .../couchbase/CouchbaseSyncGatewayDriver.java   |   2 +-
 .../couchbase/CouchbaseSyncGatewayImpl.java     |   3 +-
 .../CouchbaseSyncGatewaySshDriver.java          |   4 +-
 .../entity/nosql/couchdb/CouchDBNode.java       |   3 +-
 .../entity/nosql/couchdb/CouchDBNodeDriver.java |   2 +-
 .../entity/nosql/couchdb/CouchDBNodeImpl.java   |   3 +-
 .../nosql/couchdb/CouchDBNodeSshDriver.java     |   4 +-
 .../nosql/elasticsearch/ElasticSearchNode.java  |   4 +-
 .../elasticsearch/ElasticSearchNodeDriver.java  |   2 +-
 .../elasticsearch/ElasticSearchNodeImpl.java    |   4 +-
 .../ElasticSearchNodeSshDriver.java             |   4 +-
 .../nosql/mongodb/AbstractMongoDBServer.java    |   3 +-
 .../nosql/mongodb/AbstractMongoDBSshDriver.java |   6 +-
 .../nosql/mongodb/MongoDBClientDriver.java      |   2 +-
 .../entity/nosql/mongodb/MongoDBClientImpl.java |   3 +-
 .../entity/nosql/mongodb/MongoDBDriver.java     |   2 +-
 .../entity/nosql/mongodb/MongoDBServerImpl.java |   4 +-
 .../sharding/CoLocatedMongoDBRouter.java        |   3 +-
 .../sharding/CoLocatedMongoDBRouterImpl.java    |   3 +-
 .../sharding/MongoDBConfigServerDriver.java     |   2 +-
 .../sharding/MongoDBConfigServerImpl.java       |   2 +-
 .../mongodb/sharding/MongoDBRouterDriver.java   |   2 +-
 .../mongodb/sharding/MongoDBRouterImpl.java     |   3 +-
 .../brooklyn/entity/nosql/redis/RedisStore.java |   3 +-
 .../entity/nosql/redis/RedisStoreDriver.java    |   2 +-
 .../entity/nosql/redis/RedisStoreImpl.java      |   4 +-
 .../entity/nosql/redis/RedisStoreSshDriver.java |   4 +-
 .../brooklyn/entity/nosql/riak/RiakNode.java    |   5 +-
 .../entity/nosql/riak/RiakNodeDriver.java       |   4 +-
 .../entity/nosql/riak/RiakNodeImpl.java         |   4 +-
 .../entity/nosql/riak/RiakNodeSshDriver.java    |   9 +-
 .../brooklyn/entity/nosql/solr/SolrServer.java  |  10 +-
 .../entity/nosql/solr/SolrServerDriver.java     |   4 +-
 .../entity/nosql/solr/SolrServerImpl.java       |   3 +-
 .../entity/nosql/solr/SolrServerSshDriver.java  |   5 +-
 .../cassandra/CassandraDatacenterTest.java      |   6 +-
 .../nosql/cassandra/CassandraFabricTest.java    |   4 +-
 .../cassandra/CassandraNodeEc2LiveTest.java     |   3 +-
 .../CouchbaseSyncGatewayEc2LiveTest.java        |   3 +-
 .../nosql/couchdb/CouchDBNodeEc2LiveTest.java   |   3 +-
 .../nosql/mongodb/MongoDBEc2LiveTest.java       |   3 +-
 .../mongodb/MongoDBReplicaSetEc2LiveTest.java   |   3 +-
 .../mongodb/MongoDBRestartIntegrationTest.java  |   5 +-
 .../nosql/mongodb/MongoDBSoftLayerLiveTest.java |   3 +-
 .../MongoDBShardedDeploymentEc2LiveTest.java    |   3 +-
 .../entity/nosql/redis/RedisEc2LiveTest.java    |   3 +-
 .../nosql/riak/RiakClusterEc2LiveTest.java      |   3 +-
 .../entity/nosql/riak/RiakNodeEc2LiveTest.java  |   3 +-
 .../riak/RiakNodeGoogleComputeLiveTest.java     |   3 +-
 .../nosql/riak/RiakNodeSoftlayerLiveTest.java   |   3 +-
 .../nosql/solr/SolrServerEc2LiveTest.java       |   3 +-
 .../entity/osgi/karaf/KarafContainer.java       |   7 +-
 .../entity/osgi/karaf/KarafContainerImpl.java   |  13 +-
 .../brooklyn/entity/osgi/karaf/KarafDriver.java |   2 +-
 .../entity/osgi/karaf/KarafSshDriver.java       |   3 +-
 .../osgi/karaf/KarafContainerEc2LiveTest.java   |   3 +-
 .../entity/osgi/karaf/KarafContainerTest.java   |   4 +-
 .../entity/proxy/AbstractController.java        |   3 +-
 .../entity/proxy/AbstractControllerImpl.java    |   4 +-
 .../entity/proxy/nginx/NginxController.java     |   3 +-
 .../entity/proxy/nginx/NginxDriver.java         |   2 +-
 .../entity/proxy/nginx/NginxSshDriver.java      |   6 +-
 .../entity/webapp/JavaWebAppDriver.java         |   2 +-
 .../entity/webapp/JavaWebAppService.java        |   3 +-
 .../webapp/JavaWebAppSoftwareProcess.java       |   2 +-
 .../webapp/JavaWebAppSoftwareProcessImpl.java   |   5 +-
 .../entity/webapp/JavaWebAppSshDriver.java      |   3 +-
 .../entity/webapp/jboss/JBoss6Server.java       |   5 +-
 .../entity/webapp/jboss/JBoss6ServerImpl.java   |   5 +-
 .../entity/webapp/jboss/JBoss6SshDriver.java    |   6 +-
 .../entity/webapp/jboss/JBoss7Server.java       |   3 +-
 .../entity/webapp/jboss/JBoss7SshDriver.java    |   4 +-
 .../entity/webapp/jetty/Jetty6Server.java       |   5 +-
 .../entity/webapp/jetty/Jetty6ServerImpl.java   |   9 +-
 .../webapp/nodejs/NodeJsWebAppDriver.java       |   2 +-
 .../webapp/nodejs/NodeJsWebAppService.java      |   4 +-
 .../webapp/nodejs/NodeJsWebAppServiceImpl.java  |   4 +-
 .../webapp/nodejs/NodeJsWebAppSshDriver.java    |   6 +-
 .../entity/webapp/tomcat/Tomcat8Server.java     |   3 +-
 .../entity/webapp/tomcat/TomcatServer.java      |   6 +-
 .../entity/webapp/tomcat/TomcatServerImpl.java  |   7 +-
 .../proxy/TrackingAbstractControllerImpl.java   |   3 +-
 .../entity/proxy/nginx/NginxEc2LiveTest.java    |   5 +-
 .../nginx/NginxHttpsSslIntegrationTest.java     |   4 +-
 .../proxy/nginx/NginxIntegrationTest.java       |   3 +-
 .../proxy/nginx/NginxRebindIntegrationTest.java |   4 +-
 .../AbstractWebAppFixtureIntegrationTest.java   |   7 +-
 .../ControlledDynamicWebAppClusterTest.java     |   4 +-
 ...namicWebAppClusterRebindIntegrationTest.java |   4 +-
 .../jboss/JBoss6ServerAwsEc2LiveTest.java       |   3 +-
 ...Boss6ServerNonInheritingIntegrationTest.java |   4 +-
 .../jboss/JBoss7ServerAwsEc2LiveTest.java       |   3 +-
 .../jboss/JBoss7ServerDockerLiveTest.java       |   3 +-
 .../JBoss7ServerRebindingIntegrationTest.java   |   4 +-
 ...ultiVersionWebAppFixtureIntegrationTest.java |   4 +-
 .../Jboss7ServerGoogleComputeLiveTest.java      |   3 +-
 .../JettyWebAppFixtureIntegrationTest.java      |   4 +-
 .../webapp/nodejs/NodeJsWebAppEc2LiveTest.java  |   3 +-
 .../NodeJsWebAppFixtureIntegrationTest.java     |   3 +-
 .../nodejs/NodeJsWebAppSoftlayerLiveTest.java   |   3 +-
 .../webapp/tomcat/Tomcat8ServerEc2LiveTest.java |   4 +-
 .../Tomcat8ServerRestartIntegrationTest.java    |   5 +-
 .../tomcat/Tomcat8ServerSoftlayerLiveTest.java  |   4 +-
 ...mcat8ServerWebAppFixtureIntegrationTest.java |   4 +-
 ...ableRetrieveUsageMetricsIntegrationTest.java |   4 +-
 .../webapp/tomcat/TomcatServerEc2LiveTest.java  |   3 +-
 .../TomcatServerRestartIntegrationTest.java     |   5 +-
 .../tomcat/TomcatServerSoftlayerLiveTest.java   |   3 +-
 ...omcatServerWebAppFixtureIntegrationTest.java |   4 +-
 .../test/entity/TestJavaWebAppEntity.java       |   7 +-
 .../test/entity/TestJavaWebAppEntityImpl.java   |   3 +-
 .../service/CatalogServiceTypeResolver.java     |   7 +-
 .../service/ChefServiceTypeResolver.java        |   5 +-
 .../camp/brooklyn/ByonLocationsYamlTest.java    |   3 +-
 .../brooklyn/EmptySoftwareProcessYamlTest.java  |   4 +-
 .../camp/brooklyn/EntitiesYamlTest.java         |   3 +-
 .../test/resources/same-server-entity-test.yaml |   2 +-
 .../apache/brooklyn/cli/lister/ClassFinder.java |   3 +-
 .../main/webapp/assets/js/view/script-groovy.js |   2 +-
 .../specs/model/catalog-application-spec.js     |   8 +-
 .../specs/model/sensor-summary-spec.js          |   2 +-
 .../brooklyn/launcher/BrooklynLauncher.java     |   7 +-
 .../entity/basic/VanillaSoftwareYamlTest.java   |   4 +-
 .../BrooklynEntityMirrorIntegrationTest.java    |   4 +-
 .../brooklynnode/BrooklynNodeRestTest.java      |   9 +-
 .../blueprints/AbstractBlueprintTest.java       |   4 +-
 .../qa/load/SimulatedMySqlNodeImpl.java         |   5 +-
 .../brooklyn/qa/load/SimulatedTheeTierApp.java  |   3 +-
 .../SoftlayerObtainPrivateLiveTest.java         |   7 +-
 .../src/main/resources/reset-catalog.xml        |   2 +-
 .../rest/resources/ServerResourceTest.java      |   7 +-
 .../rest/resources/UsageResourceTest.java       |   4 +-
 .../brooklynnode/DeployBlueprintTest.java       |   5 +-
 .../testing/mocks/RestMockSimpleEntity.java     |   6 +-
 .../rest/util/EntityLocationUtilsTest.java      |   4 +-
 628 files changed, 28689 insertions(+), 29041 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/core/src/main/java/org/apache/brooklyn/sensor/core/HttpRequestSensor.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/sensor/core/HttpRequestSensor.java b/core/src/main/java/org/apache/brooklyn/sensor/core/HttpRequestSensor.java
new file mode 100644
index 0000000..2277d49
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/sensor/core/HttpRequestSensor.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.core;
+
+import java.net.URI;
+
+import net.minidev.json.JSONObject;
+
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.effector.core.AddSensor;
+import org.apache.brooklyn.entity.java.JmxAttributeSensor;
+import org.apache.brooklyn.entity.software.ssh.SshCommandSensor;
+import org.apache.brooklyn.sensor.core.HttpRequestSensor;
+import org.apache.brooklyn.sensor.feed.http.HttpFeed;
+import org.apache.brooklyn.sensor.feed.http.HttpPollConfig;
+import org.apache.brooklyn.sensor.feed.http.HttpValueFunctions;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Functions;
+import com.google.common.base.Supplier;
+
+/**
+ * Configurable {@link org.apache.brooklyn.api.entity.EntityInitializer} which adds an HTTP sensor feed to retrieve the
+ * {@link JSONObject} from a JSON response in order to populate the sensor with the data at the {@code jsonPath}.
+ *
+ * @see SshCommandSensor
+ * @see JmxAttributeSensor
+ */
+@Beta
+public final class HttpRequestSensor<T> extends AddSensor<T> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(HttpRequestSensor.class);
+
+    public static final ConfigKey<String> SENSOR_URI = ConfigKeys.newStringConfigKey("uri", "HTTP URI to poll for JSON");
+    public static final ConfigKey<String> JSON_PATH = ConfigKeys.newStringConfigKey("jsonPath", "JSON path to select in HTTP response; default $", "$");
+    public static final ConfigKey<String> USERNAME = ConfigKeys.newStringConfigKey("username", "Username for HTTP request, if required");
+    public static final ConfigKey<String> PASSWORD = ConfigKeys.newStringConfigKey("password", "Password for HTTP request, if required");
+
+    protected final Supplier<URI> uri;
+    protected final String jsonPath;
+    protected final String username;
+    protected final String password;
+
+    public HttpRequestSensor(final ConfigBag params) {
+        super(params);
+
+        uri = new Supplier<URI>() {
+            @Override
+            public URI get() {
+                return URI.create(params.get(SENSOR_URI));
+            }
+        };
+        jsonPath = params.get(JSON_PATH);
+        username = params.get(USERNAME);
+        password = params.get(PASSWORD);
+    }
+
+    @Override
+    public void apply(final EntityLocal entity) {
+        super.apply(entity);
+
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Adding HTTP JSON sensor {} to {}", name, entity);
+        }
+
+        HttpPollConfig<T> pollConfig = new HttpPollConfig<T>(sensor)
+                .checkSuccess(HttpValueFunctions.responseCodeEquals(200))
+                .onFailureOrException(Functions.constant((T) null))
+                .onSuccess(HttpValueFunctions.<T>jsonContentsFromPath(jsonPath))
+                .period(period);
+
+        HttpFeed.builder().entity(entity)
+                .baseUri(uri)
+                .credentialsIfNotNull(username, password)
+                .poll(pollConfig)
+                .build();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/core/src/main/java/org/apache/brooklyn/sensor/core/StaticSensor.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/sensor/core/StaticSensor.java b/core/src/main/java/org/apache/brooklyn/sensor/core/StaticSensor.java
new file mode 100644
index 0000000..29e679d
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/sensor/core/StaticSensor.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.core;
+
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.mgmt.Task;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.effector.core.AddSensor;
+import org.apache.brooklyn.sensor.enricher.Propagator;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.core.task.Tasks;
+import org.apache.brooklyn.util.core.task.ValueResolver;
+import org.apache.brooklyn.util.guava.Maybe;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Supplier;
+
+/** 
+ * Provides an initializer/feed which simply sets a given value.
+ * <p>
+ * {@link Task}/{@link Supplier} values are resolved when written,
+ * unlike config values which are resolved on each read.
+ * <p>
+ * This supports a {@link StaticSensor#SENSOR_PERIOD} 
+ * which can be useful if the supplied value is such a function.
+ * However when the source is another sensor,
+ * consider using {@link Propagator} which listens for changes instead. */
+public class StaticSensor<T> extends AddSensor<T> {
+
+    private static final Logger log = LoggerFactory.getLogger(StaticSensor.class);
+    
+    public static final ConfigKey<Object> STATIC_VALUE = ConfigKeys.newConfigKey(Object.class, "static.value");
+
+    private final Object value;
+
+    public StaticSensor(ConfigBag params) {
+        super(params);
+        value = params.get(STATIC_VALUE);
+    }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public void apply(EntityLocal entity) {
+        super.apply(entity);
+        
+        Maybe<T> v = Tasks.resolving(value).as((Class<T>)sensor.getType()).timeout(ValueResolver.PRETTY_QUICK_WAIT).getMaybe();
+        if (v.isPresent()) {
+            log.debug(this+" setting sensor "+sensor+" to "+v.get());
+            entity.setAttribute(sensor, v.get());
+        } else {
+            log.debug(this+" not setting sensor "+sensor+"; cannot resolve "+value);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/core/src/test/java/org/apache/brooklyn/sensor/core/HttpRequestSensorTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/sensor/core/HttpRequestSensorTest.java b/core/src/test/java/org/apache/brooklyn/sensor/core/HttpRequestSensorTest.java
new file mode 100644
index 0000000..91120e6
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/sensor/core/HttpRequestSensorTest.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.core;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.core.test.TestHttpRequestHandler;
+import org.apache.brooklyn.core.test.TestHttpServer;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.entity.core.Attributes;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.sensor.core.HttpRequestSensor;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.time.Duration;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+
+public class HttpRequestSensorTest {
+    final static AttributeSensor<String> SENSOR_STRING = Sensors.newStringSensor("aString");
+    final static String TARGET_TYPE = "java.lang.String";
+
+    private TestApplication app;
+    private EntityLocal entity;
+
+    private TestHttpServer server;
+    private String serverUrl;
+
+    @BeforeClass(alwaysRun=true)
+    public void setUp() throws Exception {
+        server = new TestHttpServer()
+            .handler("/myKey/myValue", new TestHttpRequestHandler().header("Content-Type", "application/json").response("{\"myKey\":\"myValue\"}"))
+            .start();
+        serverUrl = server.getUrl();
+
+        app = TestApplication.Factory.newManagedInstanceForTests();
+        entity = app.createAndManageChild(EntitySpec.create(TestEntity.class)
+                .location(app.newLocalhostProvisioningLocation().obtain()));
+        app.start(ImmutableList.<Location>of());
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (app != null) Entities.destroyAll(app.getManagementContext());
+        server.stop();
+    }
+
+    @Test
+    public void testHttpSensor() throws Exception {
+        HttpRequestSensor<Integer> sensor = new HttpRequestSensor<Integer>(ConfigBag.newInstance()
+                .configure(HttpRequestSensor.SENSOR_PERIOD, Duration.millis(100))
+                .configure(HttpRequestSensor.SENSOR_NAME, SENSOR_STRING.getName())
+                .configure(HttpRequestSensor.SENSOR_TYPE, TARGET_TYPE)
+                .configure(HttpRequestSensor.JSON_PATH, "$.myKey")
+                .configure(HttpRequestSensor.SENSOR_URI, serverUrl + "/myKey/myValue"));
+        sensor.apply(entity);
+        entity.setAttribute(Attributes.SERVICE_UP, true);
+
+        EntityTestUtils.assertAttributeEqualsEventually(entity, SENSOR_STRING, "myValue");
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/core/src/test/java/org/apache/brooklyn/sensor/core/StaticSensorTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/sensor/core/StaticSensorTest.java b/core/src/test/java/org/apache/brooklyn/sensor/core/StaticSensorTest.java
new file mode 100644
index 0000000..a62d985
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/sensor/core/StaticSensorTest.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.sensor.core;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.entity.stock.BasicEntity;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.sensor.core.StaticSensor;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableMap;
+
+public class StaticSensorTest extends BrooklynAppUnitTestSupport {
+
+    @Test
+    public void testAddsStaticSensorOfTypeString() {
+        BasicEntity entity = app.createAndManageChild(EntitySpec.create(BasicEntity.class)
+                .addInitializer(new StaticSensor<String>(ConfigBag.newInstance(ImmutableMap.of(
+                        StaticSensor.SENSOR_NAME, "myname",
+                        StaticSensor.SENSOR_TYPE, String.class.getName(),
+                        StaticSensor.STATIC_VALUE, "myval")))));
+        
+        EntityTestUtils.assertAttributeEquals(entity, Sensors.newSensor(String.class, "myname"), "myval");
+    }
+    
+    @Test
+    public void testAddsStaticSensorOfTypeInteger() {
+        BasicEntity entity = app.createAndManageChild(EntitySpec.create(BasicEntity.class)
+                .addInitializer(new StaticSensor<Integer>(ConfigBag.newInstance(ImmutableMap.of(
+                        StaticSensor.SENSOR_NAME, "myname",
+                        StaticSensor.SENSOR_TYPE, Integer.class.getName(),
+                        StaticSensor.STATIC_VALUE, "1")))));
+        
+        EntityTestUtils.assertAttributeEquals(entity, Sensors.newSensor(Integer.class, "myname"), 1);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/examples/simple-nosql-cluster/src/main/java/org/apache/brooklyn/demo/CumulusRDFApplication.java
----------------------------------------------------------------------
diff --git a/examples/simple-nosql-cluster/src/main/java/org/apache/brooklyn/demo/CumulusRDFApplication.java b/examples/simple-nosql-cluster/src/main/java/org/apache/brooklyn/demo/CumulusRDFApplication.java
index bcdd143..26891d5 100644
--- a/examples/simple-nosql-cluster/src/main/java/org/apache/brooklyn/demo/CumulusRDFApplication.java
+++ b/examples/simple-nosql-cluster/src/main/java/org/apache/brooklyn/demo/CumulusRDFApplication.java
@@ -42,6 +42,8 @@ import org.apache.brooklyn.entity.core.AbstractApplication;
 import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.core.EntityInternal;
 import org.apache.brooklyn.entity.core.StartableApplication;
+import org.apache.brooklyn.entity.java.UsesJava;
+import org.apache.brooklyn.entity.java.UsesJmx;
 import org.apache.brooklyn.entity.lifecycle.Lifecycle;
 import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
 import org.apache.brooklyn.entity.nosql.cassandra.CassandraDatacenter;
@@ -50,17 +52,13 @@ import org.apache.brooklyn.entity.nosql.cassandra.CassandraNode;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.entity.webapp.JavaWebAppService;
 import org.apache.brooklyn.entity.webapp.tomcat.TomcatServer;
-
-import brooklyn.entity.java.UsesJava;
-import brooklyn.entity.java.UsesJmx;
-import brooklyn.entity.software.SshEffectorTasks;
-
 import org.apache.brooklyn.launcher.BrooklynLauncher;
 import org.apache.brooklyn.location.basic.PortRanges;
 import org.apache.brooklyn.policy.ha.ServiceFailureDetector;
 import org.apache.brooklyn.policy.ha.ServiceReplacer;
 import org.apache.brooklyn.policy.ha.ServiceRestarter;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
 import org.apache.brooklyn.util.CommandLineUtil;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/examples/simple-nosql-cluster/src/main/java/org/apache/brooklyn/demo/ResilientMongoDbApp.java
----------------------------------------------------------------------
diff --git a/examples/simple-nosql-cluster/src/main/java/org/apache/brooklyn/demo/ResilientMongoDbApp.java b/examples/simple-nosql-cluster/src/main/java/org/apache/brooklyn/demo/ResilientMongoDbApp.java
index ab70e77..fdce4d0 100644
--- a/examples/simple-nosql-cluster/src/main/java/org/apache/brooklyn/demo/ResilientMongoDbApp.java
+++ b/examples/simple-nosql-cluster/src/main/java/org/apache/brooklyn/demo/ResilientMongoDbApp.java
@@ -33,9 +33,7 @@ import org.apache.brooklyn.entity.core.StartableApplication;
 import org.apache.brooklyn.entity.group.DynamicCluster;
 import org.apache.brooklyn.entity.nosql.mongodb.MongoDBReplicaSet;
 import org.apache.brooklyn.entity.nosql.mongodb.MongoDBServer;
-
-import brooklyn.entity.basic.SoftwareProcess;
-
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.launcher.BrooklynLauncher;
 import org.apache.brooklyn.policy.ha.ServiceFailureDetector;
 import org.apache.brooklyn.policy.ha.ServiceReplacer;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/NodeJsTodoApplication.java
----------------------------------------------------------------------
diff --git a/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/NodeJsTodoApplication.java b/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/NodeJsTodoApplication.java
index fd3a22c..eed6a05 100644
--- a/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/NodeJsTodoApplication.java
+++ b/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/NodeJsTodoApplication.java
@@ -26,12 +26,11 @@ import org.apache.brooklyn.entity.core.AbstractApplication;
 import org.apache.brooklyn.entity.core.Attributes;
 import org.apache.brooklyn.entity.core.StartableApplication;
 import org.apache.brooklyn.entity.nosql.redis.RedisStore;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.trait.Startable;
 import org.apache.brooklyn.entity.webapp.nodejs.NodeJsWebAppService;
 import org.apache.brooklyn.sensor.core.DependentConfiguration;
 
-import brooklyn.entity.basic.SoftwareProcess;
-
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExample.java
----------------------------------------------------------------------
diff --git a/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExample.java b/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExample.java
index a22a8a6..8682335 100644
--- a/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExample.java
+++ b/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExample.java
@@ -18,7 +18,7 @@
  */
 package org.apache.brooklyn.demo;
 
-import static brooklyn.entity.java.JavaEntityMethods.javaSysProp;
+import static org.apache.brooklyn.entity.java.JavaEntityMethods.javaSysProp;
 import static org.apache.brooklyn.sensor.core.DependentConfiguration.attributeWhenReady;
 import static org.apache.brooklyn.sensor.core.DependentConfiguration.formatString;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleApp.java
----------------------------------------------------------------------
diff --git a/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleApp.java b/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleApp.java
index a988440..e13a632 100644
--- a/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleApp.java
+++ b/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleApp.java
@@ -42,9 +42,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.core.StartableApplication;
 import org.apache.brooklyn.entity.database.mysql.MySqlNode;
 import org.apache.brooklyn.entity.group.DynamicCluster;
-
-import brooklyn.entity.java.JavaEntityMethods;
-
+import org.apache.brooklyn.entity.java.JavaEntityMethods;
 import org.apache.brooklyn.launcher.BrooklynLauncher;
 import org.apache.brooklyn.location.basic.PortRanges;
 import org.apache.brooklyn.policy.autoscaling.AutoScalerPolicy;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/examples/simple-web-cluster/src/test/java/org/apache/brooklyn/demo/RebindWebClusterDatabaseExampleAppIntegrationTest.java
----------------------------------------------------------------------
diff --git a/examples/simple-web-cluster/src/test/java/org/apache/brooklyn/demo/RebindWebClusterDatabaseExampleAppIntegrationTest.java b/examples/simple-web-cluster/src/test/java/org/apache/brooklyn/demo/RebindWebClusterDatabaseExampleAppIntegrationTest.java
index c302141..fabb071 100644
--- a/examples/simple-web-cluster/src/test/java/org/apache/brooklyn/demo/RebindWebClusterDatabaseExampleAppIntegrationTest.java
+++ b/examples/simple-web-cluster/src/test/java/org/apache/brooklyn/demo/RebindWebClusterDatabaseExampleAppIntegrationTest.java
@@ -56,9 +56,7 @@ import org.apache.brooklyn.entity.core.Entities;
 import org.apache.brooklyn.entity.core.StartableApplication;
 import org.apache.brooklyn.entity.database.mysql.MySqlNode;
 import org.apache.brooklyn.entity.group.DynamicCluster;
-
-import brooklyn.entity.java.JavaEntityMethods;
-
+import org.apache.brooklyn.entity.java.JavaEntityMethods;
 import org.apache.brooklyn.policy.autoscaling.AutoScalerPolicy;
 import org.apache.brooklyn.policy.enricher.HttpLatencyDetector;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/main/java/brooklyn/entity/basic/AbstractSoftwareProcessDriver.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/basic/AbstractSoftwareProcessDriver.java b/software/base/src/main/java/brooklyn/entity/basic/AbstractSoftwareProcessDriver.java
deleted file mode 100644
index 0b145a4..0000000
--- a/software/base/src/main/java/brooklyn/entity/basic/AbstractSoftwareProcessDriver.java
+++ /dev/null
@@ -1,516 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.entity.basic;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import static org.apache.brooklyn.util.JavaGroovyEquivalents.elvis;
-
-import java.io.File;
-import java.io.InputStream;
-import java.io.Reader;
-import java.io.StringReader;
-import java.util.Map;
-
-import org.apache.brooklyn.api.internal.EntityLocal;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
-import org.apache.brooklyn.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.entity.lifecycle.ServiceStateLogic;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.ResourceUtils;
-import org.apache.brooklyn.util.core.task.DynamicTasks;
-import org.apache.brooklyn.util.core.task.Tasks;
-import org.apache.brooklyn.util.core.text.TemplateProcessor;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.stream.ReaderInputStream;
-import org.apache.brooklyn.util.text.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Optional;
-import com.google.common.collect.ImmutableMap;
-
-/**
- * An abstract implementation of the {@link SoftwareProcessDriver}.
- */
-public abstract class AbstractSoftwareProcessDriver implements SoftwareProcessDriver {
-
-    private static final Logger log = LoggerFactory.getLogger(AbstractSoftwareProcessDriver.class);
-
-    protected final EntityLocal entity;
-    protected final ResourceUtils resource;
-    protected final Location location;
-
-    public AbstractSoftwareProcessDriver(EntityLocal entity, Location location) {
-        this.entity = checkNotNull(entity, "entity");
-        this.location = checkNotNull(location, "location");
-        this.resource = ResourceUtils.create(entity);
-    }
-
-    /*
-     * (non-Javadoc)
-     * @see brooklyn.entity.basic.SoftwareProcessDriver#rebind()
-     */
-    @Override
-    public void rebind() {
-        // no-op
-    }
-
-    /**
-     * Start the entity.
-     * <p>
-     * This installs, configures and launches the application process. However,
-     * users can also call the {@link #install()}, {@link #customize()} and
-     * {@link #launch()} steps independently. The {@link #postLaunch()} will
-     * be called after the {@link #launch()} metheod is executed, but the
-     * process may not be completely initialised at this stage, so care is
-     * required when implementing these stages.
-     * <p>
-     * The {@link BrooklynConfigKeys#ENTITY_RUNNING} key can be set on the location
-     * or the entity to skip the startup process if the entity is already running,
-     * according to the {@link #isRunning()} method. To force the startup to be
-     * skipped, {@link BrooklynConfigKeys#SKIP_ENTITY_START} can be set on the entity.
-     * The {@link BrooklynConfigKeys#SKIP_ENTITY_INSTALLATION} key can also be used to
-     * skip the {@link #setup()}, {@link #copyInstallResources()} and
-     * {@link #install()} methods if set on the entity or location. 
-     *
-     * @see #stop()
-     */
-    @Override
-    public void start() {
-        boolean skipStart = false;
-        Optional<Boolean> locationRunning = Optional.fromNullable(getLocation().getConfig(BrooklynConfigKeys.SKIP_ENTITY_START_IF_RUNNING));
-        Optional<Boolean> entityRunning = Optional.fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_START_IF_RUNNING));
-        Optional<Boolean> entityStarted = Optional.fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_START));
-        if (locationRunning.or(entityRunning).or(false)) {
-            skipStart = isRunning();
-        } else {
-            skipStart = entityStarted.or(false);
-        }
-        if (!skipStart) {
-            DynamicTasks.queue("copy-pre-install-resources", new Runnable() { public void run() {
-                waitForConfigKey(BrooklynConfigKeys.PRE_INSTALL_RESOURCES_LATCH);
-                copyPreInstallResources();
-            }});
-
-            DynamicTasks.queue("pre-install", new Runnable() { public void run() {
-                preInstall();
-            }});
-
-            if (Strings.isNonBlank(entity.getConfig(BrooklynConfigKeys.PRE_INSTALL_COMMAND))) {
-                DynamicTasks.queue("pre-install-command", new Runnable() { public void run() {
-                    runPreInstallCommand(entity.getConfig(BrooklynConfigKeys.PRE_INSTALL_COMMAND));
-                }});
-            };
-
-            Optional<Boolean> locationInstalled = Optional.fromNullable(getLocation().getConfig(BrooklynConfigKeys.SKIP_ENTITY_INSTALLATION));
-            Optional<Boolean> entityInstalled = Optional.fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_INSTALLATION));
-            boolean skipInstall = locationInstalled.or(entityInstalled).or(false);
-            if (!skipInstall) {
-                DynamicTasks.queue("setup", new Runnable() { public void run() {
-                    waitForConfigKey(BrooklynConfigKeys.SETUP_LATCH);
-                    setup();
-                }});
-
-                DynamicTasks.queue("copy-install-resources", new Runnable() { public void run() {
-                    waitForConfigKey(BrooklynConfigKeys.INSTALL_RESOURCES_LATCH);
-                    copyInstallResources();
-                }});
-
-                DynamicTasks.queue("install", new Runnable() { public void run() {
-                    waitForConfigKey(BrooklynConfigKeys.INSTALL_LATCH);
-                    install();
-                }});
-            }
-
-            if (Strings.isNonBlank(entity.getConfig(BrooklynConfigKeys.POST_INSTALL_COMMAND))) {
-                DynamicTasks.queue("post-install-command", new Runnable() { public void run() {
-                    runPostInstallCommand(entity.getConfig(BrooklynConfigKeys.POST_INSTALL_COMMAND));
-                }});
-            }
-
-            DynamicTasks.queue("customize", new Runnable() { public void run() {
-                waitForConfigKey(BrooklynConfigKeys.CUSTOMIZE_LATCH);
-                customize();
-            }});
-
-            DynamicTasks.queue("copy-runtime-resources", new Runnable() { public void run() {
-                waitForConfigKey(BrooklynConfigKeys.RUNTIME_RESOURCES_LATCH);
-                copyRuntimeResources();
-            }});
-
-            if (Strings.isNonBlank(entity.getConfig(BrooklynConfigKeys.PRE_LAUNCH_COMMAND))) {
-                DynamicTasks.queue("pre-launch-command", new Runnable() { public void run() {
-                    runPreLaunchCommand(entity.getConfig(BrooklynConfigKeys.PRE_LAUNCH_COMMAND));
-                }});
-            };
-
-            DynamicTasks.queue("launch", new Runnable() { public void run() {
-                waitForConfigKey(BrooklynConfigKeys.LAUNCH_LATCH);
-                launch();
-            }});
-
-            if (Strings.isNonBlank(entity.getConfig(BrooklynConfigKeys.POST_LAUNCH_COMMAND))) {
-                DynamicTasks.queue("post-launch-command", new Runnable() { public void run() {
-                    runPostLaunchCommand(entity.getConfig(BrooklynConfigKeys.POST_LAUNCH_COMMAND));
-                }});
-            };
-        }
-
-        DynamicTasks.queue("post-launch", new Runnable() { public void run() {
-            postLaunch();
-        }});
-    }
-
-    @Override
-    public abstract void stop();
-
-    /**
-     * Implement this method in child classes to add some pre-install behavior
-     */
-    public void preInstall() {}
-
-    public abstract void runPreInstallCommand(String command);
-    public abstract void setup();
-    public abstract void install();
-    public abstract void runPostInstallCommand(String command);
-    public abstract void customize();
-    public abstract void runPreLaunchCommand(String command);
-    public abstract void launch();
-    public abstract void runPostLaunchCommand(String command);
-
-    @Override
-    public void kill() {
-        stop();
-    }
-
-    /**
-     * Implement this method in child classes to add some post-launch behavior
-     */
-    public void postLaunch() {}
-
-    @Override
-    public void restart() {
-        DynamicTasks.queue("stop (best effort)", new Runnable() {
-            public void run() {
-                DynamicTasks.markInessential();
-                boolean previouslyRunning = isRunning();
-                try {
-                    ServiceStateLogic.setExpectedState(getEntity(), Lifecycle.STOPPING);
-                    stop();
-                } catch (Exception e) {
-                    // queue a failed task so that there is visual indication that this task had a failure,
-                    // without interrupting the parent
-                    if (previouslyRunning) {
-                        log.warn(getEntity() + " restart: stop failed, when was previously running (ignoring)", e);
-                        DynamicTasks.queue(Tasks.fail("Primary job failure (when previously running)", e));
-                    } else {
-                        log.debug(getEntity() + " restart: stop failed (but was not previously running, so not a surprise)", e);
-                        DynamicTasks.queue(Tasks.fail("Primary job failure (when not previously running)", e));
-                    }
-                    // the above queued tasks will cause this task to be indicated as failed, with an indication of severity
-                }
-            }
-        });
-
-        if (doFullStartOnRestart()) {
-            DynamicTasks.waitForLast();
-            ServiceStateLogic.setExpectedState(getEntity(), Lifecycle.STARTING);
-            start();
-        } else {
-            DynamicTasks.queue("launch", new Runnable() { public void run() {
-                ServiceStateLogic.setExpectedState(getEntity(), Lifecycle.STARTING);
-                launch();
-            }});
-            DynamicTasks.queue("post-launch", new Runnable() { public void run() {
-                postLaunch();
-            }});
-        }
-    }
-
-    @Beta
-    /** ideally restart() would take options, e.g. whether to do full start, skip installs, etc;
-     * however in the absence here is a toggle - not sure how well it works;
-     * default is false which is similar to previous behaviour (with some seemingly-obvious tidies),
-     * meaning install and configure will NOT be done on restart. */
-    protected boolean doFullStartOnRestart() {
-        return false;
-    }
-
-    @Override
-    public EntityLocal getEntity() { return entity; }
-
-    @Override
-    public Location getLocation() { return location; }
-
-    public InputStream getResource(String url) {
-        return resource.getResourceFromUrl(url);
-    }
-
-    /**
-     * Files and templates to be copied to the server <em>before</em> pre-install. This allows the {@link #preInstall()}
-     * process to have access to all required resources.
-     * <p>
-     * Will be prefixed with the entity's {@link #getInstallDir() install directory} if relative.
-     *
-     * @see SoftwareProcess#PRE_INSTALL_FILES
-     * @see SoftwareProcess#PRE_INSTALL_TEMPLATES
-     * @see #copyRuntimeResources()
-     */
-    public void copyPreInstallResources() {
-        copyResources(entity.getConfig(SoftwareProcess.PRE_INSTALL_FILES), entity.getConfig(SoftwareProcess.PRE_INSTALL_TEMPLATES));
-    }
-
-    /**
-     * Files and templates to be copied to the server <em>before</em> installation. This allows the {@link #install()}
-     * process to have access to all required resources.
-     * <p>
-     * Will be prefixed with the entity's {@link #getInstallDir() install directory} if relative.
-     *
-     * @see SoftwareProcess#INSTALL_FILES
-     * @see SoftwareProcess#INSTALL_TEMPLATES
-     * @see #copyRuntimeResources()
-     */
-    public void copyInstallResources() {
-        copyResources(entity.getConfig(SoftwareProcess.INSTALL_FILES), entity.getConfig(SoftwareProcess.INSTALL_TEMPLATES));
-    }
-
-    private void copyResources(Map<String, String> files, Map<String, String> templates) {
-        // Ensure environment variables are not looked up here, otherwise sub-classes might
-        // lookup port numbers and fail with ugly error if port is not set; better to wait
-        // until in Entity's code (e.g. customize) where such checks are done explicitly.
-
-        boolean hasAnythingToCopy = ((files != null && files.size() > 0) || (templates != null && templates.size() > 0));
-        if (hasAnythingToCopy) {
-            createDirectory(getInstallDir(), "create install directory");
-    
-            // TODO see comment in copyResource, that should be queued as a task like the above
-            // (better reporting in activities console)
-    
-            if (files != null && files.size() > 0) {
-                for (String source : files.keySet()) {
-                    String target = files.get(source);
-                    String destination = Os.isAbsolutish(target) ? target : Os.mergePathsUnix(getInstallDir(), target);
-                    copyResource(source, destination, true);
-                }
-            }
-    
-            if (templates != null && templates.size() > 0) {
-                for (String source : templates.keySet()) {
-                    String target = templates.get(source);
-                    String destination = Os.isAbsolutish(target) ? target : Os.mergePathsUnix(getInstallDir(), target);
-                    copyTemplate(source, destination, true, MutableMap.<String, Object>of());
-                }
-            }
-        }
-    }
-
-    protected abstract void createDirectory(String directoryName, String summaryForLogging);
-
-    /**
-     * Files and templates to be copied to the server <em>after</em> customisation. This allows overwriting of
-     * existing files such as entity configuration which may be copied from the installation directory
-     * during the {@link #customize()} process.
-     * <p>
-     * Will be prefixed with the entity's {@link #getRunDir() run directory} if relative.
-     *
-     * @see SoftwareProcess#RUNTIME_FILES
-     * @see SoftwareProcess#RUNTIME_TEMPLATES
-     * @see #copyInstallResources()
-     */
-    public void copyRuntimeResources() {
-        try {
-            createDirectory(getRunDir(), "create run directory");
-
-            Map<String, String> runtimeFiles = entity.getConfig(SoftwareProcess.RUNTIME_FILES);
-            if (runtimeFiles != null && runtimeFiles.size() > 0) {
-                for (String source : runtimeFiles.keySet()) {
-                    String target = runtimeFiles.get(source);
-                    String destination = Os.isAbsolutish(target) ? target : Os.mergePathsUnix(getRunDir(), target);
-                    copyResource(source, destination, true);
-                }
-            }
-
-            Map<String, String> runtimeTemplates = entity.getConfig(SoftwareProcess.RUNTIME_TEMPLATES);
-            if (runtimeTemplates != null && runtimeTemplates.size() > 0) {
-                for (String source : runtimeTemplates.keySet()) {
-                    String target = runtimeTemplates.get(source);
-                    String destination = Os.isAbsolutish(target) ? target : Os.mergePathsUnix(getRunDir(), target);
-                    copyTemplate(source, destination, true, MutableMap.<String, Object>of());
-                }
-            }
-        } catch (Exception e) {
-            log.warn("Error copying runtime resources", e);
-            throw Exceptions.propagate(e);
-        }
-    }
-
-    /**
-     * @param template File to template and copy.
-     * @param target Destination on server.
-     * @return The exit code the SSH command run.
-     */
-    public int copyTemplate(File template, String target) {
-        return copyTemplate(template.toURI().toASCIIString(), target);
-    }
-
-    /**
-     * @param template URI of file to template and copy, e.g. file://.., http://.., classpath://..
-     * @param target Destination on server.
-     * @return The exit code of the SSH command run.
-     */
-    public int copyTemplate(String template, String target) {
-        return copyTemplate(template, target, false, ImmutableMap.<String, String>of());
-    }
-
-    /**
-     * @param template URI of file to template and copy, e.g. file://.., http://.., classpath://..
-     * @param target Destination on server.
-     * @param extraSubstitutions Extra substitutions for the templater to use, for example
-     *               "foo" -> "bar", and in a template ${foo}.
-     * @return The exit code of the SSH command run.
-     */
-    public int copyTemplate(String template, String target, boolean createParent, Map<String, ?> extraSubstitutions) {
-        String data = processTemplate(template, extraSubstitutions);
-        return copyResource(MutableMap.<Object,Object>of(), new StringReader(data), target, createParent);
-    }
-
-    public abstract int copyResource(Map<Object,Object> sshFlags, String source, String target, boolean createParentDir);
-
-    public abstract int copyResource(Map<Object,Object> sshFlags, InputStream source, String target, boolean createParentDir);
-
-    /**
-     * @param file File to copy.
-     * @param target Destination on server.
-     * @return The exit code the SSH command run.
-     */
-    public int copyResource(File file, String target) {
-        return copyResource(file.toURI().toASCIIString(), target);
-    }
-
-    /**
-     * @param resource URI of file to copy, e.g. file://.., http://.., classpath://..
-     * @param target Destination on server.
-     * @return The exit code of the SSH command run
-     */
-    public int copyResource(String resource, String target) {
-        return copyResource(MutableMap.of(), resource, target);
-    }
-
-    public int copyResource(String resource, String target, boolean createParentDir) {
-        return copyResource(MutableMap.of(), resource, target, createParentDir);
-    }
-
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    public int copyResource(Map sshFlags, String source, String target) {
-        return copyResource(sshFlags, source, target, false);
-    }
-
-    /**
-     * @see #copyResource(Map, InputStream, String, boolean)
-     */
-    public int copyResource(Reader source, String target) {
-        return copyResource(MutableMap.of(), source, target, false);
-    }
-
-    /**
-     * @see #copyResource(Map, InputStream, String, boolean)
-     */
-    public int copyResource(Map<Object,Object> sshFlags, Reader source, String target, boolean createParent) {
-        return copyResource(sshFlags, new ReaderInputStream(source), target, createParent);
-    }
-
-    /**
-     * @see #copyResource(Map, InputStream, String, boolean)
-     */
-    public int copyResource(InputStream source, String target) {
-        return copyResource(MutableMap.of(), source, target, false);
-    }
-
-    public String getResourceAsString(String url) {
-        return resource.getResourceAsString(url);
-    }
-
-    public String processTemplate(File templateConfigFile, Map<String,Object> extraSubstitutions) {
-        return processTemplate(templateConfigFile.toURI().toASCIIString(), extraSubstitutions);
-    }
-
-    public String processTemplate(File templateConfigFile) {
-        return processTemplate(templateConfigFile.toURI().toASCIIString());
-    }
-
-    /** Takes the contents of a template file from the given URL (often a classpath://com/myco/myprod/myfile.conf or .sh)
-     * and replaces "${entity.xxx}" with the result of entity.getXxx() and similar for other driver, location;
-     * as well as replacing config keys on the management context
-     * <p>
-     * uses Freemarker templates under the covers
-     **/
-    public String processTemplate(String templateConfigUrl) {
-        return processTemplate(templateConfigUrl, ImmutableMap.<String,String>of());
-    }
-
-    public String processTemplate(String templateConfigUrl, Map<String,? extends Object> extraSubstitutions) {
-        return processTemplateContents(getResourceAsString(templateConfigUrl), extraSubstitutions);
-    }
-
-    public String processTemplateContents(String templateContents) {
-        return processTemplateContents(templateContents, ImmutableMap.<String,String>of());
-    }
-
-    public String processTemplateContents(String templateContents, Map<String,? extends Object> extraSubstitutions) {
-        return TemplateProcessor.processTemplateContents(templateContents, this, extraSubstitutions);
-    }
-
-    protected void waitForConfigKey(ConfigKey<?> configKey) {
-        Object val = entity.getConfig(configKey);
-        if (val != null) log.debug("{} finished waiting for {} (value {}); continuing...", new Object[] {this, configKey, val});
-    }
-
-    /**
-     * @deprecated since 0.5.0; instead rely on {@link org.apache.brooklyn.api.entity.drivers.downloads.DownloadResolverManager} to include local-repo, such as:
-     *
-     * <pre>
-     * {@code
-     * DownloadResolver resolver = Entities.newDownloader(this);
-     * List<String> urls = resolver.getTargets();
-     * }
-     * </pre>
-     */
-    protected String getEntityVersionLabel() {
-        return getEntityVersionLabel("_");
-    }
-
-    /**
-     * @deprecated since 0.5.0; instead rely on {@link org.apache.brooklyn.api.entity.drivers.downloads.DownloadResolverManager} to include local-repo
-     */
-    protected String getEntityVersionLabel(String separator) {
-        return elvis(entity.getEntityType().getSimpleName(),
-                entity.getClass().getName())+(getVersion() != null ? separator+getVersion() : "");
-    }
-
-    public String getVersion() {
-        return getEntity().getConfig(SoftwareProcess.SUGGESTED_VERSION);
-    }
-
-    public abstract String getRunDir();
-    public abstract String getInstallDir();
-}


[71/72] [abbrv] incubator-brooklyn git commit: This closes #844

Posted by he...@apache.org.
This closes #844


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

Branch: refs/heads/master
Commit: 4b08f9022b6b8094eb114f532f88c45d7ce05aad
Parents: ce5ddaf 95277b3
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Wed Aug 19 12:07:15 2015 +0100
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Wed Aug 19 12:07:15 2015 +0100

----------------------------------------------------------------------
 .../api/basic/AbstractBrooklynObjectSpec.java   |  141 --
 .../brooklyn/api/basic/BrooklynObject.java      |   76 -
 .../apache/brooklyn/api/basic/BrooklynType.java |   54 -
 .../api/basic/internal/ApiObjectsFactory.java   |   61 -
 .../internal/ApiObjectsFactoryInterface.java    |   29 -
 .../brooklyn/api/catalog/CatalogItem.java       |    8 +-
 .../apache/brooklyn/api/effector/Effector.java  |   56 +
 .../brooklyn/api/effector/ParameterType.java    |   48 +
 .../apache/brooklyn/api/entity/Application.java |    2 +-
 .../apache/brooklyn/api/entity/Effector.java    |   54 -
 .../org/apache/brooklyn/api/entity/Entity.java  |   15 +-
 .../brooklyn/api/entity/EntityInitializer.java  |   43 +
 .../apache/brooklyn/api/entity/EntitySpec.java  |  470 +++++
 .../apache/brooklyn/api/entity/EntityType.java  |    5 +-
 .../brooklyn/api/entity/EntityTypeRegistry.java |   63 +
 .../org/apache/brooklyn/api/entity/Feed.java    |   70 -
 .../org/apache/brooklyn/api/entity/Group.java   |    2 -
 .../brooklyn/api/entity/ImplementedBy.java      |   46 +
 .../brooklyn/api/entity/ParameterType.java      |   48 -
 .../brooklyn/api/entity/basic/EntityLocal.java  |  179 --
 .../api/entity/drivers/EntityDriver.java        |    2 +-
 .../api/entity/proxying/EntityInitializer.java  |   43 -
 .../api/entity/proxying/EntitySpec.java         |  472 -----
 .../api/entity/proxying/EntityTypeRegistry.java |   64 -
 .../api/entity/proxying/ImplementedBy.java      |   48 -
 .../api/entity/rebind/BrooklynObjectType.java   |   68 -
 .../api/entity/rebind/ChangeListener.java       |   44 -
 .../rebind/PersistenceExceptionHandler.java     |   43 -
 .../api/entity/rebind/RebindContext.java        |   52 -
 .../entity/rebind/RebindExceptionHandler.java   |  109 --
 .../api/entity/rebind/RebindManager.java        |  132 --
 .../api/entity/rebind/RebindSupport.java        |   57 -
 .../brooklyn/api/entity/rebind/Rebindable.java  |   40 -
 .../brooklyn/api/entity/trait/Configurable.java |   93 -
 .../brooklyn/api/entity/trait/HasShortName.java |   26 -
 .../brooklyn/api/entity/trait/Identifiable.java |   24 -
 .../brooklyn/api/event/AttributeSensor.java     |   52 -
 .../org/apache/brooklyn/api/event/Sensor.java   |   77 -
 .../apache/brooklyn/api/event/SensorEvent.java  |   47 -
 .../brooklyn/api/event/SensorEventListener.java |   37 -
 .../internal/AbstractBrooklynObjectSpec.java    |  140 ++
 .../api/internal/ApiObjectsFactory.java         |   61 +
 .../internal/ApiObjectsFactoryInterface.java    |   29 +
 .../brooklyn/api/internal/EntityLocal.java      |  178 ++
 .../apache/brooklyn/api/location/Location.java  |    2 +-
 .../api/location/LocationDefinition.java        |    2 +-
 .../brooklyn/api/location/LocationResolver.java |    2 +-
 .../brooklyn/api/location/LocationSpec.java     |    4 +-
 .../brooklyn/api/location/LocationType.java     |    2 +-
 .../api/management/AccessController.java        |   65 -
 .../brooklyn/api/management/EntityManager.java  |  126 --
 .../api/management/ExecutionContext.java        |   67 -
 .../api/management/ExecutionManager.java        |  117 --
 .../api/management/HasTaskChildren.java         |   39 -
 .../api/management/LocationManager.java         |   87 -
 .../api/management/ManagementContext.java       |  254 ---
 .../api/management/SubscriptionContext.java     |   66 -
 .../api/management/SubscriptionHandle.java      |   27 -
 .../api/management/SubscriptionManager.java     |  112 --
 .../apache/brooklyn/api/management/Task.java    |  128 --
 .../brooklyn/api/management/TaskAdaptable.java  |   24 -
 .../brooklyn/api/management/TaskFactory.java    |   25 -
 .../api/management/TaskQueueingContext.java     |   62 -
 .../brooklyn/api/management/TaskWrapper.java    |   28 -
 .../BrooklynClassLoadingContext.java            |   50 -
 .../entitlement/EntitlementClass.java           |   27 -
 .../entitlement/EntitlementContext.java         |   24 -
 .../entitlement/EntitlementManager.java         |   45 -
 .../management/ha/HighAvailabilityManager.java  |  129 --
 .../api/management/ha/HighAvailabilityMode.java |   67 -
 .../api/management/ha/ManagementNodeState.java  |   72 -
 .../management/ha/ManagementNodeSyncRecord.java |   62 -
 .../ha/ManagementPlaneSyncRecord.java           |   51 -
 .../ha/ManagementPlaneSyncRecordPersister.java  |   68 -
 .../api/management/ha/MementoCopyMode.java      |   29 -
 .../brooklyn/api/mementos/BrooklynMemento.java  |   64 -
 .../api/mementos/BrooklynMementoManifest.java   |   58 -
 .../api/mementos/BrooklynMementoPersister.java  |  137 --
 .../api/mementos/BrooklynMementoRawData.java    |  185 --
 .../api/mementos/CatalogItemMemento.java        |   49 -
 .../brooklyn/api/mementos/EnricherMemento.java  |   33 -
 .../brooklyn/api/mementos/EntityMemento.java    |   80 -
 .../brooklyn/api/mementos/FeedMemento.java      |   33 -
 .../brooklyn/api/mementos/LocationMemento.java  |   38 -
 .../apache/brooklyn/api/mementos/Memento.java   |   83 -
 .../brooklyn/api/mementos/PolicyMemento.java    |   35 -
 .../apache/brooklyn/api/mementos/TreeNode.java  |   48 -
 .../brooklyn/api/mgmt/AccessController.java     |   65 +
 .../apache/brooklyn/api/mgmt/EntityManager.java |  126 ++
 .../brooklyn/api/mgmt/ExecutionContext.java     |   67 +
 .../brooklyn/api/mgmt/ExecutionManager.java     |  117 ++
 .../brooklyn/api/mgmt/HasTaskChildren.java      |   39 +
 .../brooklyn/api/mgmt/LocationManager.java      |   87 +
 .../brooklyn/api/mgmt/ManagementContext.java    |  254 +++
 .../brooklyn/api/mgmt/SubscriptionContext.java  |   66 +
 .../brooklyn/api/mgmt/SubscriptionHandle.java   |   27 +
 .../brooklyn/api/mgmt/SubscriptionManager.java  |  112 ++
 .../java/org/apache/brooklyn/api/mgmt/Task.java |  128 ++
 .../apache/brooklyn/api/mgmt/TaskAdaptable.java |   24 +
 .../apache/brooklyn/api/mgmt/TaskFactory.java   |   25 +
 .../brooklyn/api/mgmt/TaskQueueingContext.java  |   62 +
 .../apache/brooklyn/api/mgmt/TaskWrapper.java   |   28 +
 .../BrooklynClassLoadingContext.java            |   50 +
 .../api/mgmt/entitlement/EntitlementClass.java  |   27 +
 .../mgmt/entitlement/EntitlementContext.java    |   24 +
 .../mgmt/entitlement/EntitlementManager.java    |   45 +
 .../api/mgmt/ha/HighAvailabilityManager.java    |  129 ++
 .../api/mgmt/ha/HighAvailabilityMode.java       |   67 +
 .../api/mgmt/ha/ManagementNodeState.java        |   72 +
 .../api/mgmt/ha/ManagementNodeSyncRecord.java   |   62 +
 .../api/mgmt/ha/ManagementPlaneSyncRecord.java  |   51 +
 .../ha/ManagementPlaneSyncRecordPersister.java  |   68 +
 .../brooklyn/api/mgmt/ha/MementoCopyMode.java   |   29 +
 .../api/mgmt/rebind/ChangeListener.java         |   44 +
 .../rebind/PersistenceExceptionHandler.java     |   44 +
 .../brooklyn/api/mgmt/rebind/RebindContext.java |   52 +
 .../api/mgmt/rebind/RebindExceptionHandler.java |  110 ++
 .../brooklyn/api/mgmt/rebind/RebindManager.java |  132 ++
 .../brooklyn/api/mgmt/rebind/RebindSupport.java |   57 +
 .../brooklyn/api/mgmt/rebind/Rebindable.java    |   40 +
 .../mgmt/rebind/mementos/BrooklynMemento.java   |   64 +
 .../mementos/BrooklynMementoManifest.java       |   58 +
 .../mementos/BrooklynMementoPersister.java      |  137 ++
 .../rebind/mementos/BrooklynMementoRawData.java |  185 ++
 .../rebind/mementos/CatalogItemMemento.java     |   49 +
 .../mgmt/rebind/mementos/EnricherMemento.java   |   33 +
 .../api/mgmt/rebind/mementos/EntityMemento.java |   80 +
 .../api/mgmt/rebind/mementos/FeedMemento.java   |   33 +
 .../mgmt/rebind/mementos/LocationMemento.java   |   38 +
 .../api/mgmt/rebind/mementos/Memento.java       |   83 +
 .../api/mgmt/rebind/mementos/PolicyMemento.java |   35 +
 .../api/mgmt/rebind/mementos/TreeNode.java      |   48 +
 .../brooklyn/api/objs/BrooklynObject.java       |   73 +
 .../brooklyn/api/objs/BrooklynObjectType.java   |   67 +
 .../apache/brooklyn/api/objs/BrooklynType.java  |   54 +
 .../apache/brooklyn/api/objs/Configurable.java  |   93 +
 .../apache/brooklyn/api/objs/EntityAdjunct.java |   53 +
 .../apache/brooklyn/api/objs/HasShortName.java  |   26 +
 .../apache/brooklyn/api/objs/Identifiable.java  |   24 +
 .../apache/brooklyn/api/policy/Enricher.java    |   70 -
 .../brooklyn/api/policy/EnricherSpec.java       |  213 ---
 .../brooklyn/api/policy/EnricherType.java       |   36 -
 .../brooklyn/api/policy/EntityAdjunct.java      |   55 -
 .../org/apache/brooklyn/api/policy/Policy.java  |   11 +-
 .../apache/brooklyn/api/policy/PolicySpec.java  |    4 +-
 .../apache/brooklyn/api/policy/PolicyType.java  |    2 +-
 .../brooklyn/api/sensor/AttributeSensor.java    |   52 +
 .../apache/brooklyn/api/sensor/Enricher.java    |   72 +
 .../brooklyn/api/sensor/EnricherSpec.java       |  213 +++
 .../brooklyn/api/sensor/EnricherType.java       |   36 +
 .../org/apache/brooklyn/api/sensor/Feed.java    |   70 +
 .../org/apache/brooklyn/api/sensor/Sensor.java  |   77 +
 .../apache/brooklyn/api/sensor/SensorEvent.java |   47 +
 .../api/sensor/SensorEventListener.java         |   37 +
 .../src/main/java/brooklyn/BrooklynVersion.java |  391 ----
 .../enricher/CustomAggregatingEnricher.java     |  322 ----
 .../main/java/brooklyn/enricher/Enrichers.java  |  831 ---------
 .../basic/AbstractAggregatingEnricher.java      |  174 --
 .../enricher/basic/AbstractAggregator.java      |  238 ---
 .../enricher/basic/AbstractEnricher.java        |  116 --
 .../basic/AbstractMultipleSensorAggregator.java |  169 --
 .../enricher/basic/AbstractTransformer.java     |  101 -
 .../basic/AbstractTransformingEnricher.java     |   38 -
 .../basic/AbstractTypeTransformingEnricher.java |   68 -
 .../brooklyn/enricher/basic/AddingEnricher.java |  107 --
 .../brooklyn/enricher/basic/Aggregator.java     |  223 ---
 .../java/brooklyn/enricher/basic/Combiner.java  |  138 --
 .../enricher/basic/EnricherDynamicType.java     |   44 -
 .../enricher/basic/EnricherTypeSnapshot.java    |   39 -
 .../java/brooklyn/enricher/basic/Joiner.java    |  127 --
 .../brooklyn/enricher/basic/Propagator.java     |  201 --
 .../basic/SensorPropagatingEnricher.java        |  182 --
 .../basic/SensorTransformingEnricher.java       |  106 --
 .../brooklyn/enricher/basic/Transformer.java    |  104 --
 .../brooklyn/enricher/basic/UpdatingMap.java    |  159 --
 .../YamlRollingTimeWindowMeanEnricher.java      |  179 --
 .../basic/YamlTimeWeightedDeltaEnricher.java    |   84 -
 .../brooklyn/entity/annotation/Effector.java    |   33 -
 .../entity/annotation/EffectorParam.java        |   42 -
 .../entity/basic/AbstractApplication.java       |  262 ---
 .../AbstractConfigurableEntityFactory.java      |   83 -
 .../brooklyn/entity/basic/AbstractEffector.java |   93 -
 .../brooklyn/entity/basic/AbstractEntity.java   | 1738 -----------------
 .../brooklyn/entity/basic/AbstractGroup.java    |   86 -
 .../entity/basic/AbstractGroupImpl.java         |  272 ---
 .../entity/basic/ApplicationBuilder.java        |  244 ---
 .../java/brooklyn/entity/basic/Attributes.java  |  169 --
 .../brooklyn/entity/basic/BasicApplication.java |   31 -
 .../entity/basic/BasicApplicationImpl.java      |   29 -
 .../basic/BasicConfigurableEntityFactory.java   |   75 -
 .../java/brooklyn/entity/basic/BasicEntity.java |   33 -
 .../brooklyn/entity/basic/BasicEntityImpl.java  |   26 -
 .../java/brooklyn/entity/basic/BasicGroup.java  |   37 -
 .../brooklyn/entity/basic/BasicGroupImpl.java   |   46 -
 .../entity/basic/BasicParameterType.java        |  116 --
 .../brooklyn/entity/basic/BasicStartable.java   |   57 -
 .../entity/basic/BasicStartableImpl.java        |  101 -
 .../entity/basic/BrooklynConfigKeys.java        |  185 --
 .../entity/basic/BrooklynShutdownHooks.java     |  242 ---
 .../brooklyn/entity/basic/BrooklynTags.java     |   66 -
 .../brooklyn/entity/basic/BrooklynTaskTags.java |  447 -----
 .../brooklyn/entity/basic/BrooklynTasks.java    |   24 -
 .../entity/basic/ClosureEntityFactory.java      |   53 -
 .../java/brooklyn/entity/basic/ConfigKeys.java  |  267 ---
 .../basic/ConfigMapViewWithStringKeys.java      |  131 --
 .../entity/basic/ConfigurableEntityFactory.java |   33 -
 ...figurableEntityFactoryFromEntityFactory.java |   45 -
 .../java/brooklyn/entity/basic/DataEntity.java  |   58 -
 .../brooklyn/entity/basic/DataEntityImpl.java   |   79 -
 .../brooklyn/entity/basic/DelegateEntity.java   |   73 -
 .../entity/basic/DelegateEntityImpl.java        |   49 -
 .../brooklyn/entity/basic/DynamicGroup.java     |   88 -
 .../brooklyn/entity/basic/DynamicGroupImpl.java |  230 ---
 .../entity/basic/EffectorStartableImpl.java     |   79 -
 .../java/brooklyn/entity/basic/Entities.java    | 1107 -----------
 .../brooklyn/entity/basic/EntityAdjuncts.java   |   71 -
 .../entity/basic/EntityAndAttribute.java        |  107 --
 .../brooklyn/entity/basic/EntityConfigMap.java  |  305 ---
 .../entity/basic/EntityDynamicType.java         |  339 ----
 .../brooklyn/entity/basic/EntityFactory.java    |   32 -
 .../entity/basic/EntityFactoryForLocation.java  |   30 -
 .../brooklyn/entity/basic/EntityFunctions.java  |  152 --
 .../entity/basic/EntityInitializers.java        |   49 -
 .../brooklyn/entity/basic/EntityInternal.java   |  200 --
 .../brooklyn/entity/basic/EntityPredicates.java |  451 -----
 .../brooklyn/entity/basic/EntitySuppliers.java  |   48 -
 .../java/brooklyn/entity/basic/EntityTasks.java |   82 -
 .../basic/EntityTransientCopyInternal.java      |  121 --
 .../entity/basic/EntityTypeSnapshot.java        |  126 --
 .../java/brooklyn/entity/basic/EntityTypes.java |   28 -
 .../brooklyn/entity/basic/ExplicitEffector.java |   74 -
 .../java/brooklyn/entity/basic/Lifecycle.java   |  185 --
 .../brooklyn/entity/basic/MethodEffector.java   |  180 --
 .../brooklyn/entity/basic/PolicyDescriptor.java |   66 -
 .../java/brooklyn/entity/basic/QuorumCheck.java |  108 --
 .../java/brooklyn/entity/basic/Sanitizer.java   |  172 --
 .../entity/basic/ServiceStateLogic.java         |  634 -------
 .../entity/basic/StartableApplication.java      |   26 -
 .../drivers/BasicEntityDriverManager.java       |   56 -
 .../drivers/ReflectiveEntityDriverFactory.java  |  277 ---
 .../drivers/RegistryEntityDriverFactory.java    |  127 --
 .../downloads/BasicDownloadRequirement.java     |   85 -
 .../downloads/BasicDownloadResolver.java        |   66 -
 .../drivers/downloads/BasicDownloadTargets.java |  121 --
 .../downloads/BasicDownloadsManager.java        |  161 --
 .../DownloadProducerFromCloudsoftRepo.java      |   84 -
 .../DownloadProducerFromLocalRepo.java          |   85 -
 .../DownloadProducerFromProperties.java         |  345 ----
 .../DownloadProducerFromUrlAttribute.java       |   64 -
 .../drivers/downloads/DownloadSubstituters.java |  173 --
 .../drivers/downloads/FilenameProducers.java    |   64 -
 .../entity/effector/AddChildrenEffector.java    |  118 --
 .../brooklyn/entity/effector/AddEffector.java   |  117 --
 .../brooklyn/entity/effector/AddSensor.java     |  127 --
 .../entity/effector/EffectorAndBody.java        |   61 -
 .../brooklyn/entity/effector/EffectorBase.java  |  107 --
 .../brooklyn/entity/effector/EffectorBody.java  |  101 -
 .../brooklyn/entity/effector/EffectorTasks.java |  231 ---
 .../entity/effector/EffectorWithBody.java       |   33 -
 .../brooklyn/entity/effector/Effectors.java     |  204 --
 .../group/AbstractMembershipTrackingPolicy.java |  248 ---
 .../java/brooklyn/entity/group/Cluster.java     |   36 -
 .../brooklyn/entity/group/DynamicCluster.java   |  204 --
 .../entity/group/DynamicClusterImpl.java        |  888 ---------
 .../brooklyn/entity/group/DynamicFabric.java    |   77 -
 .../entity/group/DynamicFabricImpl.java         |  276 ---
 .../entity/group/DynamicMultiGroup.java         |  106 --
 .../entity/group/DynamicMultiGroupImpl.java     |  206 ---
 .../entity/group/DynamicRegionsFabric.java      |   43 -
 .../entity/group/DynamicRegionsFabricImpl.java  |   78 -
 .../main/java/brooklyn/entity/group/Fabric.java |   26 -
 .../brooklyn/entity/group/QuarantineGroup.java  |   37 -
 .../entity/group/QuarantineGroupImpl.java       |  104 --
 .../group/StopFailedRuntimeException.java       |   40 -
 .../main/java/brooklyn/entity/group/Tier.java   |   28 -
 .../zoneaware/AbstractZoneFailureDetector.java  |  127 --
 .../BalancingNodePlacementStrategy.java         |  132 --
 .../zoneaware/CombiningZoneFailureDetector.java |   82 -
 .../CriticalCauseZoneFailureDetector.java       |   56 -
 .../ProportionalZoneFailureDetector.java        |   59 -
 .../proxying/BasicEntityTypeRegistry.java       |  156 --
 .../brooklyn/entity/proxying/EntityProxy.java   |   27 -
 .../entity/proxying/EntityProxyImpl.java        |  274 ---
 .../entity/proxying/InternalEntityFactory.java  |  403 ----
 .../entity/proxying/InternalFactory.java        |  131 --
 .../proxying/InternalLocationFactory.java       |  151 --
 .../entity/proxying/InternalPolicyFactory.java  |  199 --
 .../AbstractBrooklynObjectRebindSupport.java    |  103 --
 .../rebind/ActivePartialRebindIteration.java    |  165 --
 .../rebind/BasicCatalogItemRebindSupport.java   |   67 -
 .../rebind/BasicEnricherRebindSupport.java      |   51 -
 .../entity/rebind/BasicEntityRebindSupport.java |  237 ---
 .../entity/rebind/BasicFeedRebindSupport.java   |   50 -
 .../rebind/BasicLocationRebindSupport.java      |  139 --
 .../entity/rebind/BasicPolicyRebindSupport.java |   51 -
 .../rebind/ImmediateDeltaChangeListener.java    |  155 --
 .../rebind/InitialFullRebindIteration.java      |  134 --
 .../rebind/PeriodicDeltaChangeListener.java     |  502 -----
 .../rebind/PersistenceExceptionHandlerImpl.java |  108 --
 .../entity/rebind/PersisterDeltaImpl.java       |  174 --
 .../entity/rebind/RebindContextImpl.java        |  190 --
 .../rebind/RebindContextLookupContext.java      |  157 --
 .../rebind/RebindExceptionHandlerImpl.java      |  471 -----
 .../brooklyn/entity/rebind/RebindIteration.java | 1163 ------------
 .../entity/rebind/RebindManagerImpl.java        |  665 -------
 .../java/brooklyn/entity/rebind/TreeUtils.java  |   56 -
 .../entity/rebind/dto/AbstractMemento.java      |  230 ---
 .../rebind/dto/AbstractTreeNodeMemento.java     |  113 --
 .../rebind/dto/BasicCatalogItemMemento.java     |  256 ---
 .../entity/rebind/dto/BasicEnricherMemento.java |   94 -
 .../entity/rebind/dto/BasicEntityMemento.java   |  327 ----
 .../entity/rebind/dto/BasicFeedMemento.java     |   94 -
 .../entity/rebind/dto/BasicLocationMemento.java |  108 --
 .../entity/rebind/dto/BasicPolicyMemento.java   |   94 -
 .../entity/rebind/dto/BrooklynMementoImpl.java  |  257 ---
 .../rebind/dto/BrooklynMementoManifestImpl.java |  172 --
 .../rebind/dto/EntityMementoManifestImpl.java   |   56 -
 .../entity/rebind/dto/MementoValidators.java    |   67 -
 .../entity/rebind/dto/MementosGenerators.java   |  483 -----
 .../rebind/dto/MutableBrooklynMemento.java      |  293 ---
 .../BrooklynMementoPersisterToObjectStore.java  |  698 -------
 .../persister/BrooklynPersistenceUtils.java     |  271 ---
 .../CatalogItemLibrariesConverter.java          |   68 -
 .../rebind/persister/FileBasedObjectStore.java  |  425 -----
 .../persister/FileBasedStoreObjectAccessor.java |  132 --
 .../persister/LocationWithObjectStore.java      |   27 -
 .../rebind/persister/MementoSerializer.java     |   52 -
 .../entity/rebind/persister/PersistMode.java    |   26 -
 .../persister/PersistenceActivityMetrics.java   |   83 -
 .../persister/PersistenceObjectStore.java       |  142 --
 .../persister/RetryingMementoSerializer.java    |   95 -
 .../persister/StoreObjectAccessorLocking.java   |  219 ---
 .../rebind/persister/XmlMementoSerializer.java  |  506 -----
 .../dto/BasicManagementNodeSyncRecord.java      |  195 --
 .../dto/ManagementPlaneSyncRecordImpl.java      |   99 -
 .../transformer/BrooklynMementoTransformer.java |   32 -
 .../rebind/transformer/CompoundTransformer.java |  292 ---
 .../transformer/CompoundTransformerLoader.java  |  109 --
 .../rebind/transformer/RawDataTransformer.java  |   30 -
 .../DeleteOrphanedLocationsTransformer.java     |  126 --
 .../transformer/impl/XsltTransformer.java       |   59 -
 .../java/brooklyn/entity/trait/Changeable.java  |   36 -
 .../entity/trait/MemberReplaceable.java         |   45 -
 .../java/brooklyn/entity/trait/Resizable.java   |   50 -
 .../java/brooklyn/entity/trait/Startable.java   |  124 --
 .../brooklyn/entity/trait/StartableMethods.java |  126 --
 .../basic/AbstractCollectionConfigKey.java      |  119 --
 .../basic/AbstractStructuredConfigKey.java      |  136 --
 .../java/brooklyn/event/basic/AttributeMap.java |  203 --
 .../basic/AttributeSensorAndConfigKey.java      |  147 --
 .../event/basic/BasicAttributeSensor.java       |   62 -
 .../basic/BasicAttributeSensorAndConfigKey.java |  114 --
 .../brooklyn/event/basic/BasicConfigKey.java    |  281 ---
 .../event/basic/BasicNotificationSensor.java    |   36 -
 .../java/brooklyn/event/basic/BasicSensor.java  |  114 --
 .../brooklyn/event/basic/BasicSensorEvent.java  |  112 --
 .../event/basic/DependentConfiguration.java     |  824 ---------
 .../brooklyn/event/basic/ListConfigKey.java     |  127 --
 .../java/brooklyn/event/basic/MapConfigKey.java |  205 ---
 .../basic/PortAttributeSensorAndConfigKey.java  |  143 --
 .../main/java/brooklyn/event/basic/Sensors.java |  164 --
 .../java/brooklyn/event/basic/SetConfigKey.java |  118 --
 .../event/basic/StructuredConfigKey.java        |   60 -
 .../event/basic/SubElementConfigKey.java        |   77 -
 ...platedStringAttributeSensorAndConfigKey.java |   67 -
 .../java/brooklyn/event/feed/AbstractFeed.java  |  241 ---
 .../event/feed/AttributePollHandler.java        |  249 ---
 .../brooklyn/event/feed/ConfigToAttributes.java |   60 -
 .../event/feed/DelegatingPollHandler.java       |   96 -
 .../java/brooklyn/event/feed/FeedConfig.java    |  298 ---
 .../java/brooklyn/event/feed/PollConfig.java    |   85 -
 .../java/brooklyn/event/feed/PollHandler.java   |   38 -
 .../main/java/brooklyn/event/feed/Poller.java   |  206 ---
 .../event/feed/function/FunctionFeed.java       |  209 ---
 .../event/feed/function/FunctionPollConfig.java |  112 --
 .../java/brooklyn/event/feed/http/HttpFeed.java |  383 ----
 .../event/feed/http/HttpPollConfig.java         |  161 --
 .../brooklyn/event/feed/http/HttpPollValue.java |   40 -
 .../brooklyn/event/feed/http/HttpPolls.java     |   39 -
 .../event/feed/http/HttpValueFunctions.java     |  154 --
 .../brooklyn/event/feed/http/JsonFunctions.java |  235 ---
 .../brooklyn/event/feed/shell/ShellFeed.java    |  274 ---
 .../event/feed/shell/ShellPollConfig.java       |  126 --
 .../java/brooklyn/event/feed/ssh/SshFeed.java   |  292 ---
 .../brooklyn/event/feed/ssh/SshPollConfig.java  |  143 --
 .../brooklyn/event/feed/ssh/SshPollValue.java   |   60 -
 .../event/feed/ssh/SshValueFunctions.java       |   73 -
 .../windows/WindowsPerformanceCounterFeed.java  |  414 -----
 .../WindowsPerformanceCounterPollConfig.java    |   54 -
 .../brooklyn/basic/AbstractBrooklynObject.java  |  249 ---
 .../brooklyn/basic/BasicConfigurableObject.java |  119 --
 .../brooklyn/basic/BrooklynDynamicType.java     |  284 ---
 .../brooklyn/basic/BrooklynObjectInternal.java  |  103 --
 .../brooklyn/basic/BrooklynTypeSnapshot.java    |  101 -
 .../apache/brooklyn/basic/BrooklynTypes.java    |  132 --
 .../basic/internal/ApiObjectsFactoryImpl.java   |   42 -
 .../api/AssemblyTemplateSpecInstantiator.java   |    4 +-
 .../api/HasBrooklynManagementContext.java       |    2 +-
 .../apache/brooklyn/core/BrooklynLogging.java   |   73 +
 .../apache/brooklyn/core/BrooklynVersion.java   |  392 ++++
 .../brooklyn/core/catalog/CatalogLoadMode.java  |    3 +-
 .../core/catalog/CatalogPredicates.java         |    6 +-
 .../catalog/internal/BasicBrooklynCatalog.java  |   16 +-
 .../catalog/internal/CatalogClasspathDo.java    |   13 +-
 .../core/catalog/internal/CatalogDo.java        |    4 +-
 .../core/catalog/internal/CatalogDto.java       |    2 +-
 .../core/catalog/internal/CatalogDtoUtils.java  |    2 +-
 .../catalog/internal/CatalogEntityItemDto.java  |    2 +-
 .../catalog/internal/CatalogInitialization.java |   14 +-
 .../core/catalog/internal/CatalogItemDo.java    |    8 +-
 .../internal/CatalogItemDtoAbstract.java        |   13 +-
 .../internal/CatalogTemplateItemDto.java        |    2 +-
 .../core/catalog/internal/CatalogUtils.java     |   25 +-
 .../catalog/internal/CatalogXmlSerializer.java  |    9 +-
 .../brooklyn/core/config/BasicConfigKey.java    |  281 +++
 .../brooklyn/core/config/BrooklynLogging.java   |   74 -
 .../core/config/BrooklynProperties.java         |  483 -----
 .../core/config/BrooklynServerConfig.java       |  192 --
 .../core/config/BrooklynServerPaths.java        |  281 ---
 .../core/config/BrooklynServiceAttributes.java  |   66 -
 .../apache/brooklyn/core/config/ConfigKeys.java |  265 +++
 .../brooklyn/core/config/ConfigUtils.java       |    5 +-
 .../brooklyn/core/config/ListConfigKey.java     |  128 ++
 .../brooklyn/core/config/MapConfigKey.java      |  206 +++
 .../apache/brooklyn/core/config/Sanitizer.java  |  172 ++
 .../brooklyn/core/config/SetConfigKey.java      |  119 ++
 .../core/config/StructuredConfigKey.java        |   60 +
 .../core/config/SubElementConfigKey.java        |   77 +
 .../internal/AbstractCollectionConfigKey.java   |  120 ++
 .../config/internal/AbstractConfigMapImpl.java  |    9 +-
 .../internal/AbstractStructuredConfigKey.java   |  139 ++
 .../core/config/render/RendererHints.java       |    2 +-
 .../core/internal/ApiObjectsFactoryImpl.java    |   41 +
 .../internal/BrooklynFeatureEnablement.java     |    5 +-
 .../core/internal/BrooklynInitialization.java   |   10 +-
 .../core/internal/BrooklynProperties.java       |  482 +++++
 .../core/internal/storage/DataGridFactory.java  |    4 +-
 .../impl/inmemory/InMemoryDataGridFactory.java  |    2 +-
 .../management/ManagementContextInjectable.java |   33 -
 .../AbstractBrooklynClassLoadingContext.java    |   81 -
 .../BrooklynClassLoadingContextSequential.java  |  135 --
 ...ssLoaderFromBrooklynClassLoadingContext.java |   66 -
 .../JavaBrooklynClassLoadingContext.java        |  122 --
 .../OsgiBrooklynClassLoadingContext.java        |  146 --
 .../BasicEntitlementClassDefinition.java        |   56 -
 .../entitlement/EntitlementManagerAdapter.java  |  133 --
 .../entitlement/EntitlementPredicates.java      |   40 -
 .../management/entitlement/Entitlements.java    |  418 -----
 .../entitlement/NotEntitledException.java       |   44 -
 .../entitlement/PerUserEntitlementManager.java  |  100 -
 .../PerUserEntitlementManagerWithDefault.java   |   31 -
 .../entitlement/WebEntitlementContext.java      |   56 -
 .../core/management/ha/BasicMasterChooser.java  |  203 --
 .../ha/HighAvailabilityManagerImpl.java         | 1105 -----------
 .../ha/ManagementPlaneSyncRecordDeltaImpl.java  |  122 --
 ...ntPlaneSyncRecordPersisterToObjectStore.java |  355 ----
 .../core/management/ha/MasterChooser.java       |   39 -
 .../core/management/ha/OsgiManager.java         |  311 ----
 .../internal/AbstractManagementContext.java     |  484 -----
 .../internal/AbstractSubscriptionManager.java   |  141 --
 .../core/management/internal/AccessManager.java |   41 -
 .../internal/AsyncCollectionChangeAdapter.java  |   82 -
 .../internal/BasicSubscriptionContext.java      |  180 --
 .../internal/BrooklynGarbageCollector.java      |  626 -------
 .../internal/BrooklynObjectManagementMode.java  |   31 -
 .../internal/BrooklynObjectManagerInternal.java |   36 -
 .../internal/CollectionChangeListener.java      |   24 -
 .../core/management/internal/EffectorUtils.java |  356 ----
 .../internal/EntityChangeListener.java          |   78 -
 .../internal/EntityManagementSupport.java       |  478 -----
 .../internal/EntityManagementUtils.java         |  325 ----
 .../internal/EntityManagerInternal.java         |   32 -
 ...PropertyChangeToCollectionChangeAdapter.java |   65 -
 .../management/internal/LocalAccessManager.java |  111 --
 .../management/internal/LocalEntityManager.java |  818 --------
 .../internal/LocalLocationManager.java          |  462 -----
 .../internal/LocalManagementContext.java        |  421 -----
 .../internal/LocalSubscriptionManager.java      |  292 ---
 .../management/internal/LocalUsageManager.java  |  429 -----
 .../internal/LocationManagerInternal.java       |   28 -
 .../internal/ManagementContextInternal.java     |  122 --
 .../internal/ManagementTransitionInfo.java      |   48 -
 .../internal/ManagementTransitionMode.java      |  127 --
 .../internal/NonDeploymentAccessManager.java    |   98 -
 .../internal/NonDeploymentEntityManager.java    |  196 --
 .../internal/NonDeploymentLocationManager.java  |  146 --
 .../NonDeploymentManagementContext.java         |  639 -------
 .../internal/NonDeploymentUsageManager.java     |  132 --
 .../internal/QueueingSubscriptionManager.java   |  148 --
 .../core/management/internal/Subscription.java  |   65 -
 .../internal/SubscriptionTracker.java           |  137 --
 .../core/management/internal/UsageListener.java |  103 --
 .../core/management/internal/UsageManager.java  |  166 --
 .../core/management/usage/ApplicationUsage.java |  126 --
 .../core/management/usage/LocationUsage.java    |  135 --
 .../apache/brooklyn/core/mgmt/BrooklynTags.java |   66 +
 .../brooklyn/core/mgmt/BrooklynTaskTags.java    |  447 +++++
 .../brooklyn/core/mgmt/BrooklynTasks.java       |   25 +
 .../core/mgmt/EntityManagementUtils.java        |  323 ++++
 .../core/mgmt/ManagementContextInjectable.java  |   33 +
 .../AbstractBrooklynClassLoadingContext.java    |   81 +
 .../BrooklynClassLoadingContextSequential.java  |  135 ++
 ...ssLoaderFromBrooklynClassLoadingContext.java |   66 +
 .../JavaBrooklynClassLoadingContext.java        |  122 ++
 .../OsgiBrooklynClassLoadingContext.java        |  146 ++
 .../BasicEntitlementClassDefinition.java        |   56 +
 .../entitlement/EntitlementManagerAdapter.java  |  133 ++
 .../mgmt/entitlement/EntitlementPredicates.java |   40 +
 .../core/mgmt/entitlement/Entitlements.java     |  417 +++++
 .../mgmt/entitlement/NotEntitledException.java  |   44 +
 .../entitlement/PerUserEntitlementManager.java  |   99 +
 .../PerUserEntitlementManagerWithDefault.java   |   31 +
 .../mgmt/entitlement/WebEntitlementContext.java |   56 +
 .../core/mgmt/ha/BasicMasterChooser.java        |  203 ++
 .../mgmt/ha/HighAvailabilityManagerImpl.java    | 1104 +++++++++++
 .../ha/ManagementPlaneSyncRecordDeltaImpl.java  |  122 ++
 ...ntPlaneSyncRecordPersisterToObjectStore.java |  354 ++++
 .../brooklyn/core/mgmt/ha/MasterChooser.java    |   39 +
 .../brooklyn/core/mgmt/ha/OsgiManager.java      |  309 ++++
 .../ha/dto/BasicManagementNodeSyncRecord.java   |  194 ++
 .../ha/dto/ManagementPlaneSyncRecordImpl.java   |   99 +
 .../internal/AbstractManagementContext.java     |  482 +++++
 .../internal/AbstractSubscriptionManager.java   |  141 ++
 .../core/mgmt/internal/AccessManager.java       |   41 +
 .../internal/AsyncCollectionChangeAdapter.java  |   82 +
 .../mgmt/internal/BasicSubscriptionContext.java |  180 ++
 .../mgmt/internal/BrooklynGarbageCollector.java |  625 +++++++
 .../internal/BrooklynObjectManagementMode.java  |   31 +
 .../internal/BrooklynObjectManagerInternal.java |   36 +
 .../mgmt/internal/BrooklynShutdownHooks.java    |  242 +++
 .../mgmt/internal/CollectionChangeListener.java |   24 +
 .../core/mgmt/internal/EffectorUtils.java       |  355 ++++
 .../mgmt/internal/EntityChangeListener.java     |   78 +
 .../mgmt/internal/EntityManagementSupport.java  |  477 +++++
 .../mgmt/internal/EntityManagerInternal.java    |   32 +
 ...PropertyChangeToCollectionChangeAdapter.java |   65 +
 .../core/mgmt/internal/LocalAccessManager.java  |  111 ++
 .../core/mgmt/internal/LocalEntityManager.java  |  817 ++++++++
 .../mgmt/internal/LocalLocationManager.java     |  460 +++++
 .../mgmt/internal/LocalManagementContext.java   |  420 +++++
 .../mgmt/internal/LocalSubscriptionManager.java |  291 +++
 .../core/mgmt/internal/LocalUsageManager.java   |  427 +++++
 .../mgmt/internal/LocationManagerInternal.java  |   28 +
 .../internal/ManagementContextInternal.java     |  121 ++
 .../mgmt/internal/ManagementTransitionInfo.java |   48 +
 .../mgmt/internal/ManagementTransitionMode.java |  127 ++
 .../internal/NonDeploymentAccessManager.java    |   98 +
 .../internal/NonDeploymentEntityManager.java    |  196 ++
 .../internal/NonDeploymentLocationManager.java  |  146 ++
 .../NonDeploymentManagementContext.java         |  638 +++++++
 .../internal/NonDeploymentUsageManager.java     |  131 ++
 .../internal/QueueingSubscriptionManager.java   |  148 ++
 .../core/mgmt/internal/Subscription.java        |   65 +
 .../core/mgmt/internal/SubscriptionTracker.java |  137 ++
 .../core/mgmt/internal/UsageListener.java       |  103 ++
 .../core/mgmt/internal/UsageManager.java        |  165 ++
 .../BrooklynMementoPersisterToObjectStore.java  |  697 +++++++
 .../mgmt/persist/BrooklynPersistenceUtils.java  |  269 +++
 .../persist/CatalogItemLibrariesConverter.java  |   68 +
 .../core/mgmt/persist/FileBasedObjectStore.java |  425 +++++
 .../persist/FileBasedStoreObjectAccessor.java   |  132 ++
 .../mgmt/persist/LocationWithObjectStore.java   |   27 +
 .../core/mgmt/persist/MementoSerializer.java    |   52 +
 .../brooklyn/core/mgmt/persist/PersistMode.java |   26 +
 .../persist/PersistenceActivityMetrics.java     |   83 +
 .../mgmt/persist/PersistenceObjectStore.java    |  142 ++
 .../mgmt/persist/RetryingMementoSerializer.java |   95 +
 .../persist/StoreObjectAccessorLocking.java     |  218 +++
 .../core/mgmt/persist/XmlMementoSerializer.java |  505 +++++
 .../AbstractBrooklynObjectRebindSupport.java    |  102 +
 .../rebind/ActivePartialRebindIteration.java    |  164 ++
 .../rebind/BasicCatalogItemRebindSupport.java   |   67 +
 .../mgmt/rebind/BasicEnricherRebindSupport.java |   50 +
 .../mgmt/rebind/BasicEntityRebindSupport.java   |  236 +++
 .../mgmt/rebind/BasicFeedRebindSupport.java     |   49 +
 .../mgmt/rebind/BasicLocationRebindSupport.java |  137 ++
 .../mgmt/rebind/BasicPolicyRebindSupport.java   |   51 +
 .../rebind/ImmediateDeltaChangeListener.java    |  154 ++
 .../mgmt/rebind/InitialFullRebindIteration.java |  133 ++
 .../rebind/PeriodicDeltaChangeListener.java     |  501 +++++
 .../rebind/PersistenceExceptionHandlerImpl.java |  108 ++
 .../core/mgmt/rebind/PersisterDeltaImpl.java    |  174 ++
 .../core/mgmt/rebind/RebindContextImpl.java     |  190 ++
 .../mgmt/rebind/RebindContextLookupContext.java |  157 ++
 .../mgmt/rebind/RebindExceptionHandlerImpl.java |  471 +++++
 .../core/mgmt/rebind/RebindIteration.java       | 1161 ++++++++++++
 .../core/mgmt/rebind/RebindManagerImpl.java     |  664 +++++++
 .../brooklyn/core/mgmt/rebind/TreeUtils.java    |   56 +
 .../core/mgmt/rebind/dto/AbstractMemento.java   |  229 +++
 .../rebind/dto/AbstractTreeNodeMemento.java     |  113 ++
 .../rebind/dto/BasicCatalogItemMemento.java     |  256 +++
 .../mgmt/rebind/dto/BasicEnricherMemento.java   |   93 +
 .../mgmt/rebind/dto/BasicEntityMemento.java     |  326 ++++
 .../core/mgmt/rebind/dto/BasicFeedMemento.java  |   93 +
 .../mgmt/rebind/dto/BasicLocationMemento.java   |  107 ++
 .../mgmt/rebind/dto/BasicPolicyMemento.java     |   93 +
 .../mgmt/rebind/dto/BrooklynMementoImpl.java    |  256 +++
 .../rebind/dto/BrooklynMementoManifestImpl.java |  172 ++
 .../rebind/dto/EntityMementoManifestImpl.java   |   56 +
 .../core/mgmt/rebind/dto/MementoValidators.java |   67 +
 .../mgmt/rebind/dto/MementosGenerators.java     |  481 +++++
 .../mgmt/rebind/dto/MutableBrooklynMemento.java |  293 +++
 .../transformer/BrooklynMementoTransformer.java |   32 +
 .../rebind/transformer/CompoundTransformer.java |  291 +++
 .../transformer/CompoundTransformerLoader.java  |  108 ++
 .../rebind/transformer/RawDataTransformer.java  |   30 +
 .../DeleteOrphanedLocationsTransformer.java     |  125 ++
 .../transformer/impl/XsltTransformer.java       |   59 +
 .../core/mgmt/usage/ApplicationUsage.java       |  126 ++
 .../brooklyn/core/mgmt/usage/LocationUsage.java |  135 ++
 .../core/objs/AbstractBrooklynObject.java       |  248 +++
 .../core/objs/AbstractEntityAdjunct.java        |  514 ++++++
 .../brooklyn/core/objs/AdjunctConfigMap.java    |  139 ++
 .../apache/brooklyn/core/objs/AdjunctType.java  |  173 ++
 .../core/objs/BasicConfigurableObject.java      |  119 ++
 .../core/objs/BasicEntityTypeRegistry.java      |  156 ++
 .../brooklyn/core/objs/BrooklynDynamicType.java |  283 +++
 .../core/objs/BrooklynObjectInternal.java       |  103 ++
 .../core/objs/BrooklynTypeSnapshot.java         |  101 +
 .../brooklyn/core/objs/BrooklynTypes.java       |  131 ++
 .../brooklyn/core/objs/proxy/EntityProxy.java   |   27 +
 .../core/objs/proxy/EntityProxyImpl.java        |  273 +++
 .../core/objs/proxy/InternalEntityFactory.java  |  402 ++++
 .../core/objs/proxy/InternalFactory.java        |  131 ++
 .../objs/proxy/InternalLocationFactory.java     |  151 ++
 .../core/objs/proxy/InternalPolicyFactory.java  |  198 ++
 .../policy/basic/AbstractEntityAdjunct.java     |  510 -----
 .../core/policy/basic/AbstractPolicy.java       |  119 --
 .../brooklyn/core/policy/basic/AdjunctType.java |  173 --
 .../core/policy/basic/ConfigMapImpl.java        |  140 --
 .../core/policy/basic/GeneralPurposePolicy.java |   36 -
 .../brooklyn/core/policy/basic/Policies.java    |   73 -
 .../core/policy/basic/PolicyDynamicType.java    |   44 -
 .../core/policy/basic/PolicyTypeSnapshot.java   |   39 -
 .../core/server/BrooklynServerConfig.java       |  191 ++
 .../core/server/BrooklynServerPaths.java        |  281 +++
 .../core/server/BrooklynServiceAttributes.java  |   66 +
 .../core/server/entity/BrooklynMetrics.java     |   55 +
 .../core/server/entity/BrooklynMetricsImpl.java |   86 +
 .../core/util/BrooklynLanguageExtensions.java   |   47 -
 .../core/util/BrooklynMavenArtifacts.java       |   59 -
 .../core/util/BrooklynNetworkUtils.java         |   42 -
 .../brooklyn/core/util/ResourceUtils.java       |  638 -------
 .../brooklyn/core/util/config/ConfigBag.java    |  589 ------
 .../core/util/crypto/FluentKeySigner.java       |  191 --
 .../brooklyn/core/util/crypto/SecureKeys.java   |  185 --
 .../brooklyn/core/util/file/ArchiveBuilder.java |  423 -----
 .../brooklyn/core/util/file/ArchiveTasks.java   |   57 -
 .../brooklyn/core/util/file/ArchiveUtils.java   |  350 ----
 .../core/util/flags/ClassCoercionException.java |   39 -
 .../brooklyn/core/util/flags/FlagUtils.java     |  586 ------
 .../core/util/flags/MethodCoercions.java        |  185 --
 .../brooklyn/core/util/flags/SetFromFlag.java   |   71 -
 .../brooklyn/core/util/flags/TypeCoercions.java |  879 ---------
 .../brooklyn/core/util/http/HttpTool.java       |  386 ----
 .../core/util/http/HttpToolResponse.java        |  185 --
 .../util/internal/ConfigKeySelfExtracting.java  |   40 -
 .../brooklyn/core/util/internal/Repeater.java   |  369 ----
 .../ssh/BackoffLimitedRetryHandler.java         |   73 -
 .../util/internal/ssh/ShellAbstractTool.java    |  441 -----
 .../core/util/internal/ssh/ShellTool.java       |  114 --
 .../core/util/internal/ssh/SshAbstractTool.java |  172 --
 .../core/util/internal/ssh/SshException.java    |   32 -
 .../core/util/internal/ssh/SshTool.java         |  175 --
 .../core/util/internal/ssh/cli/SshCliTool.java  |  317 ----
 .../util/internal/ssh/process/ProcessTool.java  |  214 ---
 .../internal/ssh/sshj/SshjClientConnection.java |  281 ---
 .../core/util/internal/ssh/sshj/SshjTool.java   | 1090 -----------
 .../core/util/javalang/ReflectionScanner.java   |  134 --
 .../core/util/javalang/UrlClassLoader.java      |   69 -
 .../brooklyn/core/util/mutex/MutexSupport.java  |  119 --
 .../core/util/mutex/SemaphoreForTasks.java      |  111 --
 .../core/util/mutex/SemaphoreWithOwners.java    |  231 ---
 .../brooklyn/core/util/mutex/WithMutexes.java   |   45 -
 .../apache/brooklyn/core/util/osgi/Osgis.java   |  719 --------
 .../util/task/AbstractExecutionContext.java     |   75 -
 .../core/util/task/BasicExecutionContext.java   |  221 ---
 .../core/util/task/BasicExecutionManager.java   |  754 --------
 .../brooklyn/core/util/task/BasicTask.java      |  891 ---------
 .../brooklyn/core/util/task/CanSetName.java     |   25 -
 .../brooklyn/core/util/task/CompoundTask.java   |  131 --
 .../core/util/task/DeferredSupplier.java        |   38 -
 .../core/util/task/DynamicSequentialTask.java   |  480 -----
 .../brooklyn/core/util/task/DynamicTasks.java   |  337 ----
 .../core/util/task/ExecutionListener.java       |   31 -
 .../brooklyn/core/util/task/ExecutionUtils.java |   49 -
 .../brooklyn/core/util/task/ForwardingTask.java |  324 ----
 .../util/task/ListenableForwardingFuture.java   |   50 -
 .../brooklyn/core/util/task/ParallelTask.java   |   84 -
 .../brooklyn/core/util/task/ScheduledTask.java  |  184 --
 .../brooklyn/core/util/task/SequentialTask.java |   58 -
 .../core/util/task/SingleThreadedScheduler.java |  216 ---
 .../brooklyn/core/util/task/TaskBuilder.java    |  183 --
 .../brooklyn/core/util/task/TaskInternal.java   |  124 --
 .../brooklyn/core/util/task/TaskScheduler.java  |   41 -
 .../brooklyn/core/util/task/TaskTags.java       |   71 -
 .../apache/brooklyn/core/util/task/Tasks.java   |  487 -----
 .../brooklyn/core/util/task/ValueResolver.java  |  426 -----
 .../core/util/task/ssh/SshFetchTaskFactory.java |   88 -
 .../core/util/task/ssh/SshFetchTaskWrapper.java |  134 --
 .../core/util/task/ssh/SshPutTaskFactory.java   |  122 --
 .../core/util/task/ssh/SshPutTaskStub.java      |   69 -
 .../core/util/task/ssh/SshPutTaskWrapper.java   |  189 --
 .../brooklyn/core/util/task/ssh/SshTasks.java   |  235 ---
 .../internal/AbstractSshExecTaskFactory.java    |   58 -
 .../ssh/internal/PlainSshExecTaskFactory.java   |   71 -
 .../util/task/system/ProcessTaskFactory.java    |   64 -
 .../core/util/task/system/ProcessTaskStub.java  |  101 -
 .../util/task/system/ProcessTaskWrapper.java    |  187 --
 .../core/util/task/system/SystemTasks.java      |   29 -
 .../internal/AbstractProcessTaskFactory.java    |  215 ---
 .../system/internal/ExecWithLoggingHelpers.java |  199 --
 .../internal/SystemProcessTaskFactory.java      |  130 --
 .../core/util/text/DataUriSchemeParser.java     |  267 ---
 .../core/util/text/TemplateProcessor.java       |  398 ----
 ...ompilerIndependentOuterClassFieldMapper.java |  166 --
 .../xstream/EnumCaseForgivingConverter.java     |   60 -
 .../EnumCaseForgivingSingleValueConverter.java  |   35 -
 .../util/xstream/ImmutableListConverter.java    |   54 -
 .../util/xstream/ImmutableMapConverter.java     |   56 -
 .../util/xstream/ImmutableSetConverter.java     |   54 -
 .../util/xstream/Inet4AddressConverter.java     |   65 -
 .../core/util/xstream/MapConverter.java         |  104 --
 .../core/util/xstream/MutableSetConverter.java  |   44 -
 .../util/xstream/StringKeyMapConverter.java     |  133 --
 .../core/util/xstream/XmlSerializer.java        |   97 -
 .../brooklyn/core/util/xstream/XmlUtil.java     |   58 -
 .../effector/core/AbstractEffector.java         |   90 +
 .../effector/core/AddChildrenEffector.java      |  117 ++
 .../brooklyn/effector/core/AddEffector.java     |  116 ++
 .../brooklyn/effector/core/AddSensor.java       |  126 ++
 .../effector/core/BasicParameterType.java       |  116 ++
 .../brooklyn/effector/core/EffectorAndBody.java |   60 +
 .../brooklyn/effector/core/EffectorBase.java    |  106 ++
 .../brooklyn/effector/core/EffectorBody.java    |  100 +
 .../brooklyn/effector/core/EffectorTasks.java   |  229 +++
 .../effector/core/EffectorWithBody.java         |   32 +
 .../brooklyn/effector/core/Effectors.java       |  202 ++
 .../effector/core/ExplicitEffector.java         |   74 +
 .../brooklyn/effector/core/MethodEffector.java  |  180 ++
 .../brooklyn/entity/annotation/Effector.java    |   33 +
 .../entity/annotation/EffectorParam.java        |   42 +
 .../entity/core/AbstractApplication.java        |  264 +++
 .../brooklyn/entity/core/AbstractEntity.java    | 1739 ++++++++++++++++++
 .../apache/brooklyn/entity/core/Attributes.java |  169 ++
 .../entity/core/BrooklynConfigKeys.java         |  188 ++
 .../apache/brooklyn/entity/core/Entities.java   | 1108 +++++++++++
 .../brooklyn/entity/core/EntityAdjuncts.java    |   70 +
 .../entity/core/EntityAndAttribute.java         |  107 ++
 .../brooklyn/entity/core/EntityDynamicType.java |  339 ++++
 .../brooklyn/entity/core/EntityFunctions.java   |  153 ++
 .../entity/core/EntityInitializers.java         |   49 +
 .../brooklyn/entity/core/EntityInternal.java    |  201 ++
 .../brooklyn/entity/core/EntityPredicates.java  |  451 +++++
 .../brooklyn/entity/core/EntitySuppliers.java   |   47 +
 .../brooklyn/entity/core/EntityTasks.java       |   81 +
 .../entity/core/EntityTypeSnapshot.java         |  126 ++
 .../brooklyn/entity/core/EntityTypes.java       |   28 +
 .../entity/core/StartableApplication.java       |   25 +
 .../internal/ConfigMapViewWithStringKeys.java   |  130 ++
 .../entity/core/internal/EntityConfigMap.java   |  306 +++
 .../internal/EntityTransientCopyInternal.java   |  121 ++
 .../drivers/BasicEntityDriverManager.java       |   56 +
 .../drivers/ReflectiveEntityDriverFactory.java  |  277 +++
 .../drivers/RegistryEntityDriverFactory.java    |  127 ++
 .../downloads/BasicDownloadRequirement.java     |   85 +
 .../downloads/BasicDownloadResolver.java        |   66 +
 .../drivers/downloads/BasicDownloadTargets.java |  121 ++
 .../downloads/BasicDownloadsManager.java        |  161 ++
 .../DownloadProducerFromCloudsoftRepo.java      |   83 +
 .../DownloadProducerFromLocalRepo.java          |   84 +
 .../DownloadProducerFromProperties.java         |  344 ++++
 .../DownloadProducerFromUrlAttribute.java       |   63 +
 .../drivers/downloads/DownloadSubstituters.java |  172 ++
 .../drivers/downloads/FilenameProducers.java    |   64 +
 .../AbstractConfigurableEntityFactory.java      |   82 +
 .../entity/factory/ApplicationBuilder.java      |  247 +++
 .../factory/BasicConfigurableEntityFactory.java |   75 +
 .../entity/factory/ClosureEntityFactory.java    |   53 +
 .../factory/ConfigurableEntityFactory.java      |   33 +
 ...figurableEntityFactoryFromEntityFactory.java |   45 +
 .../brooklyn/entity/factory/EntityFactory.java  |   32 +
 .../factory/EntityFactoryForLocation.java       |   30 +
 .../brooklyn/entity/group/AbstractGroup.java    |   86 +
 .../entity/group/AbstractGroupImpl.java         |  276 +++
 .../group/AbstractMembershipTrackingPolicy.java |  246 +++
 .../brooklyn/entity/group/BasicGroup.java       |   36 +
 .../brooklyn/entity/group/BasicGroupImpl.java   |   46 +
 .../apache/brooklyn/entity/group/Cluster.java   |   35 +
 .../brooklyn/entity/group/DynamicCluster.java   |  201 ++
 .../entity/group/DynamicClusterImpl.java        |  885 +++++++++
 .../brooklyn/entity/group/DynamicFabric.java    |   75 +
 .../entity/group/DynamicFabricImpl.java         |  274 +++
 .../brooklyn/entity/group/DynamicGroup.java     |   89 +
 .../brooklyn/entity/group/DynamicGroupImpl.java |  230 +++
 .../entity/group/DynamicMultiGroup.java         |  103 ++
 .../entity/group/DynamicMultiGroupImpl.java     |  203 ++
 .../entity/group/DynamicRegionsFabric.java      |   42 +
 .../entity/group/DynamicRegionsFabricImpl.java  |   77 +
 .../apache/brooklyn/entity/group/Fabric.java    |   26 +
 .../brooklyn/entity/group/QuarantineGroup.java  |   35 +
 .../entity/group/QuarantineGroupImpl.java       |  102 +
 .../group/StopFailedRuntimeException.java       |   40 +
 .../org/apache/brooklyn/entity/group/Tier.java  |   28 +
 .../zoneaware/AbstractZoneFailureDetector.java  |  126 ++
 .../BalancingNodePlacementStrategy.java         |  131 ++
 .../zoneaware/CombiningZoneFailureDetector.java |   81 +
 .../CriticalCauseZoneFailureDetector.java       |   56 +
 .../ProportionalZoneFailureDetector.java        |   59 +
 .../brooklyn/entity/lifecycle/Lifecycle.java    |  185 ++
 .../entity/lifecycle/PolicyDescriptor.java      |   68 +
 .../brooklyn/entity/lifecycle/QuorumCheck.java  |  108 ++
 .../entity/lifecycle/ServiceStateLogic.java     |  639 +++++++
 .../brooklyn/entity/stock/BasicApplication.java |   32 +
 .../entity/stock/BasicApplicationImpl.java      |   33 +
 .../brooklyn/entity/stock/BasicEntity.java      |   34 +
 .../brooklyn/entity/stock/BasicEntityImpl.java  |   30 +
 .../brooklyn/entity/stock/BasicStartable.java   |   56 +
 .../entity/stock/BasicStartableImpl.java        |  106 ++
 .../brooklyn/entity/stock/DataEntity.java       |   58 +
 .../brooklyn/entity/stock/DataEntityImpl.java   |   79 +
 .../brooklyn/entity/stock/DelegateEntity.java   |   73 +
 .../entity/stock/DelegateEntityImpl.java        |   49 +
 .../entity/stock/EffectorStartableImpl.java     |   79 +
 .../brooklyn/entity/trait/Changeable.java       |   35 +
 .../entity/trait/MemberReplaceable.java         |   45 +
 .../apache/brooklyn/entity/trait/Resizable.java |   50 +
 .../apache/brooklyn/entity/trait/Startable.java |  123 ++
 .../brooklyn/entity/trait/StartableMethods.java |  125 ++
 .../location/access/BrooklynAccessUtils.java    |   20 +-
 .../location/access/PortForwardManager.java     |    3 +-
 .../access/PortForwardManagerAuthority.java     |    3 +-
 .../access/PortForwardManagerClient.java        |    2 +-
 .../location/access/PortForwardManagerImpl.java |   11 +-
 .../PortForwardManagerLocationResolver.java     |   10 +-
 .../location/basic/AbstractLocation.java        |  709 -------
 .../basic/AbstractLocationResolver.java         |  188 --
 .../AggregatingMachineProvisioningLocation.java |  139 --
 .../location/basic/BasicHardwareDetails.java    |   56 -
 .../location/basic/BasicLocationDefinition.java |   85 -
 .../location/basic/BasicLocationRegistry.java   |  479 -----
 .../location/basic/BasicMachineDetails.java     |  180 --
 .../location/basic/BasicMachineMetadata.java    |   84 -
 .../brooklyn/location/basic/BasicOsDetails.java |  123 --
 .../location/basic/ByonLocationResolver.java    |  251 ---
 .../location/basic/CatalogLocationResolver.java |   79 -
 .../basic/DefinedLocationByIdResolver.java      |   74 -
 .../basic/DeprecatedKeysMappingBuilder.java     |   66 -
 .../FixedListMachineProvisioningLocation.java   |  475 -----
 .../location/basic/HasSubnetHostname.java       |   32 -
 .../location/basic/HostLocationResolver.java    |   90 -
 .../basic/LocalhostLocationResolver.java        |   74 -
 .../LocalhostMachineProvisioningLocation.java   |  347 ----
 ...calhostPropertiesFromBrooklynProperties.java |   56 -
 .../location/basic/LocationConfigKeys.java      |   80 -
 .../location/basic/LocationConfigUtils.java     |  560 ------
 .../location/basic/LocationDynamicType.java     |   40 -
 .../location/basic/LocationInternal.java        |   94 -
 .../location/basic/LocationPredicates.java      |  108 --
 ...ocationPropertiesFromBrooklynProperties.java |  223 ---
 .../location/basic/LocationTypeSnapshot.java    |   40 -
 .../brooklyn/location/basic/Locations.java      |  159 --
 .../brooklyn/location/basic/Machines.java       |  189 --
 .../brooklyn/location/basic/MultiLocation.java  |  167 --
 .../location/basic/MultiLocationResolver.java   |  145 --
 .../location/basic/NamedLocationResolver.java   |   96 -
 .../brooklyn/location/basic/PortRanges.java     |  257 ---
 .../basic/RegistryLocationResolver.java         |   42 -
 .../basic/SingleMachineLocationResolver.java    |   77 -
 .../SingleMachineProvisioningLocation.java      |   91 -
 .../location/basic/SshMachineLocation.java      | 1033 -----------
 .../location/basic/SupportsPortForwarding.java  |   39 -
 .../location/basic/WinRmMachineLocation.java    |  362 ----
 .../location/byon/ByonLocationResolver.java     |  253 +++
 .../FixedListMachineProvisioningLocation.java   |  476 +++++
 .../location/byon/HostLocationResolver.java     |   93 +
 .../byon/SingleMachineLocationResolver.java     |   81 +
 .../byon/SingleMachineProvisioningLocation.java |   91 +
 .../AbstractAvailabilityZoneExtension.java      |    2 +-
 ...bstractCloudMachineProvisioningLocation.java |    6 +-
 .../cloud/AvailabilityZoneExtension.java        |    5 +-
 .../location/cloud/CloudLocationConfig.java     |    9 +-
 .../cloud/names/AbstractCloudMachineNamer.java  |    4 +-
 .../cloud/names/BasicCloudMachineNamer.java     |    2 +-
 .../location/cloud/names/CloudMachineNamer.java |    2 +-
 .../cloud/names/CustomMachineNamer.java         |   10 +-
 .../location/core/AbstractLocation.java         |  709 +++++++
 .../location/core/AbstractLocationResolver.java |  188 ++
 .../AggregatingMachineProvisioningLocation.java |  141 ++
 .../location/core/BasicHardwareDetails.java     |   56 +
 .../location/core/BasicLocationDefinition.java  |   85 +
 .../location/core/BasicLocationRegistry.java    |  489 +++++
 .../location/core/BasicMachineDetails.java      |  183 ++
 .../location/core/BasicMachineMetadata.java     |   84 +
 .../brooklyn/location/core/BasicOsDetails.java  |  123 ++
 .../location/core/CatalogLocationResolver.java  |   79 +
 .../core/DefinedLocationByIdResolver.java       |   74 +
 .../core/DeprecatedKeysMappingBuilder.java      |   66 +
 .../location/core/HasSubnetHostname.java        |   32 +
 .../location/core/LocationConfigKeys.java       |   79 +
 .../location/core/LocationConfigUtils.java      |  559 ++++++
 .../location/core/LocationPredicates.java       |  108 ++
 ...ocationPropertiesFromBrooklynProperties.java |  223 +++
 .../brooklyn/location/core/Locations.java       |  160 ++
 .../apache/brooklyn/location/core/Machines.java |  191 ++
 .../brooklyn/location/core/MultiLocation.java   |  166 ++
 .../location/core/MultiLocationResolver.java    |  145 ++
 .../location/core/NamedLocationResolver.java    |   97 +
 .../brooklyn/location/core/PortRanges.java      |  257 +++
 .../location/core/RegistryLocationResolver.java |   42 +
 .../location/core/SupportsPortForwarding.java   |   39 +
 .../core/internal/LocationDynamicType.java      |   40 +
 .../core/internal/LocationInternal.java         |   93 +
 .../core/internal/LocationTypeSnapshot.java     |   40 +
 .../location/dynamic/DynamicLocation.java       |    5 +-
 .../location/dynamic/LocationOwner.java         |   11 +-
 .../brooklyn/location/geo/HostGeoInfo.java      |    6 +-
 .../location/geo/LocalhostExternalIpLoader.java |    2 +-
 .../localhost/LocalhostLocationResolver.java    |   76 +
 .../LocalhostMachineProvisioningLocation.java   |  352 ++++
 ...calhostPropertiesFromBrooklynProperties.java |   57 +
 .../location/ssh/SshMachineLocation.java        | 1037 +++++++++++
 .../winrm/AdvertiseWinrmLoginPolicy.java        |   80 +
 .../location/winrm/WinRmMachineLocation.java    |  362 ++++
 .../brooklyn/policy/core/AbstractPolicy.java    |  119 ++
 .../policy/core/GeneralPurposePolicy.java       |   36 +
 .../apache/brooklyn/policy/core/Policies.java   |   73 +
 .../brooklyn/policy/core/PolicyDynamicType.java |   43 +
 .../policy/core/PolicyTypeSnapshot.java         |   39 +
 .../brooklyn/sensor/core/AttributeMap.java      |  202 ++
 .../core/AttributeSensorAndConfigKey.java       |  147 ++
 .../sensor/core/BasicAttributeSensor.java       |   62 +
 .../core/BasicAttributeSensorAndConfigKey.java  |  114 ++
 .../sensor/core/BasicNotificationSensor.java    |   36 +
 .../brooklyn/sensor/core/BasicSensor.java       |  114 ++
 .../brooklyn/sensor/core/BasicSensorEvent.java  |  112 ++
 .../sensor/core/DependentConfiguration.java     |  823 +++++++++
 .../brooklyn/sensor/core/HttpRequestSensor.java |   96 +
 .../core/PortAttributeSensorAndConfigKey.java   |  141 ++
 .../apache/brooklyn/sensor/core/Sensors.java    |  164 ++
 .../brooklyn/sensor/core/StaticSensor.java      |   72 +
 ...platedStringAttributeSensorAndConfigKey.java |   66 +
 .../enricher/AbstractAggregatingEnricher.java   |  173 ++
 .../sensor/enricher/AbstractAggregator.java     |  237 +++
 .../sensor/enricher/AbstractEnricher.java       |  115 ++
 .../AbstractMultipleSensorAggregator.java       |  169 ++
 .../sensor/enricher/AbstractTransformer.java    |  100 +
 .../enricher/AbstractTransformingEnricher.java  |   38 +
 .../AbstractTypeTransformingEnricher.java       |   67 +
 .../sensor/enricher/AddingEnricher.java         |  106 ++
 .../brooklyn/sensor/enricher/Aggregator.java    |  221 +++
 .../brooklyn/sensor/enricher/Combiner.java      |  137 ++
 .../enricher/CustomAggregatingEnricher.java     |  320 ++++
 .../sensor/enricher/EnricherDynamicType.java    |   43 +
 .../sensor/enricher/EnricherTypeSnapshot.java   |   39 +
 .../brooklyn/sensor/enricher/Enrichers.java     |  824 +++++++++
 .../apache/brooklyn/sensor/enricher/Joiner.java |  126 ++
 .../brooklyn/sensor/enricher/Propagator.java    |  200 ++
 .../enricher/SensorPropagatingEnricher.java     |  180 ++
 .../enricher/SensorTransformingEnricher.java    |  106 ++
 .../brooklyn/sensor/enricher/Transformer.java   |  103 ++
 .../brooklyn/sensor/enricher/UpdatingMap.java   |  158 ++
 .../YamlRollingTimeWindowMeanEnricher.java      |  178 ++
 .../enricher/YamlTimeWeightedDeltaEnricher.java |   83 +
 .../brooklyn/sensor/feed/AbstractFeed.java      |  240 +++
 .../sensor/feed/AttributePollHandler.java       |  248 +++
 .../sensor/feed/ConfigToAttributes.java         |   59 +
 .../sensor/feed/DelegatingPollHandler.java      |   96 +
 .../apache/brooklyn/sensor/feed/FeedConfig.java |  297 +++
 .../apache/brooklyn/sensor/feed/PollConfig.java |   85 +
 .../brooklyn/sensor/feed/PollHandler.java       |   38 +
 .../org/apache/brooklyn/sensor/feed/Poller.java |  205 +++
 .../sensor/feed/function/FunctionFeed.java      |  208 +++
 .../feed/function/FunctionPollConfig.java       |  111 ++
 .../brooklyn/sensor/feed/http/HttpFeed.java     |  382 ++++
 .../sensor/feed/http/HttpPollConfig.java        |  160 ++
 .../sensor/feed/http/HttpPollValue.java         |   40 +
 .../brooklyn/sensor/feed/http/HttpPolls.java    |   39 +
 .../sensor/feed/http/HttpValueFunctions.java    |  154 ++
 .../sensor/feed/http/JsonFunctions.java         |  235 +++
 .../brooklyn/sensor/feed/shell/ShellFeed.java   |  273 +++
 .../sensor/feed/shell/ShellPollConfig.java      |  125 ++
 .../brooklyn/sensor/feed/ssh/SshFeed.java       |  290 +++
 .../brooklyn/sensor/feed/ssh/SshPollConfig.java |  142 ++
 .../brooklyn/sensor/feed/ssh/SshPollValue.java  |   60 +
 .../sensor/feed/ssh/SshValueFunctions.java      |   73 +
 .../windows/WindowsPerformanceCounterFeed.java  |  412 +++++
 .../WindowsPerformanceCounterPollConfig.java    |   53 +
 .../util/core/BrooklynLanguageExtensions.java   |   47 +
 .../util/core/BrooklynMavenArtifacts.java       |   58 +
 .../util/core/BrooklynNetworkUtils.java         |   42 +
 .../brooklyn/util/core/ResourceUtils.java       |  638 +++++++
 .../brooklyn/util/core/config/ConfigBag.java    |  588 ++++++
 .../util/core/crypto/FluentKeySigner.java       |  191 ++
 .../brooklyn/util/core/crypto/SecureKeys.java   |  185 ++
 .../brooklyn/util/core/file/ArchiveBuilder.java |  423 +++++
 .../brooklyn/util/core/file/ArchiveTasks.java   |   57 +
 .../brooklyn/util/core/file/ArchiveUtils.java   |  350 ++++
 .../util/core/flags/ClassCoercionException.java |   39 +
 .../brooklyn/util/core/flags/FlagUtils.java     |  586 ++++++
 .../util/core/flags/MethodCoercions.java        |  185 ++
 .../brooklyn/util/core/flags/SetFromFlag.java   |   71 +
 .../brooklyn/util/core/flags/TypeCoercions.java |  878 +++++++++
 .../brooklyn/util/core/http/HttpTool.java       |  386 ++++
 .../util/core/http/HttpToolResponse.java        |  184 ++
 .../core/internal/ConfigKeySelfExtracting.java  |   40 +
 .../brooklyn/util/core/internal/Repeater.java   |  369 ++++
 .../ssh/BackoffLimitedRetryHandler.java         |   73 +
 .../core/internal/ssh/ShellAbstractTool.java    |  441 +++++
 .../util/core/internal/ssh/ShellTool.java       |  113 ++
 .../util/core/internal/ssh/SshAbstractTool.java |  172 ++
 .../util/core/internal/ssh/SshException.java    |   32 +
 .../util/core/internal/ssh/SshTool.java         |  174 ++
 .../util/core/internal/ssh/cli/SshCliTool.java  |  316 ++++
 .../core/internal/ssh/process/ProcessTool.java  |  214 +++
 .../internal/ssh/sshj/SshjClientConnection.java |  281 +++
 .../util/core/internal/ssh/sshj/SshjTool.java   | 1090 +++++++++++
 .../util/core/javalang/ReflectionScanner.java   |  134 ++
 .../util/core/javalang/UrlClassLoader.java      |   69 +
 .../brooklyn/util/core/mutex/MutexSupport.java  |  119 ++
 .../util/core/mutex/SemaphoreForTasks.java      |  111 ++
 .../util/core/mutex/SemaphoreWithOwners.java    |  231 +++
 .../brooklyn/util/core/mutex/WithMutexes.java   |   45 +
 .../apache/brooklyn/util/core/osgi/Osgis.java   |  719 ++++++++
 .../core/task/AbstractExecutionContext.java     |   75 +
 .../util/core/task/BasicExecutionContext.java   |  220 +++
 .../util/core/task/BasicExecutionManager.java   |  754 ++++++++
 .../brooklyn/util/core/task/BasicTask.java      |  891 +++++++++
 .../brooklyn/util/core/task/CanSetName.java     |   25 +
 .../brooklyn/util/core/task/CompoundTask.java   |  130 ++
 .../util/core/task/DeferredSupplier.java        |   38 +
 .../util/core/task/DynamicSequentialTask.java   |  479 +++++
 .../brooklyn/util/core/task/DynamicTasks.java   |  336 ++++
 .../util/core/task/ExecutionListener.java       |   31 +
 .../brooklyn/util/core/task/ExecutionUtils.java |   49 +
 .../brooklyn/util/core/task/ForwardingTask.java |  324 ++++
 .../core/task/ListenableForwardingFuture.java   |   50 +
 .../brooklyn/util/core/task/ParallelTask.java   |   84 +
 .../brooklyn/util/core/task/ScheduledTask.java  |  184 ++
 .../brooklyn/util/core/task/SequentialTask.java |   58 +
 .../util/core/task/SingleThreadedScheduler.java |  216 +++
 .../brooklyn/util/core/task/TaskBuilder.java    |  183 ++
 .../brooklyn/util/core/task/TaskInternal.java   |  124 ++
 .../brooklyn/util/core/task/TaskScheduler.java  |   41 +
 .../brooklyn/util/core/task/TaskTags.java       |   71 +
 .../apache/brooklyn/util/core/task/Tasks.java   |  487 +++++
 .../brooklyn/util/core/task/ValueResolver.java  |  425 +++++
 .../util/core/task/ssh/SshFetchTaskFactory.java |   88 +
 .../util/core/task/ssh/SshFetchTaskWrapper.java |  134 ++
 .../util/core/task/ssh/SshPutTaskFactory.java   |  122 ++
 .../util/core/task/ssh/SshPutTaskStub.java      |   69 +
 .../util/core/task/ssh/SshPutTaskWrapper.java   |  189 ++
 .../brooklyn/util/core/task/ssh/SshTasks.java   |  233 +++
 .../internal/AbstractSshExecTaskFactory.java    |   58 +
 .../ssh/internal/PlainSshExecTaskFactory.java   |   71 +
 .../core/task/system/ProcessTaskFactory.java    |   64 +
 .../util/core/task/system/ProcessTaskStub.java  |  101 +
 .../core/task/system/ProcessTaskWrapper.java    |  186 ++
 .../util/core/task/system/SystemTasks.java      |   29 +
 .../internal/AbstractProcessTaskFactory.java    |  213 +++
 .../system/internal/ExecWithLoggingHelpers.java |  199 ++
 .../internal/SystemProcessTaskFactory.java      |  130 ++
 .../util/core/text/DataUriSchemeParser.java     |  267 +++
 .../util/core/text/TemplateProcessor.java       |  397 ++++
 ...ompilerIndependentOuterClassFieldMapper.java |  166 ++
 .../xstream/EnumCaseForgivingConverter.java     |   60 +
 .../EnumCaseForgivingSingleValueConverter.java  |   35 +
 .../core/xstream/ImmutableListConverter.java    |   54 +
 .../core/xstream/ImmutableMapConverter.java     |   56 +
 .../core/xstream/ImmutableSetConverter.java     |   54 +
 .../core/xstream/Inet4AddressConverter.java     |   65 +
 .../util/core/xstream/MapConverter.java         |  104 ++
 .../util/core/xstream/MutableSetConverter.java  |   44 +
 .../core/xstream/StringKeyMapConverter.java     |  133 ++
 .../util/core/xstream/XmlSerializer.java        |   97 +
 .../brooklyn/util/core/xstream/XmlUtil.java     |   58 +
 ...pi.basic.internal.ApiObjectsFactoryInterface |   19 -
 ...klyn.api.internal.ApiObjectsFactoryInterface |   19 +
 ...pache.brooklyn.api.location.LocationResolver |   16 +-
 .../recursiveCopyWithExtraRules.xslt            |   32 -
 .../recursiveCopyWithExtraRules.xslt            |   32 +
 .../test/java/brooklyn/BrooklynVersionTest.java |  126 --
 ...stomAggregatingEnricherDeprecatedTest.groovy |  367 ----
 .../enricher/CustomAggregatingEnricherTest.java |  557 ------
 .../java/brooklyn/enricher/EnrichersTest.java   |  503 -----
 ...SensorPropagatingEnricherDeprecatedTest.java |  109 --
 .../enricher/SensorPropagatingEnricherTest.java |  218 ---
 .../TransformingEnricherDeprecatedTest.groovy   |   84 -
 .../enricher/TransformingEnricherTest.java      |   72 -
 .../enricher/basic/BasicEnricherTest.java       |  119 --
 .../enricher/basic/EnricherConfigTest.java      |  148 --
 .../YamlRollingTimeWindowMeanEnricherTest.java  |  178 --
 .../YamlTimeWeightedDeltaEnricherTest.java      |  107 --
 .../entity/BrooklynAppLiveTestSupport.java      |   67 -
 .../entity/BrooklynAppUnitTestSupport.java      |   75 -
 .../brooklyn/entity/EffectorMetadataTest.java   |  166 --
 .../entity/EffectorSayHiGroovyTest.groovy       |  186 --
 .../java/brooklyn/entity/EffectorSayHiTest.java |  173 --
 .../entity/EntityPreManagementTest.java         |  147 --
 .../java/brooklyn/entity/SetFromFlagTest.java   |  215 ---
 .../basic/AbstractApplicationLegacyTest.java    |  154 --
 .../entity/basic/AbstractEntityLegacyTest.java  |  129 --
 .../brooklyn/entity/basic/AttributeMapTest.java |  227 ---
 .../brooklyn/entity/basic/AttributeTest.java    |   67 -
 .../entity/basic/BasicStartableTest.java        |  172 --
 .../entity/basic/BrooklynShutdownHooksTest.java |   92 -
 .../basic/ConfigEntityInheritanceTest.java      |  188 --
 .../brooklyn/entity/basic/ConfigKeysTest.java   |   87 -
 .../entity/basic/ConfigMapGroovyTest.groovy     |   61 -
 .../brooklyn/entity/basic/ConfigMapTest.java    |  296 ---
 .../brooklyn/entity/basic/DataEntityTest.java   |  141 --
 .../basic/DependentConfigurationTest.java       |  410 -----
 .../entity/basic/DynamicEntityTest.java         |   59 -
 .../brooklyn/entity/basic/DynamicGroupTest.java |  545 ------
 .../brooklyn/entity/basic/EntitiesTest.java     |  133 --
 .../basic/EntityConfigMapUsageLegacyTest.java   |  292 ---
 .../entity/basic/EntityConfigMapUsageTest.java  |  319 ----
 .../brooklyn/entity/basic/EntityConfigTest.java |  174 --
 .../entity/basic/EntityFunctionsTest.java       |   77 -
 .../entity/basic/EntityLocationsTest.java       |  127 --
 .../entity/basic/EntityPredicatesTest.java      |  127 --
 .../entity/basic/EntityRegistrationTest.java    |  101 -
 .../brooklyn/entity/basic/EntitySpecTest.java   |  214 ---
 .../entity/basic/EntitySubscriptionTest.java    |  243 ---
 .../entity/basic/EntitySuppliersTest.java       |   71 -
 .../brooklyn/entity/basic/EntityTypeTest.java   |  282 ---
 .../entity/basic/LifecycleTransitionTest.java   |   51 -
 .../basic/MapConfigKeyAndFriendsMoreTest.java   |  274 ---
 ...apListAndOtherStructuredConfigKeyTest.groovy |  357 ----
 .../entity/basic/OwnedChildrenTest.java         |  210 ---
 .../entity/basic/PolicyRegistrationTest.java    |  151 --
 .../brooklyn/entity/basic/SanitizerTest.java    |   37 -
 .../entity/basic/ServiceStateLogicTest.java     |  309 ----
 .../drivers/BasicEntityDriverManagerTest.java   |   75 -
 .../drivers/EntityDriverRegistryTest.java       |   61 -
 .../ReflectiveEntityDriverFactoryTest.java      |  171 --
 .../RegistryEntityDriverFactoryTest.java        |   87 -
 .../downloads/BasicDownloadsRegistryTest.java   |  157 --
 .../DownloadProducerFromLocalRepoTest.java      |  130 --
 .../DownloadProducerFromPropertiesTest.java     |  161 --
 .../downloads/DownloadSubstitutersTest.java     |  131 --
 .../downloads/FilenameProducersTest.java        |   33 -
 .../drivers/downloads/MyEntityDriver.java       |   44 -
 .../entity/effector/EffectorBasicTest.java      |  185 --
 .../effector/EffectorConcatenateTest.java       |  242 ---
 .../entity/effector/EffectorTaskTest.java       |  434 -----
 .../entity/group/DynamicClusterTest.java        |  985 ----------
 ...DynamicClusterWithAvailabilityZonesTest.java |  226 ---
 .../entity/group/DynamicFabricTest.java         |  498 -----
 .../entity/group/DynamicMultiGroupTest.java     |  224 ---
 .../entity/group/DynamicRegionsFabricTest.java  |  171 --
 .../entity/group/GroupPickUpEntitiesTest.java   |  158 --
 .../java/brooklyn/entity/group/GroupTest.java   |  145 --
 .../group/MembershipTrackingPolicyTest.java     |  314 ----
 .../entity/group/QuarantineGroupTest.java       |   86 -
 .../BalancingNodePlacementStrategyTest.java     |  117 --
 .../ProportionalZoneFailureDetectorTest.java    |  124 --
 .../java/brooklyn/entity/hello/HelloEntity.java |   54 -
 .../brooklyn/entity/hello/HelloEntityImpl.java  |   31 -
 .../entity/hello/LocalEntitiesTest.java         |  284 ---
 .../ApplicationBuilderOverridingTest.java       |  221 ---
 .../proxying/BasicEntityTypeRegistryTest.java   |  135 --
 .../entity/proxying/EntityManagerTest.java      |   83 -
 .../entity/proxying/EntityProxyTest.java        |  171 --
 .../proxying/InternalEntityFactoryTest.java     |  107 --
 .../entity/rebind/ActivePartialRebindTest.java  |  108 --
 .../rebind/ActivePartialRebindVersionTest.java  |  119 --
 .../entity/rebind/CheckpointEntityTest.java     |  110 --
 .../java/brooklyn/entity/rebind/Dumpers.java    |  273 ---
 .../entity/rebind/RebindCatalogEntityTest.java  |  157 --
 .../entity/rebind/RebindCatalogItemTest.java    |  260 ---
 ...talogWhenCatalogPersistenceDisabledTest.java |   95 -
 .../entity/rebind/RebindDynamicGroupTest.java   |   69 -
 .../entity/rebind/RebindEnricherTest.java       |  326 ----
 .../rebind/RebindEntityDynamicTypeInfoTest.java |  123 --
 .../entity/rebind/RebindEntityTest.java         |  955 ----------
 .../entity/rebind/RebindFailuresTest.java       |  294 ---
 .../brooklyn/entity/rebind/RebindFeedTest.java  |  405 ----
 .../entity/rebind/RebindFeedWithHaTest.java     |  131 --
 .../brooklyn/entity/rebind/RebindGroupTest.java |  124 --
 .../rebind/RebindLocalhostLocationTest.java     |  104 --
 .../entity/rebind/RebindLocationTest.java       |  390 ----
 .../entity/rebind/RebindManagerSorterTest.java  |  149 --
 .../entity/rebind/RebindManagerTest.java        |   62 -
 .../brooklyn/entity/rebind/RebindOptions.java   |   94 -
 .../entity/rebind/RebindPolicyTest.java         |  341 ----
 .../rebind/RebindSshMachineLocationTest.java    |   84 -
 .../entity/rebind/RebindTestFixture.java        |  327 ----
 .../entity/rebind/RebindTestFixtureWithApp.java |   33 -
 .../brooklyn/entity/rebind/RebindTestUtils.java |  481 -----
 .../rebind/RecordingRebindExceptionHandler.java |   91 -
 .../BrooklynMementoPersisterFileBasedTest.java  |   55 -
 ...ntoPersisterInMemorySizeIntegrationTest.java |  107 --
 .../BrooklynMementoPersisterInMemoryTest.java   |   34 -
 .../BrooklynMementoPersisterTestFixture.java    |  166 --
 .../persister/FileBasedObjectStoreTest.java     |  100 -
 .../FileBasedStoreObjectAccessorWriterTest.java |   64 -
 .../rebind/persister/InMemoryObjectStore.java   |  167 --
 .../InMemoryStoreObjectAccessorWriterTest.java  |   36 -
 .../rebind/persister/ListeningObjectStore.java  |  252 ---
 ...nceStoreObjectAccessorWriterTestFixture.java |  137 --
 .../persister/XmlMementoSerializerTest.java     |  456 -----
 .../CompoundTransformerLoaderTest.java          |   77 -
 .../transformer/CompoundTransformerTest.java    |  481 -----
 .../transformer/impl/XsltTransformerTest.java   |  167 --
 .../brooklyn/entity/trait/FailingEntity.java    |   85 -
 .../entity/trait/FailingEntityImpl.java         |   88 -
 .../entity/trait/StartableMethodsTest.java      |  128 --
 .../event/feed/ConfigToAttributesTest.java      |   70 -
 .../java/brooklyn/event/feed/PollerTest.java    |  107 --
 .../event/feed/function/FunctionFeedTest.java   |  314 ----
 .../feed/http/HttpFeedIntegrationTest.java      |  160 --
 .../brooklyn/event/feed/http/HttpFeedTest.java  |  390 ----
 .../event/feed/http/HttpValueFunctionsTest.java |   93 -
 .../event/feed/http/JsonFunctionsTest.java      |  129 --
 .../feed/shell/ShellFeedIntegrationTest.java    |  225 ---
 .../event/feed/ssh/SshFeedIntegrationTest.java  |  261 ---
 .../WindowsPerformanceCounterFeedLiveTest.java  |  104 --
 .../WindowsPerformanceCounterFeedTest.java      |  132 --
 .../longevity/EntityCleanupLongevityTest.java   |   61 -
 .../EntityCleanupLongevityTestFixture.java      |  176 --
 .../qa/longevity/EntityCleanupTest.java         |   58 -
 .../qa/performance/AbstractPerformanceTest.java |  138 --
 .../EntityPerformanceLongevityTest.java         |   35 -
 .../qa/performance/EntityPerformanceTest.java   |  145 --
 .../EntityPersistencePerformanceTest.java       |  102 -
 .../FilePersistencePerformanceTest.java         |  187 --
 .../GroovyYardStickPerformanceTest.groovy       |   62 -
 .../JavaYardStickPerformanceTest.java           |   81 -
 .../SubscriptionPerformanceTest.java            |  167 --
 .../qa/performance/TaskPerformanceTest.java     |  181 --
 .../test/java/brooklyn/test/HttpService.java    |  216 ---
 .../brooklyn/test/TestHttpRequestHandler.java   |   72 -
 .../test/java/brooklyn/test/TestHttpServer.java |  143 --
 .../test/location/TestPaasLocation.java         |   32 -
 .../java/brooklyn/test/policy/TestEnricher.java |   63 -
 .../java/brooklyn/test/policy/TestPolicy.java   |   62 -
 .../brooklyn/core/BrooklynVersionTest.java      |  124 ++
 .../core/catalog/internal/CatalogDtoTest.java   |   13 +-
 .../core/catalog/internal/CatalogLoadTest.java  |    2 +-
 .../core/catalog/internal/CatalogScanTest.java  |   13 +-
 .../core/catalog/internal/CatalogTestUtils.java |    6 +-
 .../catalog/internal/CatalogVersioningTest.java |    7 +-
 .../core/catalog/internal/MyCatalogItems.java   |    5 +-
 .../config/BrooklynPropertiesBuilderTest.java   |    2 +-
 .../BrooklynPropertiesFromGroovyTest.groovy     |    2 +-
 .../core/config/BrooklynPropertiesTest.java     |    4 +-
 .../brooklyn/core/config/ConfigKeysTest.java    |   87 +
 .../brooklyn/core/config/ConfigUtilsTest.java   |    2 -
 .../config/MapConfigKeyAndFriendsMoreTest.java  |  271 +++
 ...apListAndOtherStructuredConfigKeyTest.groovy |  357 ++++
 .../internal/BrooklynFeatureEnablementTest.java |    1 -
 .../entitlement/AcmeEntitlementManager.java     |   52 -
 .../entitlement/AcmeEntitlementManagerTest.java |   60 -
 .../AcmeEntitlementManagerTestFixture.java      |  158 --
 .../entitlement/EntitlementsTest.java           |  208 ---
 .../entitlement/EntityEntitlementTest.java      |  185 --
 ...PerUserEntitlementManagerPropertiesTest.java |   52 -
 .../HighAvailabilityManagerFileBasedTest.java   |   47 -
 ...ilabilityManagerInMemoryIntegrationTest.java |   96 -
 .../ha/HighAvailabilityManagerInMemoryTest.java |  144 --
 .../HighAvailabilityManagerSplitBrainTest.java  |  474 -----
 .../ha/HighAvailabilityManagerTestFixture.java  |  287 ---
 .../core/management/ha/HotStandbyTest.java      |  666 -------
 .../ha/ImmutableManagementPlaneSyncRecord.java  |   57 -
 ...agementPlaneSyncRecordPersisterInMemory.java |  100 -
 .../core/management/ha/MasterChooserTest.java   |  146 --
 .../ha/MutableManagementPlaneSyncRecord.java    |   62 -
 .../management/ha/TestEntityFailingRebind.java  |   55 -
 .../core/management/ha/WarmStandbyTest.java     |  155 --
 .../management/internal/AccessManagerTest.java  |  145 --
 .../internal/EntityExecutionManagerTest.java    |  478 -----
 .../LocalManagementContextInstancesTest.java    |   87 -
 .../internal/LocalManagementContextTest.java    |  126 --
 .../internal/LocalSubscriptionManagerTest.java  |  181 --
 .../core/management/osgi/OsgiPathTest.java      |  105 --
 .../management/osgi/OsgiStandaloneTest.java     |  256 ---
 .../core/management/osgi/OsgiTestResources.java |   74 -
 .../osgi/OsgiVersionMoreEntityTest.java         |  458 -----
 .../entitlement/AcmeEntitlementManager.java     |   52 +
 .../entitlement/AcmeEntitlementManagerTest.java |   60 +
 .../AcmeEntitlementManagerTestFixture.java      |  157 ++
 .../core/mgmt/entitlement/EntitlementsTest.java |  207 +++
 .../mgmt/entitlement/EntityEntitlementTest.java |  184 ++
 ...PerUserEntitlementManagerPropertiesTest.java |   52 +
 .../HighAvailabilityManagerFileBasedTest.java   |   46 +
 ...ilabilityManagerInMemoryIntegrationTest.java |   95 +
 .../ha/HighAvailabilityManagerInMemoryTest.java |  142 ++
 .../HighAvailabilityManagerSplitBrainTest.java  |  473 +++++
 .../ha/HighAvailabilityManagerTestFixture.java  |  286 +++
 .../brooklyn/core/mgmt/ha/HotStandbyTest.java   |  664 +++++++
 .../ha/ImmutableManagementPlaneSyncRecord.java  |   57 +
 ...agementPlaneSyncRecordPersisterInMemory.java |   99 +
 .../core/mgmt/ha/MasterChooserTest.java         |  145 ++
 .../ha/MutableManagementPlaneSyncRecord.java    |   62 +
 .../core/mgmt/ha/TestEntityFailingRebind.java   |   55 +
 .../brooklyn/core/mgmt/ha/WarmStandbyTest.java  |  154 ++
 .../core/mgmt/internal/AccessManagerTest.java   |  143 ++
 .../internal/BrooklynShutdownHooksTest.java     |   91 +
 .../internal/EntityExecutionManagerTest.java    |  477 +++++
 .../LocalManagementContextInstancesTest.java    |   87 +
 .../internal/LocalManagementContextTest.java    |  126 ++
 .../internal/LocalSubscriptionManagerTest.java  |  180 ++
 .../brooklyn/core/mgmt/osgi/OsgiPathTest.java   |  104 ++
 .../core/mgmt/osgi/OsgiStandaloneTest.java      |  256 +++
 .../core/mgmt/osgi/OsgiTestResources.java       |   74 +
 .../mgmt/osgi/OsgiVersionMoreEntityTest.java    |  456 +++++
 .../BrooklynMementoPersisterFileBasedTest.java  |   55 +
 ...ntoPersisterInMemorySizeIntegrationTest.java |  106 ++
 .../BrooklynMementoPersisterInMemoryTest.java   |   33 +
 .../BrooklynMementoPersisterTestFixture.java    |  165 ++
 .../mgmt/persist/FileBasedObjectStoreTest.java  |  101 +
 .../FileBasedStoreObjectAccessorWriterTest.java |   65 +
 .../core/mgmt/persist/InMemoryObjectStore.java  |  170 ++
 .../InMemoryStoreObjectAccessorWriterTest.java  |   36 +
 .../core/mgmt/persist/ListeningObjectStore.java |  254 +++
 ...nceStoreObjectAccessorWriterTestFixture.java |  136 ++
 .../mgmt/persist/XmlMementoSerializerTest.java  |  455 +++++
 .../mgmt/rebind/ActivePartialRebindTest.java    |  108 ++
 .../rebind/ActivePartialRebindVersionTest.java  |  119 ++
 .../core/mgmt/rebind/CheckpointEntityTest.java  |  109 ++
 .../brooklyn/core/mgmt/rebind/Dumpers.java      |  273 +++
 .../mgmt/rebind/RebindCatalogEntityTest.java    |  155 ++
 .../core/mgmt/rebind/RebindCatalogItemTest.java |  260 +++
 ...talogWhenCatalogPersistenceDisabledTest.java |   95 +
 .../mgmt/rebind/RebindDynamicGroupTest.java     |   68 +
 .../core/mgmt/rebind/RebindEnricherTest.java    |  324 ++++
 .../rebind/RebindEntityDynamicTypeInfoTest.java |  122 ++
 .../core/mgmt/rebind/RebindEntityTest.java      |  954 ++++++++++
 .../core/mgmt/rebind/RebindFailuresTest.java    |  293 +++
 .../core/mgmt/rebind/RebindFeedTest.java        |  403 ++++
 .../core/mgmt/rebind/RebindFeedWithHaTest.java  |  131 ++
 .../core/mgmt/rebind/RebindGroupTest.java       |  123 ++
 .../rebind/RebindLocalhostLocationTest.java     |  104 ++
 .../core/mgmt/rebind/RebindLocationTest.java    |  389 ++++
 .../mgmt/rebind/RebindManagerSorterTest.java    |  147 ++
 .../core/mgmt/rebind/RebindManagerTest.java     |   62 +
 .../core/mgmt/rebind/RebindOptions.java         |   93 +
 .../core/mgmt/rebind/RebindPolicyTest.java      |  339 ++++
 .../rebind/RebindSshMachineLocationTest.java    |   84 +
 .../core/mgmt/rebind/RebindTestFixture.java     |  326 ++++
 .../mgmt/rebind/RebindTestFixtureWithApp.java   |   32 +
 .../core/mgmt/rebind/RebindTestUtils.java       |  483 +++++
 .../rebind/RecordingRebindExceptionHandler.java |   92 +
 .../CompoundTransformerLoaderTest.java          |   79 +
 .../transformer/CompoundTransformerTest.java    |  481 +++++
 .../transformer/impl/XsltTransformerTest.java   |  170 ++
 .../core/policy/basic/BasicPolicyTest.java      |    9 +-
 .../core/policy/basic/EnricherTypeTest.java     |    7 +-
 .../core/policy/basic/PolicyConfigTest.java     |    9 +-
 .../policy/basic/PolicySubscriptionTest.java    |   22 +-
 .../core/policy/basic/PolicyTypeTest.java       |    5 +-
 .../core/server/entity/BrooklynMetricsTest.java |  127 ++
 .../core/test/BrooklynAppLiveTestSupport.java   |   66 +
 .../core/test/BrooklynAppUnitTestSupport.java   |   74 +
 .../apache/brooklyn/core/test/HttpService.java  |  216 +++
 .../core/test/TestHttpRequestHandler.java       |   72 +
 .../brooklyn/core/test/TestHttpServer.java      |  143 ++
 .../lite/CampPlatformWithJustBrooklynMgmt.java  |    6 +-
 .../camp/brooklyn/lite/CampYamlLiteTest.java    |   29 +-
 .../camp/brooklyn/lite/TestAppAssembly.java     |    2 +-
 .../lite/TestAppAssemblyInstantiator.java       |   12 +-
 .../core/test/entity/BlockingEntity.java        |   45 +
 .../core/test/entity/BlockingEntityImpl.java    |   59 +
 .../entity/LocalManagementContextForTests.java  |  157 ++
 .../core/test/entity/NoopStartable.java         |   29 +
 .../core/test/entity/TestApplication.java       |   59 +
 .../core/test/entity/TestApplicationImpl.java   |   97 +
 .../entity/TestApplicationNoEnrichersImpl.java  |   29 +
 .../brooklyn/core/test/entity/TestCluster.java  |   30 +
 .../core/test/entity/TestClusterImpl.java       |   65 +
 .../brooklyn/core/test/entity/TestEntity.java   |  112 ++
 .../core/test/entity/TestEntityImpl.java        |  185 ++
 .../test/entity/TestEntityNoEnrichersImpl.java  |   32 +
 .../entity/TestEntityTransientCopyImpl.java     |   28 +
 .../core/test/location/TestPaasLocation.java    |   32 +
 .../brooklyn/core/test/policy/TestEnricher.java |   62 +
 .../brooklyn/core/test/policy/TestPolicy.java   |   61 +
 .../longevity/EntityCleanupLongevityTest.java   |   61 +
 .../EntityCleanupLongevityTestFixture.java      |  174 ++
 .../test/qa/longevity/EntityCleanupTest.java    |   58 +
 .../qa/performance/AbstractPerformanceTest.java |  136 ++
 .../EntityPerformanceLongevityTest.java         |   35 +
 .../qa/performance/EntityPerformanceTest.java   |  144 ++
 .../EntityPersistencePerformanceTest.java       |   99 +
 .../FilePersistencePerformanceTest.java         |  186 ++
 .../GroovyYardStickPerformanceTest.groovy       |   62 +
 .../JavaYardStickPerformanceTest.java           |   81 +
 .../SubscriptionPerformanceTest.java            |  167 ++
 .../qa/performance/TaskPerformanceTest.java     |  181 ++
 .../core/util/BrooklynMavenArtifactsTest.java   |   97 -
 .../core/util/ResourceUtilsHttpTest.java        |  197 --
 .../brooklyn/core/util/ResourceUtilsTest.java   |  189 --
 .../core/util/config/ConfigBagTest.java         |  193 --
 .../util/crypto/SecureKeysAndSignerTest.java    |  168 --
 .../core/util/file/ArchiveBuilderTest.java      |  193 --
 .../core/util/file/ArchiveUtilsTest.java        |  138 --
 .../core/util/flags/MethodCoercionsTest.java    |  148 --
 .../core/util/http/BetterMockWebServer.java     |  138 --
 .../core/util/http/HttpToolIntegrationTest.java |  100 -
 .../core/util/internal/FlagUtilsTest.java       |  314 ----
 .../core/util/internal/RepeaterTest.groovy      |  257 ---
 .../core/util/internal/TypeCoercionsTest.java   |  360 ----
 .../util/internal/ssh/RecordingSshTool.java     |   97 -
 .../internal/ssh/ShellToolAbstractTest.java     |  440 -----
 .../ssh/SshToolAbstractIntegrationTest.java     |  303 ---
 .../ssh/SshToolAbstractPerformanceTest.java     |  137 --
 .../ssh/cli/SshCliToolIntegrationTest.java      |  118 --
 .../ssh/cli/SshCliToolPerformanceTest.java      |   44 -
 .../ssh/process/ProcessToolIntegrationTest.java |   69 -
 .../ssh/process/ProcessToolStaticsTest.java     |   79 -
 .../sshj/SshjToolAsyncStubIntegrationTest.java  |  177 --
 .../ssh/sshj/SshjToolIntegrationTest.java       |  313 ----
 .../ssh/sshj/SshjToolPerformanceTest.java       |   44 -
 .../core/util/mutex/WithMutexesTest.java        |  129 --
 .../brooklyn/core/util/osgi/OsgisTest.java      |   41 -
 .../util/ssh/BashCommandsIntegrationTest.java   |  503 -----
 .../task/BasicTaskExecutionPerformanceTest.java |  208 ---
 .../core/util/task/BasicTaskExecutionTest.java  |  461 -----
 .../core/util/task/BasicTasksFutureTest.java    |  226 ---
 .../util/task/CompoundTaskExecutionTest.java    |  257 ---
 .../util/task/DynamicSequentialTaskTest.java    |  370 ----
 .../util/task/NonBasicTaskExecutionTest.java    |  129 --
 .../core/util/task/ScheduledExecutionTest.java  |  290 ---
 .../util/task/SingleThreadedSchedulerTest.java  |  194 --
 .../core/util/task/TaskFinalizationTest.java    |   62 -
 .../brooklyn/core/util/task/TasksTest.java      |  184 --
 .../core/util/task/ValueResolverTest.java       |  134 --
 .../core/util/task/ssh/SshTasksTest.java        |  212 ---
 .../core/util/task/system/SystemTasksTest.java  |  137 --
 .../core/util/text/DataUriSchemeParserTest.java |   53 -
 .../core/util/text/TemplateProcessorTest.java   |  180 --
 .../util/xstream/CompilerCompatibilityTest.java |  158 --
 .../core/util/xstream/ConverterTestFixture.java |   40 -
 .../xstream/EnumCaseForgivingConverterTest.java |   53 -
 .../xstream/ImmutableListConverterTest.java     |   60 -
 .../util/xstream/InetAddressConverterTest.java  |   42 -
 .../util/xstream/StringKeyMapConverterTest.java |   77 -
 .../brooklyn/core/util/xstream/XmlUtilTest.java |   34 -
 .../effector/core/EffectorBasicTest.java        |  183 ++
 .../effector/core/EffectorConcatenateTest.java  |  241 +++
 .../effector/core/EffectorMetadataTest.java     |  166 ++
 .../core/EffectorSayHiGroovyTest.groovy         |  179 ++
 .../effector/core/EffectorSayHiTest.java        |  173 ++
 .../effector/core/EffectorTaskTest.java         |  437 +++++
 .../basic/RecordingSensorEventListener.java     |  115 --
 .../core/AbstractApplicationLegacyTest.java     |  156 ++
 .../entity/core/AbstractEntityLegacyTest.java   |  131 ++
 .../brooklyn/entity/core/AttributeMapTest.java  |  226 +++
 .../brooklyn/entity/core/AttributeTest.java     |   66 +
 .../core/ConfigEntityInheritanceTest.java       |  190 ++
 .../entity/core/DependentConfigurationTest.java |  413 +++++
 .../brooklyn/entity/core/DynamicEntityTest.java |   60 +
 .../brooklyn/entity/core/EntitiesTest.java      |  134 ++
 .../brooklyn/entity/core/EntityConfigTest.java  |  178 ++
 .../entity/core/EntityFunctionsTest.java        |   77 +
 .../entity/core/EntityLocationsTest.java        |  126 ++
 .../entity/core/EntityPreManagementTest.java    |  146 ++
 .../entity/core/EntityPredicatesTest.java       |  129 ++
 .../entity/core/EntityRegistrationTest.java     |  102 +
 .../entity/core/EntitySetFromFlagTest.java      |  213 +++
 .../brooklyn/entity/core/EntitySpecTest.java    |  214 +++
 .../entity/core/EntitySubscriptionTest.java     |  242 +++
 .../entity/core/EntitySuppliersTest.java        |   70 +
 .../brooklyn/entity/core/EntityTypeTest.java    |  284 +++
 .../brooklyn/entity/core/OwnedChildrenTest.java |  213 +++
 .../entity/core/PolicyRegistrationTest.java     |  152 ++
 .../core/RecordingSensorEventListener.java      |  115 ++
 .../brooklyn/entity/core/SanitizerTest.java     |   38 +
 .../core/internal/ConfigMapGroovyTest.groovy    |   61 +
 .../entity/core/internal/ConfigMapTest.java     |  298 +++
 .../EntityConfigMapUsageLegacyTest.java         |  292 +++
 .../core/internal/EntityConfigMapUsageTest.java |  318 ++++
 .../drivers/BasicEntityDriverManagerTest.java   |   74 +
 .../drivers/EntityDriverRegistryTest.java       |   59 +
 .../ReflectiveEntityDriverFactoryTest.java      |  169 ++
 .../RegistryEntityDriverFactoryTest.java        |   86 +
 .../downloads/BasicDownloadsRegistryTest.java   |  155 ++
 .../DownloadProducerFromLocalRepoTest.java      |  130 ++
 .../DownloadProducerFromPropertiesTest.java     |  162 ++
 .../downloads/DownloadSubstitutersTest.java     |  131 ++
 .../downloads/FilenameProducersTest.java        |   34 +
 .../drivers/downloads/MyEntityDriver.java       |   44 +
 .../entity/group/DynamicClusterTest.java        |  984 ++++++++++
 ...DynamicClusterWithAvailabilityZonesTest.java |  225 +++
 .../entity/group/DynamicFabricTest.java         |  496 +++++
 .../brooklyn/entity/group/DynamicGroupTest.java |  550 ++++++
 .../entity/group/DynamicMultiGroupTest.java     |  223 +++
 .../entity/group/DynamicRegionsFabricTest.java  |  170 ++
 .../entity/group/GroupPickUpEntitiesTest.java   |  157 ++
 .../apache/brooklyn/entity/group/GroupTest.java |  144 ++
 .../group/MembershipTrackingPolicyTest.java     |  313 ++++
 .../entity/group/QuarantineGroupTest.java       |   85 +
 .../BalancingNodePlacementStrategyTest.java     |  116 ++
 .../ProportionalZoneFailureDetectorTest.java    |  123 ++
 .../brooklyn/entity/hello/HelloEntity.java      |   53 +
 .../brooklyn/entity/hello/HelloEntityImpl.java  |   31 +
 .../entity/hello/LocalEntitiesTest.java         |  282 +++
 .../lifecycle/LifecycleTransitionTest.java      |   51 +
 .../entity/lifecycle/ServiceStateLogicTest.java |  314 ++++
 .../ApplicationBuilderOverridingTest.java       |  221 +++
 .../proxying/BasicEntityTypeRegistryTest.java   |  135 ++
 .../entity/proxying/EntityManagerTest.java      |   83 +
 .../entity/proxying/EntityProxyTest.java        |  171 ++
 .../proxying/InternalEntityFactoryTest.java     |  109 ++
 .../entity/stock/BasicStartableTest.java        |  178 ++
 .../brooklyn/entity/stock/DataEntityTest.java   |  142 ++
 .../brooklyn/entity/trait/FailingEntity.java    |   84 +
 .../entity/trait/FailingEntityImpl.java         |   87 +
 .../entity/trait/StartableMethodsTest.java      |  127 ++
 .../access/BrooklynAccessUtilsTest.java         |   13 +-
 .../PortForwardManagerLocationResolverTest.java |    7 +-
 .../access/PortForwardManagerRebindTest.java    |   30 +-
 .../location/access/PortForwardManagerTest.java |   12 +-
 .../location/basic/AbstractLocationTest.java    |  184 --
 ...regatingMachineProvisioningLocationTest.java |  117 --
 .../basic/ByonLocationResolverTest.java         |  423 -----
 ...stMachineProvisioningLocationRebindTest.java |  129 --
 ...ixedListMachineProvisioningLocationTest.java |  575 ------
 .../basic/HostLocationResolverTest.java         |  126 --
 .../basic/LegacyAbstractLocationTest.java       |  150 --
 .../basic/LocalhostLocationResolverTest.java    |  265 ---
 ...ocalhostMachineProvisioningLocationTest.java |  214 ---
 .../LocalhostProvisioningAndAccessTest.java     |   58 -
 .../location/basic/LocationConfigTest.java      |  203 --
 .../location/basic/LocationConfigUtilsTest.java |  154 --
 .../location/basic/LocationExtensionsTest.java  |  186 --
 .../location/basic/LocationManagementTest.java  |   81 -
 .../location/basic/LocationPredicatesTest.java  |   99 -
 ...ionPropertiesFromBrooklynPropertiesTest.java |  121 --
 .../location/basic/LocationRegistryTest.java    |  159 --
 .../location/basic/MachineDetailsTest.java      |   81 -
 .../location/basic/MultiLocationRebindTest.java |  120 --
 .../basic/MultiLocationResolverTest.java        |  199 --
 .../location/basic/MultiLocationTest.java       |  120 --
 .../location/basic/PaasLocationTest.java        |   35 -
 .../brooklyn/location/basic/PortRangesTest.java |  129 --
 .../RecordingMachineLocationCustomizer.java     |   71 -
 .../location/basic/SimulatedLocation.java       |  136 --
 .../SingleMachineLocationResolverTest.java      |  131 --
 .../SingleMachineProvisioningLocationTest.java  |   63 -
 .../SshMachineLocationIntegrationTest.java      |  140 --
 .../SshMachineLocationPerformanceTest.java      |  171 --
 .../SshMachineLocationReuseIntegrationTest.java |  173 --
 .../location/basic/SshMachineLocationTest.java  |  340 ----
 .../basic/TestPortSupplierLocation.java         |   90 -
 .../location/byon/ByonLocationResolverTest.java |  429 +++++
 ...stMachineProvisioningLocationRebindTest.java |  131 ++
 ...ixedListMachineProvisioningLocationTest.java |  578 ++++++
 .../location/byon/HostLocationResolverTest.java |  126 ++
 .../byon/SingleMachineLocationResolverTest.java |  132 ++
 .../SingleMachineProvisioningLocationTest.java  |   65 +
 .../location/cloud/CloudMachineNamerTest.java   |   16 +-
 .../location/cloud/CustomMachineNamerTest.java  |   16 +-
 .../location/core/AbstractLocationTest.java     |  185 ++
 ...regatingMachineProvisioningLocationTest.java |  117 ++
 .../core/LegacyAbstractLocationTest.java        |  151 ++
 .../location/core/LocationConfigTest.java       |  204 ++
 .../location/core/LocationConfigUtilsTest.java  |  156 ++
 .../location/core/LocationExtensionsTest.java   |  187 ++
 .../location/core/LocationManagementTest.java   |   82 +
 .../location/core/LocationPredicatesTest.java   |  102 +
 ...ionPropertiesFromBrooklynPropertiesTest.java |  122 ++
 .../location/core/LocationRegistryTest.java     |  161 ++
 .../location/core/MachineDetailsTest.java       |   83 +
 .../location/core/MultiLocationRebindTest.java  |  122 ++
 .../core/MultiLocationResolverTest.java         |  203 ++
 .../location/core/MultiLocationTest.java        |  121 ++
 .../location/core/PaasLocationTest.java         |   35 +
 .../brooklyn/location/core/PortRangesTest.java  |  130 ++
 .../RecordingMachineLocationCustomizer.java     |   71 +
 .../location/core/SimulatedLocation.java        |  141 ++
 .../location/core/TestPortSupplierLocation.java |   90 +
 .../LocalhostLocationResolverTest.java          |  269 +++
 ...ocalhostMachineProvisioningLocationTest.java |  215 +++
 .../LocalhostProvisioningAndAccessTest.java     |   59 +
 .../brooklyn/location/geo/HostGeoInfoTest.java  |    2 +-
 .../geo/HostGeoLookupIntegrationTest.java       |    4 +-
 .../ssh/SshMachineLocationIntegrationTest.java  |  141 ++
 .../ssh/SshMachineLocationPerformanceTest.java  |  172 ++
 .../SshMachineLocationReuseIntegrationTest.java |  172 ++
 .../location/ssh/SshMachineLocationTest.java    |  345 ++++
 .../winrm/AdvertiseWinrmLoginPolicyTest.java    |   51 +
 .../winrm/WinRmMachineLocationTest.java         |   44 +
 .../sensor/core/HttpRequestSensorTest.java      |   85 +
 .../brooklyn/sensor/core/StaticSensorTest.java  |   55 +
 .../sensor/enricher/BasicEnricherTest.java      |  119 ++
 ...stomAggregatingEnricherDeprecatedTest.groovy |  367 ++++
 .../enricher/CustomAggregatingEnricherTest.java |  556 ++++++
 .../sensor/enricher/EnricherConfigTest.java     |  147 ++
 .../brooklyn/sensor/enricher/EnrichersTest.java |  501 +++++
 ...SensorPropagatingEnricherDeprecatedTest.java |  108 ++
 .../enricher/SensorPropagatingEnricherTest.java |  218 +++
 .../TransformingEnricherDeprecatedTest.groovy   |   82 +
 .../enricher/TransformingEnricherTest.java      |   71 +
 .../YamlRollingTimeWindowMeanEnricherTest.java  |  179 ++
 .../YamlTimeWeightedDeltaEnricherTest.java      |  107 ++
 .../sensor/feed/ConfigToAttributesTest.java     |   70 +
 .../apache/brooklyn/sensor/feed/PollerTest.java |  108 ++
 .../sensor/feed/function/FunctionFeedTest.java  |  315 ++++
 .../feed/http/HttpFeedIntegrationTest.java      |  160 ++
 .../brooklyn/sensor/feed/http/HttpFeedTest.java |  392 ++++
 .../feed/http/HttpValueFunctionsTest.java       |   94 +
 .../sensor/feed/http/JsonFunctionsTest.java     |  130 ++
 .../feed/shell/ShellFeedIntegrationTest.java    |  226 +++
 .../sensor/feed/ssh/SshFeedIntegrationTest.java |  264 +++
 .../WindowsPerformanceCounterFeedLiveTest.java  |  104 ++
 .../WindowsPerformanceCounterFeedTest.java      |  132 ++
 .../brooklyn/test/entity/BlockingEntity.java    |   46 -
 .../test/entity/BlockingEntityImpl.java         |   59 -
 .../entity/LocalManagementContextForTests.java  |  157 --
 .../brooklyn/test/entity/NoopStartable.java     |   29 -
 .../brooklyn/test/entity/TestApplication.java   |   60 -
 .../test/entity/TestApplicationImpl.java        |   99 -
 .../entity/TestApplicationNoEnrichersImpl.java  |   29 -
 .../brooklyn/test/entity/TestCluster.java       |   31 -
 .../brooklyn/test/entity/TestClusterImpl.java   |   65 -
 .../apache/brooklyn/test/entity/TestEntity.java |  113 --
 .../brooklyn/test/entity/TestEntityImpl.java    |  186 --
 .../test/entity/TestEntityNoEnrichersImpl.java  |   32 -
 .../entity/TestEntityTransientCopyImpl.java     |   28 -
 .../util/core/BrooklynMavenArtifactsTest.java   |   97 +
 .../util/core/ResourceUtilsHttpTest.java        |  196 ++
 .../brooklyn/util/core/ResourceUtilsTest.java   |  189 ++
 .../util/core/config/ConfigBagTest.java         |  192 ++
 .../core/crypto/SecureKeysAndSignerTest.java    |  168 ++
 .../util/core/file/ArchiveBuilderTest.java      |  193 ++
 .../util/core/file/ArchiveUtilsTest.java        |  136 ++
 .../util/core/flags/MethodCoercionsTest.java    |  148 ++
 .../util/core/http/BetterMockWebServer.java     |  138 ++
 .../util/core/http/HttpToolIntegrationTest.java |   99 +
 .../util/core/internal/FlagUtilsTest.java       |  313 ++++
 .../util/core/internal/RepeaterTest.groovy      |  256 +++
 .../util/core/internal/TypeCoercionsTest.java   |  359 ++++
 .../core/internal/ssh/RecordingSshTool.java     |   97 +
 .../internal/ssh/ShellToolAbstractTest.java     |  440 +++++
 .../ssh/SshToolAbstractIntegrationTest.java     |  303 +++
 .../ssh/SshToolAbstractPerformanceTest.java     |  137 ++
 .../ssh/cli/SshCliToolIntegrationTest.java      |  118 ++
 .../ssh/cli/SshCliToolPerformanceTest.java      |   44 +
 .../ssh/process/ProcessToolIntegrationTest.java |   69 +
 .../ssh/process/ProcessToolStaticsTest.java     |   79 +
 .../sshj/SshjToolAsyncStubIntegrationTest.java  |  177 ++
 .../ssh/sshj/SshjToolIntegrationTest.java       |  313 ++++
 .../ssh/sshj/SshjToolPerformanceTest.java       |   44 +
 .../util/core/mutex/WithMutexesTest.java        |  129 ++
 .../brooklyn/util/core/osgi/OsgisTest.java      |   41 +
 .../core/ssh/BashCommandsIntegrationTest.java   |  501 +++++
 .../task/BasicTaskExecutionPerformanceTest.java |  208 +++
 .../util/core/task/BasicTaskExecutionTest.java  |  461 +++++
 .../util/core/task/BasicTasksFutureTest.java    |  226 +++
 .../core/task/CompoundTaskExecutionTest.java    |  257 +++
 .../core/task/DynamicSequentialTaskTest.java    |  370 ++++
 .../core/task/NonBasicTaskExecutionTest.java    |  129 ++
 .../util/core/task/ScheduledExecutionTest.java  |  290 +++
 .../core/task/SingleThreadedSchedulerTest.java  |  194 ++
 .../util/core/task/TaskFinalizationTest.java    |   62 +
 .../brooklyn/util/core/task/TasksTest.java      |  183 ++
 .../util/core/task/ValueResolverTest.java       |  133 ++
 .../util/core/task/ssh/SshTasksTest.java        |  210 +++
 .../util/core/task/system/SystemTasksTest.java  |  136 ++
 .../util/core/text/DataUriSchemeParserTest.java |   53 +
 .../util/core/text/TemplateProcessorTest.java   |  179 ++
 .../core/xstream/CompilerCompatibilityTest.java |  158 ++
 .../util/core/xstream/ConverterTestFixture.java |   40 +
 .../xstream/EnumCaseForgivingConverterTest.java |   53 +
 .../xstream/ImmutableListConverterTest.java     |   60 +
 .../core/xstream/InetAddressConverterTest.java  |   42 +
 .../core/xstream/StringKeyMapConverterTest.java |   77 +
 .../brooklyn/util/core/xstream/XmlUtilTest.java |   34 +
 .../rebind/compiler_compatibility_eclipse.xml   |   41 -
 .../rebind/compiler_compatibility_oracle.xml    |   41 -
 .../rebind/compiler_compatibility_eclipse.xml   |   41 +
 .../rebind/compiler_compatibility_oracle.xml    |   41 +
 .../brooklyn/demo/GlobalWebFabricExample.java   |   22 +-
 .../brooklyn/demo/KafkaClusterExample.java      |    7 +-
 .../demo/StandaloneQpidBrokerExample.java       |    9 +-
 .../brooklyn/demo/CumulusRDFApplication.java    |   50 +-
 .../demo/HighAvailabilityCassandraCluster.java  |   14 +-
 .../brooklyn/demo/ResilientMongoDbApp.java      |   20 +-
 .../brooklyn/demo/RiakClusterExample.java       |   14 +-
 .../brooklyn/demo/SimpleCassandraCluster.java   |   10 +-
 .../brooklyn/demo/SimpleCouchDBCluster.java     |    5 +-
 .../brooklyn/demo/SimpleMongoDBReplicaSet.java  |    5 +-
 .../brooklyn/demo/SimpleRedisCluster.java       |    5 +-
 .../apache/brooklyn/demo/StormSampleApp.java    |   10 +-
 .../brooklyn/demo/WideAreaCassandraCluster.java |   14 +-
 .../brooklyn/demo/NodeJsTodoApplication.java    |   17 +-
 .../brooklyn/demo/SingleWebServerExample.java   |   14 +-
 .../demo/WebClusterDatabaseExample.java         |   28 +-
 .../demo/WebClusterDatabaseExampleApp.java      |   36 +-
 .../demo/WebClusterDatabaseExampleGroovy.groovy |   22 +-
 .../apache/brooklyn/demo/WebClusterExample.java |   10 +-
 ...lusterDatabaseExampleAppIntegrationTest.java |   24 +-
 .../JcloudsBlobStoreBasedObjectStore.java       |  239 ---
 .../jclouds/JcloudsStoreObjectAccessor.java     |  128 --
 .../policy/os/AdvertiseWinrmLoginPolicy.java    |   83 -
 .../brooklyn/policy/os/CreateUserPolicy.java    |  175 --
 .../JcloudsBlobStoreBasedObjectStore.java       |  237 +++
 .../jclouds/JcloudsStoreObjectAccessor.java     |  127 ++
 ...AbstractJcloudsSubnetSshMachineLocation.java |    3 +-
 .../location/jclouds/BrooklynMachinePool.java   |   10 +-
 .../jclouds/ComputeServiceRegistry.java         |    2 +-
 .../jclouds/ComputeServiceRegistryImpl.java     |    5 +-
 .../jclouds/JcloudsByonLocationResolver.java    |   17 +-
 .../location/jclouds/JcloudsLocation.java       |   43 +-
 .../location/jclouds/JcloudsLocationConfig.java |   12 +-
 .../jclouds/JcloudsLocationCustomizer.java      |    2 +-
 .../jclouds/JcloudsLocationResolver.java        |   10 +-
 .../jclouds/JcloudsMachineLocation.java         |    2 +-
 .../location/jclouds/JcloudsMachineNamer.java   |    2 +-
 ...JcloudsPropertiesFromBrooklynProperties.java |    8 +-
 .../jclouds/JcloudsSshMachineLocation.java      |   10 +-
 .../brooklyn/location/jclouds/JcloudsUtil.java  |    5 +-
 .../jclouds/JcloudsWinRmMachineLocation.java    |    4 +-
 .../jclouds/SudoTtyFixingCustomizer.java        |    8 +-
 .../JcloudsLocationSecurityGroupCustomizer.java |    2 +-
 .../zone/AwsAvailabilityZoneExtension.java      |    2 +-
 .../policy/jclouds/os/CreateUserPolicy.java     |  173 ++
 .../location/jclouds/sample/setup-server.sh     |   31 +
 .../resources/sample/script/setup-server.sh     |   31 -
 .../persister/jclouds/BlobStoreCleaner.java     |   71 -
 .../persister/jclouds/BlobStoreExpiryTest.java  |  198 --
 .../BlobStorePersistencePerformanceTest.java    |  121 --
 .../rebind/persister/jclouds/BlobStoreTest.java |  152 --
 ...nMementoPersisterJcloudsObjectStoreTest.java |   67 -
 ...tyToBlobStorePersistencePerformanceTest.java |   65 -
 ...ailabilityManagerJcloudsObjectStoreTest.java |   80 -
 .../JcloudsBlobStoreBasedObjectStoreTest.java   |  119 --
 .../jclouds/JcloudsExpect100ContinueTest.java   |  150 --
 .../JcloudsObjectStoreAccessorWriterTest.java   |  182 --
 .../os/AdvertiseWinrmLoginPolicyTest.java       |   52 -
 .../policy/os/CreateUserPolicyLiveTest.java     |  113 --
 .../policy/os/CreateUserPolicyTest.java         |  138 --
 .../mgmt/persist/jclouds/BlobStoreCleaner.java  |   71 +
 .../persist/jclouds/BlobStoreExpiryTest.java    |  196 ++
 .../BlobStorePersistencePerformanceTest.java    |  121 ++
 .../mgmt/persist/jclouds/BlobStoreTest.java     |  150 ++
 ...nMementoPersisterJcloudsObjectStoreTest.java |   67 +
 ...tyToBlobStorePersistencePerformanceTest.java |   65 +
 ...ailabilityManagerJcloudsObjectStoreTest.java |   80 +
 .../JcloudsBlobStoreBasedObjectStoreTest.java   |  118 ++
 .../jclouds/JcloudsExpect100ContinueTest.java   |  148 ++
 .../JcloudsObjectStoreAccessorWriterTest.java   |  182 ++
 .../jclouds/AbstractJcloudsLiveTest.java        |   12 +-
 .../jclouds/AbstractJcloudsStubbedLiveTest.java |    2 +-
 .../jclouds/BailOutJcloudsLocation.java         |   15 +-
 .../jclouds/BrooklynMachinePoolLiveTest.java    |    4 +-
 .../jclouds/JcloudsAddressesLiveTest.java       |    4 +-
 .../JcloudsByonLocationResolverAwsLiveTest.java |    4 +-
 ...dsByonLocationResolverSoftlayerLiveTest.java |    4 +-
 .../JcloudsByonLocationResolverTest.java        |    9 +-
 .../jclouds/JcloudsLocationMetadataTest.java    |   12 +-
 .../JcloudsLocationRebindMachineLiveTest.java   |    2 +-
 .../jclouds/JcloudsLocationResolverTest.java    |   13 +-
 ...ationTemplateOptionsCustomisersLiveTest.java |    2 +-
 .../location/jclouds/JcloudsLocationTest.java   |   15 +-
 .../location/jclouds/JcloudsLoginLiveTest.java  |    2 +-
 .../jclouds/JcloudsMachineNamerTest.java        |    2 +-
 .../location/jclouds/LiveTestEntity.java        |   12 +-
 .../jclouds/RebindJcloudsLocationLiveTest.java  |   15 +-
 .../jclouds/RebindJcloudsLocationTest.java      |    8 +-
 ...loudsLocationUserLoginAndConfigLiveTest.java |    2 +-
 ...hineProvisioningLocationJcloudsLiveTest.java |    6 +-
 .../jclouds/StandaloneJcloudsLiveTest.java      |    2 +-
 .../provider/AbstractJcloudsLocationTest.java   |   10 +-
 .../AwsEc2LocationWindowsLiveTest.groovy        |   11 +-
 .../provider/CarrenzaLocationLiveTest.groovy    |   13 +-
 .../provider/RackspaceLocationLiveTest.java     |    2 +-
 .../zone/AwsAvailabilityZoneExtensionTest.java  |    6 +-
 .../jclouds/os/CreateUserPolicyLiveTest.java    |  112 ++
 .../policy/jclouds/os/CreateUserPolicyTest.java |  137 ++
 .../java/brooklyn/enricher/DeltaEnricher.java   |   54 -
 .../brooklyn/enricher/HttpLatencyDetector.java  |  320 ----
 .../brooklyn/enricher/RollingMeanEnricher.java  |   82 -
 .../enricher/RollingTimeWindowMeanEnricher.java |  213 ---
 .../enricher/TimeFractionDeltaEnricher.java     |  110 --
 .../enricher/TimeWeightedDeltaEnricher.java     |  131 --
 .../entity/brooklyn/BrooklynMetrics.java        |   56 -
 .../entity/brooklyn/BrooklynMetricsImpl.java    |   87 -
 .../policy/autoscaling/AutoScalerPolicy.java    |   32 +-
 .../brooklyn/policy/enricher/DeltaEnricher.java |   53 +
 .../policy/enricher/HttpLatencyDetector.java    |  319 ++++
 .../policy/enricher/RollingMeanEnricher.java    |   81 +
 .../enricher/RollingTimeWindowMeanEnricher.java |  212 +++
 .../enricher/TimeFractionDeltaEnricher.java     |  109 ++
 .../enricher/TimeWeightedDeltaEnricher.java     |  130 ++
 .../followthesun/DefaultFollowTheSunModel.java  |    2 +-
 .../policy/followthesun/FollowTheSunPolicy.java |   18 +-
 .../policy/followthesun/FollowTheSunPool.java   |    7 +-
 .../followthesun/FollowTheSunPoolImpl.java      |   15 +-
 .../policy/ha/AbstractFailureDetector.java      |   22 +-
 .../policy/ha/ConditionalSuspendPolicy.java     |   15 +-
 .../policy/ha/ConnectionFailureDetector.java    |   12 +-
 .../apache/brooklyn/policy/ha/HASensors.java    |    2 +-
 .../policy/ha/ServiceFailureDetector.java       |   28 +-
 .../brooklyn/policy/ha/ServiceReplacer.java     |   32 +-
 .../brooklyn/policy/ha/ServiceRestarter.java    |   30 +-
 .../policy/ha/SshMachineFailureDetector.java    |   12 +-
 .../loadbalancing/BalanceableContainer.java     |    7 +-
 .../loadbalancing/BalanceableWorkerPool.java    |    7 +-
 .../BalanceableWorkerPoolImpl.java              |   15 +-
 .../loadbalancing/ItemsInContainersGroup.java   |    9 +-
 .../ItemsInContainersGroupImpl.java             |   11 +-
 .../loadbalancing/LoadBalancingPolicy.java      |   18 +-
 .../brooklyn/policy/loadbalancing/Movable.java  |   13 +-
 .../enricher/DeltaEnrichersTests.groovy         |  125 --
 .../enricher/HttpLatencyDetectorTest.java       |  150 --
 .../brooklyn/enricher/RebindEnricherTest.java   |  148 --
 .../enricher/RollingMeanEnricherTest.groovy     |  106 --
 .../RollingTimeWindowMeanEnricherTest.groovy    |  156 --
 .../enricher/TimeFractionDeltaEnricherTest.java |  104 --
 .../entity/brooklyn/BrooklynMetricsTest.java    |  128 --
 .../autoscaling/AutoScalerPolicyMetricTest.java |   21 +-
 .../autoscaling/AutoScalerPolicyRebindTest.java |   22 +-
 .../AutoScalerPolicyReconfigurationTest.java    |   13 +-
 .../autoscaling/AutoScalerPolicyTest.java       |   13 +-
 .../autoscaling/LocallyResizableEntity.java     |    9 +-
 .../policy/enricher/DeltaEnrichersTests.groovy  |  123 ++
 .../enricher/HttpLatencyDetectorTest.java       |  149 ++
 .../policy/enricher/RebindEnricherTest.java     |  153 ++
 .../enricher/RollingMeanEnricherTest.groovy     |  105 ++
 .../RollingTimeWindowMeanEnricherTest.groovy    |  155 ++
 .../enricher/TimeFractionDeltaEnricherTest.java |  104 ++
 .../AbstractFollowTheSunPolicyTest.java         |   20 +-
 .../followthesun/FollowTheSunModelTest.java     |    3 +-
 .../FollowTheSunPolicySoakTest.java             |    8 +-
 .../followthesun/FollowTheSunPolicyTest.java    |   12 +-
 .../ha/ConnectionFailureDetectorTest.java       |   18 +-
 .../brooklyn/policy/ha/HaPolicyRebindTest.java  |   28 +-
 ...ServiceFailureDetectorStabilizationTest.java |   30 +-
 .../policy/ha/ServiceFailureDetectorTest.java   |   32 +-
 .../brooklyn/policy/ha/ServiceReplacerTest.java |   38 +-
 .../policy/ha/ServiceRestarterTest.java         |   28 +-
 .../AbstractLoadBalancingPolicyTest.java        |   20 +-
 .../BalanceableWorkerPoolTest.java              |   22 +-
 .../ItemsInContainersGroupTest.java             |   14 +-
 .../LoadBalancingPolicyConcurrencyTest.java     |    7 +-
 .../LoadBalancingPolicySoakTest.java            |    5 +-
 .../loadbalancing/LoadBalancingPolicyTest.java  |    5 +-
 .../loadbalancing/MockContainerEntity.java      |   17 +-
 .../loadbalancing/MockContainerEntityImpl.java  |    7 +-
 .../policy/loadbalancing/MockItemEntity.java    |    7 +-
 .../loadbalancing/MockItemEntityImpl.java       |    5 +-
 .../entity/monitoring/zabbix/ZabbixFeed.java    |   25 +-
 .../monitoring/zabbix/ZabbixMonitored.java      |   11 +-
 .../monitoring/zabbix/ZabbixPollConfig.java     |   11 +-
 .../entity/monitoring/zabbix/ZabbixServer.java  |   11 +-
 .../monitoring/zabbix/ZabbixServerImpl.java     |   19 +-
 .../basic/AbstractSoftwareProcessDriver.java    |  513 ------
 .../basic/AbstractSoftwareProcessSshDriver.java |  654 -------
 .../AbstractSoftwareProcessWinRmDriver.java     |  195 --
 .../entity/basic/AbstractVanillaProcess.java    |   35 -
 .../entity/basic/EmptySoftwareProcess.java      |   28 -
 .../basic/EmptySoftwareProcessDriver.java       |   22 -
 .../entity/basic/EmptySoftwareProcessImpl.java  |   39 -
 .../basic/EmptySoftwareProcessSshDriver.java    |   83 -
 .../SameServerDriverLifecycleEffectorTasks.java |  170 --
 .../brooklyn/entity/basic/SameServerEntity.java |   69 -
 .../entity/basic/SameServerEntityImpl.java      |  126 --
 .../brooklyn/entity/basic/SoftwareProcess.java  |  359 ----
 .../entity/basic/SoftwareProcessDriver.java     |   76 -
 ...wareProcessDriverLifecycleEffectorTasks.java |  258 ---
 .../entity/basic/SoftwareProcessImpl.java       |  647 -------
 .../entity/basic/VanillaSoftwareProcess.java    |   61 -
 .../basic/VanillaSoftwareProcessDriver.java     |   23 -
 .../basic/VanillaSoftwareProcessImpl.java       |   37 -
 .../basic/VanillaSoftwareProcessSshDriver.java  |  163 --
 .../entity/basic/VanillaWindowsProcess.java     |   64 -
 .../basic/VanillaWindowsProcessDriver.java      |   23 -
 .../entity/basic/VanillaWindowsProcessImpl.java |   47 -
 .../basic/VanillaWindowsProcessWinRmDriver.java |   83 -
 .../basic/lifecycle/NaiveScriptRunner.java      |   43 -
 .../entity/basic/lifecycle/ScriptHelper.java    |  438 -----
 .../entity/basic/lifecycle/ScriptPart.java      |   82 -
 .../entity/brooklynnode/BrooklynCluster.java    |   71 -
 .../brooklynnode/BrooklynClusterImpl.java       |  116 --
 .../brooklynnode/BrooklynEntityMirror.java      |   68 -
 .../brooklynnode/BrooklynEntityMirrorImpl.java  |  195 --
 .../entity/brooklynnode/BrooklynNode.java       |  314 ----
 .../entity/brooklynnode/BrooklynNodeDriver.java |   27 -
 .../entity/brooklynnode/BrooklynNodeImpl.java   |  524 ------
 .../brooklynnode/BrooklynNodeSshDriver.java     |  395 ----
 .../entity/brooklynnode/EntityHttpClient.java   |   93 -
 .../brooklynnode/EntityHttpClientImpl.java      |  163 --
 .../entity/brooklynnode/LocalBrooklynNode.java  |   37 -
 .../brooklynnode/LocalBrooklynNodeImpl.java     |   46 -
 .../brooklynnode/RemoteEffectorBuilder.java     |   85 -
 .../BrooklynClusterUpgradeEffectorBody.java     |  207 ---
 .../BrooklynNodeUpgradeEffectorBody.java        |  230 ---
 .../effector/SelectMasterEffectorBody.java      |  175 --
 .../SetHighAvailabilityModeEffectorBody.java    |   64 -
 ...SetHighAvailabilityPriorityEffectorBody.java |   55 -
 .../brooklyn/entity/chef/ChefAttributeFeed.java |  411 -----
 .../entity/chef/ChefAttributePollConfig.java    |   54 -
 .../brooklyn/entity/chef/ChefBashCommands.java  |   42 -
 .../java/brooklyn/entity/chef/ChefConfig.java   |   99 -
 .../java/brooklyn/entity/chef/ChefConfigs.java  |  103 --
 .../java/brooklyn/entity/chef/ChefEntity.java   |   27 -
 .../brooklyn/entity/chef/ChefEntityImpl.java    |   39 -
 .../entity/chef/ChefLifecycleEffectorTasks.java |  362 ----
 .../brooklyn/entity/chef/ChefServerTasks.java   |   97 -
 .../brooklyn/entity/chef/ChefSoloDriver.java    |   87 -
 .../brooklyn/entity/chef/ChefSoloTasks.java     |   71 -
 .../java/brooklyn/entity/chef/ChefTasks.java    |  154 --
 .../entity/chef/KnifeConvergeTaskFactory.java   |  248 ---
 .../brooklyn/entity/chef/KnifeTaskFactory.java  |  241 ---
 .../java/brooklyn/entity/java/JavaAppUtils.java |  264 ---
 .../brooklyn/entity/java/JavaEntityMethods.java |   30 -
 .../entity/java/JavaSoftwareProcessDriver.java  |   30 -
 .../java/JavaSoftwareProcessSshDriver.java      |  444 -----
 .../java/brooklyn/entity/java/JmxSupport.java   |  359 ----
 .../brooklyn/entity/java/JmxmpSslSupport.java   |  134 --
 .../java/brooklyn/entity/java/UsesJava.java     |   69 -
 .../brooklyn/entity/java/UsesJavaMXBeans.java   |   78 -
 .../main/java/brooklyn/entity/java/UsesJmx.java |  192 --
 .../brooklyn/entity/java/VanillaJavaApp.java    |   78 -
 .../entity/java/VanillaJavaAppDriver.java       |   26 -
 .../entity/java/VanillaJavaAppImpl.java         |  113 --
 .../entity/java/VanillaJavaAppSshDriver.java    |  212 ---
 .../entity/machine/MachineAttributes.java       |   88 -
 .../brooklyn/entity/machine/MachineEntity.java  |   60 -
 .../entity/machine/MachineEntityImpl.java       |  184 --
 .../java/brooklyn/entity/pool/ServerPool.java   |  111 --
 .../brooklyn/entity/pool/ServerPoolImpl.java    |  434 -----
 .../entity/pool/ServerPoolLocation.java         |   83 -
 .../entity/pool/ServerPoolLocationResolver.java |  138 --
 .../entity/service/EntityLaunchListener.java    |  112 --
 .../entity/service/InitdServiceInstaller.java   |  137 --
 .../entity/service/SystemServiceEnricher.java   |  154 --
 .../entity/service/SystemServiceInstaller.java  |   25 -
 .../service/SystemServiceInstallerFactory.java  |   28 -
 .../entity/software/MachineInitTasks.java       |  173 --
 .../software/MachineLifecycleEffectorTasks.java |  949 ----------
 .../software/ProvidesProvisioningFlags.java     |   34 -
 .../entity/software/SshEffectorTasks.java       |  336 ----
 .../brooklyn/entity/software/StaticSensor.java  |   73 -
 .../entity/software/http/HttpRequestSensor.java |   99 -
 .../software/java/JmxAttributeSensor.java       |  123 --
 .../entity/software/ssh/SshCommandEffector.java |  104 --
 .../entity/software/ssh/SshCommandSensor.java   |  143 --
 .../winrm/WindowsPerformanceCounterSensors.java |   74 -
 .../event/feed/jmx/JmxAttributePollConfig.java  |   75 -
 .../java/brooklyn/event/feed/jmx/JmxFeed.java   |  437 -----
 .../java/brooklyn/event/feed/jmx/JmxHelper.java |  725 --------
 .../event/feed/jmx/JmxNotificationFilters.java  |   64 -
 .../jmx/JmxNotificationSubscriptionConfig.java  |   96 -
 .../event/feed/jmx/JmxOperationPollConfig.java  |  122 --
 .../event/feed/jmx/JmxValueFunctions.java       |   95 -
 .../entity/brooklynnode/BrooklynCluster.java    |   70 +
 .../brooklynnode/BrooklynClusterImpl.java       |  115 ++
 .../brooklynnode/BrooklynEntityMirror.java      |   67 +
 .../brooklynnode/BrooklynEntityMirrorImpl.java  |  194 ++
 .../entity/brooklynnode/BrooklynNode.java       |  312 ++++
 .../entity/brooklynnode/BrooklynNodeDriver.java |   27 +
 .../entity/brooklynnode/BrooklynNodeImpl.java   |  522 ++++++
 .../brooklynnode/BrooklynNodeSshDriver.java     |  394 ++++
 .../entity/brooklynnode/EntityHttpClient.java   |   93 +
 .../brooklynnode/EntityHttpClientImpl.java      |  162 ++
 .../entity/brooklynnode/LocalBrooklynNode.java  |   37 +
 .../brooklynnode/LocalBrooklynNodeImpl.java     |   46 +
 .../brooklynnode/RemoteEffectorBuilder.java     |   84 +
 .../BrooklynClusterUpgradeEffectorBody.java     |  206 +++
 .../BrooklynNodeUpgradeEffectorBody.java        |  229 +++
 .../effector/SelectMasterEffectorBody.java      |  174 ++
 .../SetHighAvailabilityModeEffectorBody.java    |   63 +
 ...SetHighAvailabilityPriorityEffectorBody.java |   54 +
 .../brooklyn/entity/chef/ChefAttributeFeed.java |  410 +++++
 .../entity/chef/ChefAttributePollConfig.java    |   53 +
 .../brooklyn/entity/chef/ChefBashCommands.java  |   42 +
 .../apache/brooklyn/entity/chef/ChefConfig.java |   98 +
 .../brooklyn/entity/chef/ChefConfigs.java       |  102 +
 .../apache/brooklyn/entity/chef/ChefEntity.java |   26 +
 .../brooklyn/entity/chef/ChefEntityImpl.java    |   38 +
 .../entity/chef/ChefLifecycleEffectorTasks.java |  360 ++++
 .../brooklyn/entity/chef/ChefServerTasks.java   |   97 +
 .../brooklyn/entity/chef/ChefSoloDriver.java    |   85 +
 .../brooklyn/entity/chef/ChefSoloTasks.java     |   70 +
 .../apache/brooklyn/entity/chef/ChefTasks.java  |  153 ++
 .../entity/chef/KnifeConvergeTaskFactory.java   |  246 +++
 .../brooklyn/entity/chef/KnifeTaskFactory.java  |  240 +++
 .../brooklyn/entity/java/JavaAppUtils.java      |  263 +++
 .../brooklyn/entity/java/JavaEntityMethods.java |   30 +
 .../entity/java/JavaSoftwareProcessDriver.java  |   30 +
 .../java/JavaSoftwareProcessSshDriver.java      |  443 +++++
 .../entity/java/JmxAttributeSensor.java         |  121 ++
 .../apache/brooklyn/entity/java/JmxSupport.java |  357 ++++
 .../brooklyn/entity/java/JmxmpSslSupport.java   |  134 ++
 .../apache/brooklyn/entity/java/UsesJava.java   |   68 +
 .../brooklyn/entity/java/UsesJavaMXBeans.java   |   77 +
 .../apache/brooklyn/entity/java/UsesJmx.java    |  190 ++
 .../brooklyn/entity/java/VanillaJavaApp.java    |   77 +
 .../entity/java/VanillaJavaAppDriver.java       |   26 +
 .../entity/java/VanillaJavaAppImpl.java         |  112 ++
 .../entity/java/VanillaJavaAppSshDriver.java    |  211 +++
 .../entity/machine/MachineAttributes.java       |   87 +
 .../brooklyn/entity/machine/MachineEntity.java  |   59 +
 .../entity/machine/MachineEntityImpl.java       |  182 ++
 .../entity/machine/MachineInitTasks.java        |  172 ++
 .../machine/ProvidesProvisioningFlags.java      |   35 +
 .../entity/machine/pool/ServerPool.java         |  109 ++
 .../entity/machine/pool/ServerPoolImpl.java     |  432 +++++
 .../entity/machine/pool/ServerPoolLocation.java |   82 +
 .../pool/ServerPoolLocationResolver.java        |  138 ++
 .../base/AbstractSoftwareProcessDriver.java     |  516 ++++++
 .../base/AbstractSoftwareProcessSshDriver.java  |  657 +++++++
 .../AbstractSoftwareProcessWinRmDriver.java     |  193 ++
 .../software/base/AbstractVanillaProcess.java   |   35 +
 .../software/base/EmptySoftwareProcess.java     |   28 +
 .../base/EmptySoftwareProcessDriver.java        |   22 +
 .../software/base/EmptySoftwareProcessImpl.java |   39 +
 .../base/EmptySoftwareProcessSshDriver.java     |   83 +
 .../SameServerDriverLifecycleEffectorTasks.java |  170 ++
 .../entity/software/base/SameServerEntity.java  |   71 +
 .../software/base/SameServerEntityImpl.java     |  128 ++
 .../entity/software/base/SoftwareProcess.java   |  362 ++++
 .../software/base/SoftwareProcessDriver.java    |   75 +
 ...wareProcessDriverLifecycleEffectorTasks.java |  261 +++
 .../software/base/SoftwareProcessImpl.java      |  651 +++++++
 .../software/base/VanillaSoftwareProcess.java   |   62 +
 .../base/VanillaSoftwareProcessDriver.java      |   23 +
 .../base/VanillaSoftwareProcessImpl.java        |   37 +
 .../base/VanillaSoftwareProcessSshDriver.java   |  162 ++
 .../software/base/VanillaWindowsProcess.java    |   64 +
 .../base/VanillaWindowsProcessDriver.java       |   23 +
 .../base/VanillaWindowsProcessImpl.java         |   47 +
 .../base/VanillaWindowsProcessWinRmDriver.java  |   84 +
 .../MachineLifecycleEffectorTasks.java          |  951 ++++++++++
 .../base/lifecycle/NaiveScriptRunner.java       |   43 +
 .../software/base/lifecycle/ScriptHelper.java   |  436 +++++
 .../software/base/lifecycle/ScriptPart.java     |   82 +
 .../system_service/EntityLaunchListener.java    |  111 ++
 .../system_service/InitdServiceInstaller.java   |  135 ++
 .../system_service/SystemServiceEnricher.java   |  152 ++
 .../system_service/SystemServiceInstaller.java  |   25 +
 .../SystemServiceInstallerFactory.java          |   28 +
 .../sensor/feed/jmx/JmxAttributePollConfig.java |   74 +
 .../brooklyn/sensor/feed/jmx/JmxFeed.java       |  423 +++++
 .../brooklyn/sensor/feed/jmx/JmxHelper.java     |  724 ++++++++
 .../sensor/feed/jmx/JmxNotificationFilters.java |   64 +
 .../jmx/JmxNotificationSubscriptionConfig.java  |   95 +
 .../sensor/feed/jmx/JmxOperationPollConfig.java |  121 ++
 .../sensor/feed/jmx/JmxValueFunctions.java      |   95 +
 .../brooklyn/sensor/ssh/SshCommandEffector.java |  102 +
 .../brooklyn/sensor/ssh/SshCommandSensor.java   |  142 ++
 .../brooklyn/sensor/ssh/SshEffectorTasks.java   |  334 ++++
 .../winrm/WindowsPerformanceCounterSensors.java |   73 +
 ...pache.brooklyn.api.location.LocationResolver |    2 +-
 .../entity/brooklynnode/brooklyn-cluster.yaml   |   33 -
 .../brooklyn-node-persisting-to-tmp.yaml        |   27 -
 .../entity/brooklynnode/brooklyn-node.yaml      |   35 -
 .../brooklyn/entity/service/service.sh          |   51 -
 .../entity/brooklynnode/brooklyn-cluster.yaml   |   33 +
 .../brooklyn-node-persisting-to-tmp.yaml        |   27 +
 .../entity/brooklynnode/brooklyn-node.yaml      |   35 +
 .../brooklyn/entity/system_service/service.sh   |   51 +
 .../brooklyn/entity/AbstractEc2LiveTest.java    |  138 --
 .../entity/AbstractGoogleComputeLiveTest.java   |  138 --
 .../entity/AbstractSoftlayerLiveTest.java       |  116 --
 ...ctSoftwareProcessRestartIntegrationTest.java |   94 -
 .../entity/basic/DoNothingSoftwareProcess.java  |   30 -
 .../basic/DoNothingSoftwareProcessDriver.java   |   69 -
 .../basic/DoNothingSoftwareProcessImpl.java     |   35 -
 .../entity/basic/SameServerEntityTest.java      |   82 -
 .../basic/SoftwareProcessEntityLatchTest.java   |  158 --
 .../basic/SoftwareProcessEntityRebindTest.java  |  177 --
 .../entity/basic/SoftwareProcessEntityTest.java |  786 --------
 ...SoftwareProcessSshDriverIntegrationTest.java |  384 ----
 .../basic/SoftwareProcessSubclassTest.java      |  166 --
 ...ftwareProcessAndChildrenIntegrationTest.java |  194 --
 .../entity/basic/lifecycle/MyEntity.java        |   28 -
 .../entity/basic/lifecycle/MyEntityApp.java     |   26 -
 .../entity/basic/lifecycle/MyEntityImpl.java    |  126 --
 .../basic/lifecycle/NaiveScriptRunnerTest.java  |  254 ---
 .../basic/lifecycle/ScriptHelperTest.java       |  159 --
 .../basic/lifecycle/StartStopSshDriverTest.java |  170 --
 .../BrooklynClusterIntegrationTest.java         |   97 -
 .../BrooklynNodeIntegrationTest.java            |  630 -------
 .../entity/brooklynnode/BrooklynNodeTest.java   |  139 --
 .../brooklynnode/CallbackEntityHttpClient.java  |  101 -
 .../entity/brooklynnode/MockBrooklynNode.java   |   71 -
 .../brooklynnode/SameBrooklynNodeImpl.java      |   96 -
 .../brooklynnode/SelectMasterEffectorTest.java  |  257 ---
 .../brooklyn/entity/chef/ChefConfigsTest.java   |   51 -
 .../entity/chef/ChefLiveTestSupport.java        |  100 -
 .../chef/ChefServerTasksIntegrationTest.java    |  125 --
 .../AbstractChefToyMySqlEntityLiveTest.java     |   42 -
 .../ChefSoloDriverMySqlEntityLiveTest.java      |   50 -
 .../mysql/ChefSoloDriverToyMySqlEntity.java     |   90 -
 ...micChefAutodetectToyMySqlEntityLiveTest.java |   43 -
 ...DynamicChefServerToyMySqlEntityLiveTest.java |   51 -
 .../DynamicChefSoloToyMySqlEntityLiveTest.java  |   43 -
 .../chef/mysql/DynamicToyMySqlEntityChef.java   |   82 -
 .../chef/mysql/TypedToyMySqlEntityChef.java     |   56 -
 .../brooklyn/entity/driver/MockSshDriver.java   |   74 -
 ...rWithAvailabilityZonesMultiLocationTest.java |  115 --
 .../brooklyn/entity/java/EntityPollingTest.java |  206 ---
 .../entity/java/ExampleVanillaMain.java         |   26 -
 .../java/ExampleVanillaMainCpuHungry.java       |   41 -
 .../java/brooklyn/entity/java/JavaOptsTest.java |  359 ----
 ...SoftwareProcessSshDriverIntegrationTest.java |  174 --
 .../brooklyn/entity/java/JmxSupportTest.java    |  135 --
 .../brooklyn/entity/java/SslKeyConfigTest.java  |   53 -
 .../entity/java/VanillaJavaAppRebindTest.java   |  173 --
 .../entity/java/VanillaJavaAppTest.java         |  350 ----
 .../machine/MachineEntityEc2LiveTest.java       |   57 -
 .../entity/machine/MachineEntityRebindTest.java |   45 -
 .../entity/pool/AbstractServerPoolTest.java     |  146 --
 .../entity/pool/ServerPoolLiveTest.java         |   98 -
 .../pool/ServerPoolLocationResolverTest.java    |   89 -
 .../entity/pool/ServerPoolRebindTest.java       |  109 --
 .../brooklyn/entity/pool/ServerPoolTest.java    |  176 --
 .../service/SystemServiceEnricherTest.java      |   96 -
 .../entity/software/AbstractDockerLiveTest.java |  100 -
 .../MachineLifecycleEffectorTasksTest.java      |  140 --
 .../entity/software/SoftwareEffectorTest.java   |  142 --
 .../entity/software/SshEffectorTasksTest.java   |  265 ---
 .../entity/software/StaticSensorTest.java       |   55 -
 .../software/http/HttpRequestSensorTest.java    |   85 -
 .../mysql/AbstractToyMySqlEntityTest.java       |  109 --
 .../mysql/DynamicToyMySqlEntityBuilder.java     |  191 --
 .../mysql/DynamicToyMySqlEntityTest.java        |   58 -
 .../software/ssh/SshCommandIntegrationTest.java |  126 --
 .../PortAttributeSensorAndConfigKeyTest.java    |   87 -
 .../brooklyn/event/feed/jmx/JmxFeedTest.java    |  418 -----
 .../brooklyn/event/feed/jmx/JmxHelperTest.java  |  311 ----
 .../event/feed/jmx/RebindJmxFeedTest.java       |  148 --
 .../usage/ApplicationUsageTrackingTest.java     |  225 ---
 .../usage/LocationUsageTrackingTest.java        |  212 ---
 .../usage/RecordingLegacyUsageListener.java     |   70 -
 .../usage/RecordingUsageListener.java           |   67 -
 .../management/usage/UsageListenerTest.java     |  144 --
 .../brooklyn/test/GeneralisedDynamicMBean.java  |  146 --
 .../src/test/java/brooklyn/test/JmxService.java |  173 --
 .../brooklyn/entity/AbstractEc2LiveTest.java    |  139 ++
 .../entity/AbstractGoogleComputeLiveTest.java   |  137 ++
 .../entity/AbstractSoftlayerLiveTest.java       |  115 ++
 .../BrooklynClusterIntegrationTest.java         |   97 +
 .../BrooklynNodeIntegrationTest.java            |  632 +++++++
 .../entity/brooklynnode/BrooklynNodeTest.java   |  141 ++
 .../brooklynnode/CallbackEntityHttpClient.java  |  100 +
 .../entity/brooklynnode/MockBrooklynNode.java   |   72 +
 .../brooklynnode/SameBrooklynNodeImpl.java      |   97 +
 .../brooklynnode/SelectMasterEffectorTest.java  |  259 +++
 .../brooklyn/entity/chef/ChefConfigsTest.java   |   52 +
 .../entity/chef/ChefLiveTestSupport.java        |   99 +
 .../chef/ChefServerTasksIntegrationTest.java    |  126 ++
 .../AbstractChefToyMySqlEntityLiveTest.java     |   40 +
 .../ChefSoloDriverMySqlEntityLiveTest.java      |   49 +
 .../mysql/ChefSoloDriverToyMySqlEntity.java     |   89 +
 ...micChefAutodetectToyMySqlEntityLiveTest.java |   43 +
 ...DynamicChefServerToyMySqlEntityLiveTest.java |   50 +
 .../DynamicChefSoloToyMySqlEntityLiveTest.java  |   43 +
 .../chef/mysql/DynamicToyMySqlEntityChef.java   |   81 +
 .../chef/mysql/TypedToyMySqlEntityChef.java     |   55 +
 .../brooklyn/entity/java/EntityPollingTest.java |  206 +++
 .../entity/java/ExampleVanillaMain.java         |   26 +
 .../java/ExampleVanillaMainCpuHungry.java       |   41 +
 .../brooklyn/entity/java/JavaOptsTest.java      |  361 ++++
 ...SoftwareProcessSshDriverIntegrationTest.java |  173 ++
 .../brooklyn/entity/java/JmxSupportTest.java    |  135 ++
 .../brooklyn/entity/java/SslKeyConfigTest.java  |   53 +
 .../entity/java/VanillaJavaAppRebindTest.java   |  173 ++
 .../entity/java/VanillaJavaAppTest.java         |  352 ++++
 .../machine/MachineEntityEc2LiveTest.java       |   57 +
 .../entity/machine/MachineEntityRebindTest.java |   44 +
 .../machine/pool/AbstractServerPoolTest.java    |  145 ++
 .../entity/machine/pool/ServerPoolLiveTest.java |   97 +
 .../pool/ServerPoolLocationResolverTest.java    |   90 +
 .../machine/pool/ServerPoolRebindTest.java      |  109 ++
 .../entity/machine/pool/ServerPoolTest.java     |  175 ++
 .../software/base/AbstractDockerLiveTest.java   |   99 +
 ...ctSoftwareProcessRestartIntegrationTest.java |   96 +
 .../software/base/DoNothingSoftwareProcess.java |   33 +
 .../base/DoNothingSoftwareProcessDriver.java    |   69 +
 .../base/DoNothingSoftwareProcessImpl.java      |   38 +
 .../software/base/SameServerEntityTest.java     |   84 +
 .../software/base/SoftwareEffectorTest.java     |  141 ++
 .../base/SoftwareProcessEntityLatchTest.java    |  161 ++
 .../base/SoftwareProcessEntityRebindTest.java   |  179 ++
 .../base/SoftwareProcessEntityTest.java         |  799 ++++++++
 ...SoftwareProcessSshDriverIntegrationTest.java |  389 ++++
 .../base/SoftwareProcessSubclassTest.java       |  169 ++
 ...ftwareProcessAndChildrenIntegrationTest.java |  197 ++
 .../MachineLifecycleEffectorTasksTest.java      |  147 ++
 .../software/base/lifecycle/MyEntity.java       |   27 +
 .../software/base/lifecycle/MyEntityApp.java    |   26 +
 .../software/base/lifecycle/MyEntityImpl.java   |  125 ++
 .../base/lifecycle/NaiveScriptRunnerTest.java   |  254 +++
 .../base/lifecycle/ScriptHelperTest.java        |  157 ++
 .../base/lifecycle/StartStopSshDriverTest.java  |  168 ++
 .../usage/ApplicationUsageTrackingTest.java     |  224 +++
 .../mgmt/usage/LocationUsageTrackingTest.java   |  210 +++
 .../usage/RecordingLegacyUsageListener.java     |   70 +
 .../core/mgmt/usage/RecordingUsageListener.java |   67 +
 .../test/core/mgmt/usage/UsageListenerTest.java |  142 ++
 .../base/test/driver/MockSshDriver.java         |   72 +
 ...rWithAvailabilityZonesMultiLocationTest.java |  115 ++
 .../base/test/jmx/GeneralisedDynamicMBean.java  |  146 ++
 .../software/base/test/jmx/JmxService.java      |  172 ++
 .../location/MachineDetailsEc2LiveTest.java     |   70 +
 .../MachineDetailsGoogleComputeLiveTest.java    |   67 +
 .../location/WinRmMachineLocationLiveTest.java  |   92 +
 .../test/mysql/AbstractToyMySqlEntityTest.java  |  107 ++
 .../mysql/DynamicToyMySqlEntityBuilder.java     |  189 ++
 .../test/mysql/DynamicToyMySqlEntityTest.java   |   58 +
 .../PortAttributeSensorAndConfigKeyTest.java    |   86 +
 .../test/ssh/SshCommandIntegrationTest.java     |  126 ++
 .../SystemServiceEnricherTest.java              |   95 +
 .../basic/MachineDetailsEc2LiveTest.java        |   68 -
 .../MachineDetailsGoogleComputeLiveTest.java    |   65 -
 .../basic/WinRmMachineLocationLiveTest.java     |   94 -
 .../basic/WinRmMachineLocationTest.java         |   44 -
 .../brooklyn/sensor/feed/jmx/JmxFeedTest.java   |  422 +++++
 .../brooklyn/sensor/feed/jmx/JmxHelperTest.java |  311 ++++
 .../sensor/feed/jmx/RebindJmxFeedTest.java      |  148 ++
 .../sensor/ssh/SshEffectorTasksTest.java        |  264 +++
 .../resources/brooklyn/entity/basic/frogs.txt   |   27 -
 .../brooklyn/entity/basic/template.yaml         |   23 -
 .../basic/template_with_extra_substitutions.txt |   18 -
 .../brooklyn-tests.pem                          |   27 -
 .../brooklyn-validator.pem                      |   27 -
 .../hosted-chef-brooklyn-credentials/knife.rb   |   27 -
 .../brooklyn-tests.pem                          |   27 +
 .../brooklyn-validator.pem                      |   27 +
 .../hosted-chef-brooklyn-credentials/knife.rb   |   27 +
 .../brooklyn/entity/software/base/frogs.txt     |   27 +
 .../brooklyn/entity/software/base/template.yaml |   23 +
 .../base/template_with_extra_substitutions.txt  |   18 +
 .../brooklyn/entity/database/DatabaseNode.java  |    2 +-
 .../entity/database/DatastoreMixins.java        |   15 +-
 .../entity/database/crate/CrateNode.java        |   32 +-
 .../entity/database/crate/CrateNodeDriver.java  |    2 +-
 .../entity/database/crate/CrateNodeImpl.java    |   17 +-
 .../database/crate/CrateNodeSshDriver.java      |    9 +-
 .../entity/database/mariadb/MariaDbDriver.java  |    7 +-
 .../entity/database/mariadb/MariaDbNode.java    |   30 +-
 .../database/mariadb/MariaDbNodeImpl.java       |   18 +-
 .../database/mariadb/MariaDbSshDriver.java      |   18 +-
 .../entity/database/mysql/MySqlCluster.java     |   14 +-
 .../entity/database/mysql/MySqlClusterImpl.java |   35 +-
 .../entity/database/mysql/MySqlDriver.java      |    7 +-
 .../entity/database/mysql/MySqlNode.java        |   36 +-
 .../entity/database/mysql/MySqlNodeImpl.java    |   18 +-
 .../entity/database/mysql/MySqlSshDriver.java   |   20 +-
 .../database/postgresql/PostgreSqlDriver.java   |    9 +-
 .../database/postgresql/PostgreSqlNode.java     |   24 +-
 .../PostgreSqlNodeChefImplFromScratch.java      |   36 +-
 .../database/postgresql/PostgreSqlNodeImpl.java |    7 +-
 .../database/postgresql/PostgreSqlSpecs.java    |    7 +-
 .../postgresql/PostgreSqlSshDriver.java         |   23 +-
 .../entity/database/rubyrep/RubyRepDriver.java  |    2 +-
 .../entity/database/rubyrep/RubyRepNode.java    |   21 +-
 .../database/rubyrep/RubyRepNodeImpl.java       |    8 +-
 .../database/rubyrep/RubyRepSshDriver.java      |   12 +-
 .../brooklyn/entity/database/mssql/mssql.yaml   |    2 +-
 .../crate/CrateNodeIntegrationTest.java         |   12 +-
 .../mariadb/MariaDbIntegrationTest.java         |   18 +-
 .../database/mariadb/MariaDbLiveEc2Test.java    |    6 +-
 .../mariadb/MariaDbLiveRackspaceTest.java       |    4 +-
 .../mysql/MySqlClusterIntegrationTest.java      |    3 +-
 .../database/mysql/MySqlClusterLiveEc2Test.java |    4 +-
 .../mysql/MySqlClusterLiveSoftlayerTest.java    |    4 +-
 .../database/mysql/MySqlClusterTestHelper.java  |    4 +-
 .../database/mysql/MySqlIntegrationTest.java    |    8 +-
 .../entity/database/mysql/MySqlLiveEc2Test.java |    5 +-
 .../entity/database/mysql/MySqlLiveGceTest.java |    5 +-
 .../database/mysql/MySqlLiveRackspaceTest.java  |    6 +-
 .../mysql/MySqlRestartIntegrationTest.java      |    7 +-
 .../database/mysql/MysqlDockerLiveTest.java     |    4 +-
 .../postgresql/PostgreSqDockerLiveTest.java     |    4 +-
 .../database/postgresql/PostgreSqlChefTest.java |   18 +-
 .../postgresql/PostgreSqlEc2LiveTest.java       |    5 +-
 .../postgresql/PostgreSqlGceLiveTest.java       |    5 +-
 .../postgresql/PostgreSqlIntegrationTest.java   |   18 +-
 .../postgresql/PostgreSqlRackspaceLiveTest.java |    6 +-
 .../PostgreSqlRebindIntegrationTest.java        |    7 +-
 .../PostgreSqlRestartIntegrationTest.java       |    7 +-
 .../database/rubyrep/RubyRepEc2LiveTest.java    |    8 +-
 .../rubyrep/RubyRepIntegrationTest.java         |   20 +-
 .../rubyrep/RubyRepRackspaceLiveTest.java       |    6 +-
 .../entity/messaging/MessageBroker.java         |    5 +-
 .../apache/brooklyn/entity/messaging/Queue.java |    7 +-
 .../apache/brooklyn/entity/messaging/Topic.java |    2 +-
 .../messaging/activemq/ActiveMQBroker.java      |   25 +-
 .../messaging/activemq/ActiveMQBrokerImpl.java  |   11 +-
 .../activemq/ActiveMQDestinationImpl.java       |    7 +-
 .../messaging/activemq/ActiveMQDriver.java      |    2 +-
 .../messaging/activemq/ActiveMQQueue.java       |    3 +-
 .../messaging/activemq/ActiveMQQueueImpl.java   |    5 +-
 .../messaging/activemq/ActiveMQSpecs.java       |    2 +-
 .../messaging/activemq/ActiveMQSshDriver.java   |    7 +-
 .../messaging/activemq/ActiveMQTopic.java       |    3 +-
 .../entity/messaging/amqp/AmqpExchange.java     |    7 +-
 .../entity/messaging/amqp/AmqpServer.java       |    7 +-
 .../entity/messaging/jms/JMSBroker.java         |    2 +-
 .../entity/messaging/jms/JMSBrokerImpl.java     |    6 +-
 .../messaging/jms/JMSDestinationImpl.java       |    2 +-
 .../kafka/AbstractfKafkaSshDriver.java          |   10 +-
 .../brooklyn/entity/messaging/kafka/Kafka.java  |   12 +-
 .../entity/messaging/kafka/KafkaBroker.java     |   24 +-
 .../messaging/kafka/KafkaBrokerDriver.java      |    2 +-
 .../entity/messaging/kafka/KafkaBrokerImpl.java |   13 +-
 .../messaging/kafka/KafkaBrokerSshDriver.java   |    8 +-
 .../entity/messaging/kafka/KafkaCluster.java    |   29 +-
 .../messaging/kafka/KafkaClusterImpl.java       |   17 +-
 .../entity/messaging/kafka/KafkaZooKeeper.java  |   17 +-
 .../messaging/kafka/KafkaZooKeeperDriver.java   |    2 +-
 .../messaging/kafka/KafkaZooKeeperImpl.java     |    3 +-
 .../kafka/KafkaZooKeeperSshDriver.java          |    5 +-
 .../entity/messaging/qpid/QpidBroker.java       |   21 +-
 .../entity/messaging/qpid/QpidBrokerImpl.java   |   15 +-
 .../messaging/qpid/QpidDestinationImpl.java     |   13 +-
 .../entity/messaging/qpid/QpidDriver.java       |    2 +-
 .../entity/messaging/qpid/QpidQueue.java        |    3 +-
 .../entity/messaging/qpid/QpidQueueImpl.java    |    5 +-
 .../entity/messaging/qpid/QpidSshDriver.java    |    8 +-
 .../entity/messaging/qpid/QpidTopic.java        |    3 +-
 .../entity/messaging/rabbit/RabbitBroker.java   |   21 +-
 .../messaging/rabbit/RabbitBrokerImpl.java      |    7 +-
 .../messaging/rabbit/RabbitDestination.java     |    5 +-
 .../entity/messaging/rabbit/RabbitDriver.java   |    2 +-
 .../entity/messaging/rabbit/RabbitQueue.java    |    6 +-
 .../messaging/rabbit/RabbitSshDriver.java       |    9 +-
 .../brooklyn/entity/messaging/storm/Storm.java  |   21 +-
 .../entity/messaging/storm/StormDeployment.java |    9 +-
 .../messaging/storm/StormDeploymentImpl.java    |   13 +-
 .../entity/messaging/storm/StormDriver.java     |    2 +-
 .../entity/messaging/storm/StormImpl.java       |   13 +-
 .../entity/messaging/storm/StormSshDriver.java  |   20 +-
 .../entity/zookeeper/AbstractZooKeeperImpl.java |   11 +-
 .../entity/zookeeper/ZooKeeperDriver.java       |    2 +-
 .../entity/zookeeper/ZooKeeperEnsemble.java     |   15 +-
 .../entity/zookeeper/ZooKeeperEnsembleImpl.java |   11 +-
 .../entity/zookeeper/ZooKeeperNode.java         |   17 +-
 .../entity/zookeeper/ZooKeeperSshDriver.java    |    8 +-
 .../messaging/activemq/ActiveMQEc2LiveTest.java |    7 +-
 .../activemq/ActiveMQGoogleComputeLiveTest.java |    7 +-
 .../activemq/ActiveMQIntegrationTest.java       |   15 +-
 .../messaging/kafka/KafkaIntegrationTest.java   |   16 +-
 .../entity/messaging/kafka/KafkaLiveTest.java   |    9 +-
 .../entity/messaging/kafka/KafkaSupport.java    |    2 +-
 .../entity/messaging/qpid/QpidEc2LiveTest.java  |    5 +-
 .../messaging/qpid/QpidIntegrationTest.java     |   15 +-
 .../messaging/rabbit/RabbitEc2LiveTest.java     |    5 +-
 .../messaging/rabbit/RabbitIntegrationTest.java |   14 +-
 .../storm/StormAbstractCloudLiveTest.java       |   21 +-
 .../messaging/storm/StormEc2LiveTest.java       |    9 +-
 .../zookeeper/ZooKeeperEc2LiveTest.java         |    9 +-
 .../zookeeper/ZooKeeperEnsembleLiveTest.java    |   12 +-
 .../entity/monitoring/monit/MonitDriver.java    |    2 +-
 .../entity/monitoring/monit/MonitNode.java      |   21 +-
 .../entity/monitoring/monit/MonitNodeImpl.java  |   11 +-
 .../entity/monitoring/monit/MonitSshDriver.java |    9 +-
 .../monitoring/monit/MonitIntegrationTest.java  |   15 +-
 .../entity/network/bind/BindDnsServer.java      |   22 +-
 .../network/bind/BindDnsServerDriver.java       |    4 +-
 .../entity/network/bind/BindDnsServerImpl.java  |   19 +-
 .../network/bind/BindDnsServerSshDriver.java    |    5 +-
 .../network/bind/BindDnsServerByonLiveTest.java |    4 +-
 .../network/bind/BindDnsServerEc2LiveTest.java  |    4 +-
 .../bind/BindDnsServerIntegrationTest.java      |   27 +-
 .../network/bind/BindDnsServerLiveTest.java     |   17 +-
 .../bind/BindDnsServerSoftlayerLiveTest.java    |    4 +-
 .../bind/DoNothingSoftwareProcessDriver.java    |    9 +-
 .../network/bind/PrefixAndIdEnricher.java       |   15 +-
 .../network/bind/TestBindDnsServerImpl.java     |    5 +-
 .../nosql/cassandra/CassandraCluster.java       |    2 +-
 .../nosql/cassandra/CassandraDatacenter.java    |   25 +-
 .../cassandra/CassandraDatacenterImpl.java      |   36 +-
 .../entity/nosql/cassandra/CassandraFabric.java |   13 +-
 .../nosql/cassandra/CassandraFabricImpl.java    |   23 +-
 .../entity/nosql/cassandra/CassandraNode.java   |   32 +-
 .../nosql/cassandra/CassandraNodeDriver.java    |    5 +-
 .../nosql/cassandra/CassandraNodeImpl.java      |   40 +-
 .../nosql/cassandra/CassandraNodeSshDriver.java |   31 +-
 .../nosql/couchbase/CouchbaseCluster.java       |   13 +-
 .../nosql/couchbase/CouchbaseClusterImpl.java   |   46 +-
 .../entity/nosql/couchbase/CouchbaseNode.java   |   29 +-
 .../nosql/couchbase/CouchbaseNodeDriver.java    |    3 +-
 .../nosql/couchbase/CouchbaseNodeImpl.java      |   30 +-
 .../nosql/couchbase/CouchbaseNodeSshDriver.java |   36 +-
 .../nosql/couchbase/CouchbaseSyncGateway.java   |   17 +-
 .../couchbase/CouchbaseSyncGatewayDriver.java   |    2 +-
 .../couchbase/CouchbaseSyncGatewayImpl.java     |    9 +-
 .../CouchbaseSyncGatewaySshDriver.java          |   14 +-
 .../entity/nosql/couchdb/CouchDBCluster.java    |   13 +-
 .../nosql/couchdb/CouchDBClusterImpl.java       |    5 +-
 .../entity/nosql/couchdb/CouchDBNode.java       |   11 +-
 .../entity/nosql/couchdb/CouchDBNodeDriver.java |    2 +-
 .../entity/nosql/couchdb/CouchDBNodeImpl.java   |   11 +-
 .../nosql/couchdb/CouchDBNodeSshDriver.java     |    8 +-
 .../elasticsearch/ElasticSearchCluster.java     |    9 +-
 .../elasticsearch/ElasticSearchClusterImpl.java |    5 +-
 .../nosql/elasticsearch/ElasticSearchNode.java  |   24 +-
 .../elasticsearch/ElasticSearchNodeDriver.java  |    2 +-
 .../elasticsearch/ElasticSearchNodeImpl.java    |   16 +-
 .../ElasticSearchNodeSshDriver.java             |   10 +-
 .../nosql/mongodb/AbstractMongoDBServer.java    |   13 +-
 .../nosql/mongodb/AbstractMongoDBSshDriver.java |   12 +-
 .../entity/nosql/mongodb/MongoDBClient.java     |   13 +-
 .../nosql/mongodb/MongoDBClientDriver.java      |    2 +-
 .../entity/nosql/mongodb/MongoDBClientImpl.java |    4 +-
 .../nosql/mongodb/MongoDBClientSshDriver.java   |   10 +-
 .../entity/nosql/mongodb/MongoDBDriver.java     |    2 +-
 .../entity/nosql/mongodb/MongoDBReplicaSet.java |   15 +-
 .../nosql/mongodb/MongoDBReplicaSetImpl.java    |   21 +-
 .../entity/nosql/mongodb/MongoDBServer.java     |   17 +-
 .../entity/nosql/mongodb/MongoDBServerImpl.java |   12 +-
 .../entity/nosql/mongodb/MongoDBSshDriver.java  |    3 +-
 .../sharding/CoLocatedMongoDBRouter.java        |   15 +-
 .../sharding/CoLocatedMongoDBRouterImpl.java    |   13 +-
 .../mongodb/sharding/MongoDBConfigServer.java   |    2 +-
 .../sharding/MongoDBConfigServerCluster.java    |    9 +-
 .../MongoDBConfigServerClusterImpl.java         |    5 +-
 .../sharding/MongoDBConfigServerDriver.java     |    2 +-
 .../sharding/MongoDBConfigServerImpl.java       |    2 +-
 .../sharding/MongoDBConfigServerSshDriver.java  |    3 +-
 .../nosql/mongodb/sharding/MongoDBRouter.java   |    9 +-
 .../mongodb/sharding/MongoDBRouterCluster.java  |    9 +-
 .../sharding/MongoDBRouterClusterImpl.java      |   15 +-
 .../mongodb/sharding/MongoDBRouterDriver.java   |    2 +-
 .../mongodb/sharding/MongoDBRouterImpl.java     |    7 +-
 .../sharding/MongoDBRouterSshDriver.java        |    3 +-
 .../mongodb/sharding/MongoDBShardCluster.java   |    5 +-
 .../sharding/MongoDBShardClusterImpl.java       |   11 +-
 .../sharding/MongoDBShardedDeployment.java      |   15 +-
 .../sharding/MongoDBShardedDeploymentImpl.java  |   25 +-
 .../entity/nosql/redis/RedisCluster.java        |    7 +-
 .../entity/nosql/redis/RedisClusterImpl.java    |   21 +-
 .../brooklyn/entity/nosql/redis/RedisShard.java |    2 +-
 .../entity/nosql/redis/RedisShardImpl.java      |    2 +-
 .../brooklyn/entity/nosql/redis/RedisSlave.java |    7 +-
 .../brooklyn/entity/nosql/redis/RedisStore.java |   17 +-
 .../entity/nosql/redis/RedisStoreDriver.java    |    2 +-
 .../entity/nosql/redis/RedisStoreImpl.java      |   14 +-
 .../entity/nosql/redis/RedisStoreSshDriver.java |    8 +-
 .../brooklyn/entity/nosql/riak/RiakCluster.java |   15 +-
 .../entity/nosql/riak/RiakClusterImpl.java      |   33 +-
 .../brooklyn/entity/nosql/riak/RiakNode.java    |   27 +-
 .../entity/nosql/riak/RiakNodeDriver.java       |    4 +-
 .../entity/nosql/riak/RiakNodeImpl.java         |   20 +-
 .../entity/nosql/riak/RiakNodeSshDriver.java    |   19 +-
 .../brooklyn/entity/nosql/solr/SolrServer.java  |   24 +-
 .../entity/nosql/solr/SolrServerDriver.java     |    4 +-
 .../entity/nosql/solr/SolrServerImpl.java       |   11 +-
 .../entity/nosql/solr/SolrServerSshDriver.java  |   13 +-
 .../cassandra/AbstractCassandraNodeTest.java    |    4 +-
 .../entity/nosql/cassandra/AstyanaxSupport.java |    3 +-
 .../CassandraDatacenterIntegrationTest.java     |    9 +-
 .../cassandra/CassandraDatacenterLiveTest.java  |   11 +-
 ...assandraDatacenterRebindIntegrationTest.java |   11 +-
 .../cassandra/CassandraDatacenterTest.java      |   20 +-
 .../nosql/cassandra/CassandraFabricTest.java    |   26 +-
 .../cassandra/CassandraNodeEc2LiveTest.java     |    5 +-
 .../cassandra/CassandraNodeIntegrationTest.java |    9 +-
 .../nosql/cassandra/CassandraNodeLiveTest.java  |    2 +-
 .../nosql/couchbase/CouchbaseOfflineTest.java   |   12 +-
 .../CouchbaseSyncGatewayEc2LiveTest.java        |    9 +-
 .../nosql/couchdb/AbstractCouchDBNodeTest.java  |   10 +-
 .../nosql/couchdb/CouchDBClusterLiveTest.java   |   11 +-
 .../nosql/couchdb/CouchDBNodeEc2LiveTest.java   |    7 +-
 .../couchdb/CouchDBNodeIntegrationTest.java     |    5 +-
 .../nosql/couchdb/CouchDBNodeLiveTest.java      |    5 +-
 .../entity/nosql/couchdb/JcouchdbSupport.java   |    3 +-
 .../ElasticSearchClusterIntegrationTest.java    |   17 +-
 .../ElasticSearchNodeIntegrationTest.java       |   22 +-
 .../nosql/mongodb/MongoDBEc2LiveTest.java       |    5 +-
 .../nosql/mongodb/MongoDBIntegrationTest.java   |   13 +-
 .../mongodb/MongoDBRebindIntegrationTest.java   |    7 +-
 .../mongodb/MongoDBReplicaSetEc2LiveTest.java   |    9 +-
 .../MongoDBReplicaSetIntegrationTest.java       |   12 +-
 .../mongodb/MongoDBRestartIntegrationTest.java  |    7 +-
 .../nosql/mongodb/MongoDBSoftLayerLiveTest.java |    5 +-
 .../MongoDBConfigServerIntegrationTest.java     |   14 +-
 .../MongoDBShardedDeploymentEc2LiveTest.java    |    7 +-
 ...MongoDBShardedDeploymentIntegrationTest.java |    9 +-
 .../redis/RedisClusterIntegrationTest.java      |   16 +-
 .../entity/nosql/redis/RedisEc2LiveTest.java    |    5 +-
 .../nosql/redis/RedisIntegrationTest.java       |   12 +-
 .../nosql/riak/RiakClusterEc2LiveTest.java      |    7 +-
 .../entity/nosql/riak/RiakNodeEc2LiveTest.java  |    5 +-
 .../riak/RiakNodeGoogleComputeLiveTest.java     |    5 +-
 .../nosql/riak/RiakNodeIntegrationTest.java     |   10 +-
 .../nosql/riak/RiakNodeSoftlayerLiveTest.java   |    5 +-
 .../nosql/solr/AbstractSolrServerTest.java      |    4 +-
 .../entity/nosql/solr/SolrJSupport.java         |    3 +-
 .../nosql/solr/SolrServerEc2LiveTest.java       |    7 +-
 .../nosql/solr/SolrServerIntegrationTest.java   |    7 +-
 .../entity/nosql/solr/SolrServerLiveTest.java   |    5 +-
 .../entity/osgi/karaf/KarafContainer.java       |   27 +-
 .../entity/osgi/karaf/KarafContainerImpl.java   |   23 +-
 .../brooklyn/entity/osgi/karaf/KarafDriver.java |    2 +-
 .../entity/osgi/karaf/KarafSshDriver.java       |    7 +-
 .../osgi/karaf/KarafContainerEc2LiveTest.java   |    5 +-
 .../entity/osgi/karaf/KarafContainerTest.java   |   14 +-
 .../entity/dns/AbstractGeoDnsService.java       |   14 +-
 .../entity/dns/AbstractGeoDnsServiceImpl.java   |   18 +-
 .../dns/geoscaling/GeoscalingDnsService.java    |   15 +-
 .../geoscaling/GeoscalingDnsServiceImpl.java    |    8 +-
 .../geoscaling/GeoscalingScriptGenerator.java   |    2 +-
 .../dns/geoscaling/GeoscalingWebClient.java     |    2 +-
 .../entity/proxy/AbstractController.java        |   15 +-
 .../entity/proxy/AbstractControllerImpl.java    |   28 +-
 .../proxy/AbstractNonProvisionedController.java |    2 +-
 .../AbstractNonProvisionedControllerImpl.java   |   13 +-
 .../brooklyn/entity/proxy/LoadBalancer.java     |   21 +-
 .../entity/proxy/LoadBalancerCluster.java       |    5 +-
 .../entity/proxy/LoadBalancerClusterImpl.java   |    3 +-
 .../brooklyn/entity/proxy/ProxySslConfig.java   |    4 +-
 .../entity/proxy/nginx/NginxController.java     |   23 +-
 .../entity/proxy/nginx/NginxControllerImpl.java |   35 +-
 .../entity/proxy/nginx/NginxDriver.java         |    2 +-
 .../entity/proxy/nginx/NginxSshDriver.java      |   26 +-
 .../nginx/NginxTemplateConfigGenerator.java     |    7 +-
 .../brooklyn/entity/proxy/nginx/UrlMapping.java |   17 +-
 .../entity/proxy/nginx/UrlMappingImpl.java      |   19 +-
 .../webapp/ControlledDynamicWebAppCluster.java  |   37 +-
 .../ControlledDynamicWebAppClusterImpl.java     |   31 +-
 .../entity/webapp/DynamicWebAppCluster.java     |    9 +-
 .../entity/webapp/DynamicWebAppClusterImpl.java |   29 +-
 .../entity/webapp/DynamicWebAppFabric.java      |    9 +-
 .../entity/webapp/DynamicWebAppFabricImpl.java  |    7 +-
 .../entity/webapp/ElasticJavaWebAppService.java |   11 +-
 .../entity/webapp/JavaWebAppDriver.java         |    2 +-
 .../entity/webapp/JavaWebAppService.java        |   17 +-
 .../webapp/JavaWebAppSoftwareProcess.java       |    2 +-
 .../webapp/JavaWebAppSoftwareProcessImpl.java   |    9 +-
 .../entity/webapp/JavaWebAppSshDriver.java      |   13 +-
 .../entity/webapp/WebAppServiceConstants.java   |   13 +-
 .../entity/webapp/WebAppServiceMethods.java     |   10 +-
 .../entity/webapp/WebAppServiceMetrics.java     |   11 +-
 .../entity/webapp/jboss/JBoss6Server.java       |   13 +-
 .../entity/webapp/jboss/JBoss6ServerImpl.java   |    9 +-
 .../entity/webapp/jboss/JBoss6SshDriver.java    |   12 +-
 .../entity/webapp/jboss/JBoss7Server.java       |   21 +-
 .../entity/webapp/jboss/JBoss7ServerImpl.java   |   12 +-
 .../entity/webapp/jboss/JBoss7SshDriver.java    |    8 +-
 .../entity/webapp/jetty/Jetty6Server.java       |   19 +-
 .../entity/webapp/jetty/Jetty6ServerImpl.java   |   13 +-
 .../entity/webapp/jetty/Jetty6SshDriver.java    |    6 +-
 .../webapp/nodejs/NodeJsWebAppDriver.java       |    2 +-
 .../webapp/nodejs/NodeJsWebAppService.java      |   14 +-
 .../webapp/nodejs/NodeJsWebAppServiceImpl.java  |   13 +-
 .../webapp/nodejs/NodeJsWebAppSshDriver.java    |   12 +-
 .../entity/webapp/tomcat/Tomcat7SshDriver.java  |    2 +-
 .../entity/webapp/tomcat/Tomcat8Server.java     |   11 +-
 .../entity/webapp/tomcat/TomcatServer.java      |   24 +-
 .../entity/webapp/tomcat/TomcatServerImpl.java  |    7 +-
 .../entity/webapp/tomcat/TomcatSshDriver.java   |    6 +-
 .../entity/dns/AbstractGeoDnsServiceTest.java   |   42 +-
 .../geoscaling/GeoscalingIntegrationTest.java   |   20 +-
 .../GeoscalingScriptGeneratorTest.java          |    2 +-
 .../dns/geoscaling/GeoscalingWebClientTest.java |    2 +-
 .../entity/proxy/AbstractControllerTest.java    |   32 +-
 .../entity/proxy/ProxySslConfigTest.java        |    2 +-
 .../brooklyn/entity/proxy/StubAppServer.java    |   11 +-
 .../proxy/TrackingAbstractController.java       |    2 +-
 .../proxy/TrackingAbstractControllerImpl.java   |    3 +-
 .../brooklyn/entity/proxy/UrlMappingTest.java   |   26 +-
 .../nginx/NginxClusterIntegrationTest.java      |   18 +-
 .../entity/proxy/nginx/NginxEc2LiveTest.java    |    7 +-
 .../nginx/NginxHttpsSslIntegrationTest.java     |   16 +-
 .../proxy/nginx/NginxIntegrationTest.java       |   11 +-
 .../proxy/nginx/NginxLightIntegrationTest.java  |   16 +-
 .../proxy/nginx/NginxRebindIntegrationTest.java |   22 +-
 .../nginx/NginxRebindWithHaIntegrationTest.java |   36 +-
 .../nginx/NginxUrlMappingIntegrationTest.java   |   20 +-
 .../proxy/nginx/NginxWebClusterEc2LiveTest.java |   16 +-
 .../AbstractWebAppFixtureIntegrationTest.java   |   39 +-
 ...lledDynamicWebAppClusterIntegrationTest.java |   14 +-
 .../ControlledDynamicWebAppClusterTest.java     |   18 +-
 .../entity/webapp/DynamicWebAppClusterTest.java |   16 +-
 .../entity/webapp/DynamicWebAppFabricTest.java  |   18 +-
 .../webapp/ElasticCustomLocationTest.java       |   16 +-
 ...ElasticJavaWebAppServiceIntegrationTest.java |    8 +-
 .../entity/webapp/HttpsSslConfigTest.java       |    2 +-
 .../webapp/TomcatAutoScalerPolicyTest.java      |   12 +-
 .../webapp/WebAppConcurrentDeployTest.java      |   18 +-
 .../webapp/WebAppLiveIntegrationTest.groovy     |   29 +-
 ...namicWebAppClusterRebindIntegrationTest.java |   18 +-
 ...namicWebAppClusterRebindIntegrationTest.java |   16 +-
 .../jboss/JBoss6ServerAwsEc2LiveTest.java       |    5 +-
 ...Boss6ServerNonInheritingIntegrationTest.java |   10 +-
 .../jboss/JBoss7ServerAwsEc2LiveTest.java       |    5 +-
 .../jboss/JBoss7ServerDockerLiveTest.java       |    5 +-
 ...Boss7ServerNonInheritingIntegrationTest.java |   10 +-
 .../JBoss7ServerRebindingIntegrationTest.java   |   13 +-
 ...ultiVersionWebAppFixtureIntegrationTest.java |    9 +-
 .../Jboss7ServerGoogleComputeLiveTest.java      |    5 +-
 .../JettyWebAppFixtureIntegrationTest.java      |    9 +-
 .../webapp/nodejs/NodeJsWebAppEc2LiveTest.java  |    5 +-
 .../NodeJsWebAppFixtureIntegrationTest.java     |   15 +-
 .../NodeJsWebAppSimpleIntegrationTest.java      |   10 +-
 .../nodejs/NodeJsWebAppSoftlayerLiveTest.java   |    5 +-
 .../webapp/tomcat/Tomcat8ServerEc2LiveTest.java |    6 +-
 .../Tomcat8ServerRestartIntegrationTest.java    |    7 +-
 .../tomcat/Tomcat8ServerSoftlayerLiveTest.java  |    6 +-
 ...mcat8ServerWebAppFixtureIntegrationTest.java |   10 +-
 ...ableRetrieveUsageMetricsIntegrationTest.java |   10 +-
 .../webapp/tomcat/TomcatServerEc2LiveTest.java  |    5 +-
 .../TomcatServerRestartIntegrationTest.java     |    7 +-
 .../tomcat/TomcatServerSoftlayerLiveTest.java   |    5 +-
 ...omcatServerWebAppFixtureIntegrationTest.java |   10 +-
 .../test/entity/TestJavaWebAppEntity.java       |   21 +-
 .../test/entity/TestJavaWebAppEntityImpl.java   |    5 +-
 .../impl/hazelcast/EntityStreamSerializer.java  |    3 +-
 .../impl/hazelcast/HazelcastDataGrid.java       |    2 +-
 .../hazelcast/HazelcastDataGridFactory.java     |    2 +-
 .../impl/hazelcast/HazelcastStorageTest.java    |    4 +-
 .../app/ClusterWebServerDatabaseSample.java     |   36 +-
 .../sample/app/SingleWebServerSample.java       |   13 +-
 .../app/SampleLocalhostIntegrationTest.java     |   19 +-
 .../brooklyn/sample/app/SampleUnitTest.java     |   21 +-
 .../camp/brooklyn/BrooklynCampConstants.java    |    5 +-
 .../camp/brooklyn/BrooklynCampPlatform.java     |    6 +-
 .../BrooklynCampPlatformLauncherAbstract.java   |    4 +-
 .../camp/brooklyn/YamlLauncherAbstract.java     |   13 +-
 .../BrooklynAssemblyTemplateInstantiator.java   |   19 +-
 .../BrooklynComponentTemplateResolver.java      |   33 +-
 .../BrooklynEntityDecorationResolver.java       |   12 +-
 .../spi/creation/BrooklynEntityMatcher.java     |    6 +-
 .../creation/BrooklynYamlLocationResolver.java  |    2 +-
 .../creation/BrooklynYamlTypeInstantiator.java  |    4 +-
 .../spi/creation/EntitySpecConfiguration.java   |    2 +-
 .../service/BrooklynServiceTypeResolver.java    |    2 +-
 .../service/CatalogServiceTypeResolver.java     |   13 +-
 .../service/ChefServiceTypeResolver.java        |    7 +-
 .../service/JavaServiceTypeResolver.java        |    2 +-
 .../creation/service/ServiceTypeResolver.java   |    2 +-
 .../spi/dsl/BrooklynDslDeferredSupplier.java    |   13 +-
 .../camp/brooklyn/spi/dsl/DslUtils.java         |    2 +-
 .../spi/dsl/methods/BrooklynDslCommon.java      |   25 +-
 .../brooklyn/spi/dsl/methods/DslComponent.java  |   27 +-
 .../lookup/AbstractBrooklynResourceLookup.java  |    2 +-
 .../lookup/AbstractTemplateBrooklynLookup.java  |    4 +-
 .../spi/lookup/AssemblyBrooklynLookup.java      |    2 +-
 .../lookup/AssemblyTemplateBrooklynLookup.java  |    4 +-
 .../brooklyn/spi/lookup/BrooklynUrlLookup.java  |    5 +-
 .../lookup/PlatformComponentBrooklynLookup.java |    2 +-
 ...PlatformComponentTemplateBrooklynLookup.java |    4 +-
 .../platform/BrooklynImmutableCampPlatform.java |    2 +-
 .../camp/brooklyn/AbstractYamlRebindTest.java   |   21 +-
 .../camp/brooklyn/AbstractYamlTest.java         |   17 +-
 .../brooklyn/camp/brooklyn/AppYamlTest.java     |   19 +-
 .../camp/brooklyn/ApplicationsYamlTest.java     |    7 +-
 .../BrooklynYamlTypeInstantiatorTest.java       |    4 +-
 .../camp/brooklyn/ByonLocationsYamlTest.java    |   17 +-
 .../camp/brooklyn/DslAndRebindYamlTest.java     |   23 +-
 .../brooklyn/EmptySoftwareProcessYamlTest.java  |    8 +-
 .../EnrichersSlightlySimplerYamlTest.java       |   11 +-
 .../camp/brooklyn/EnrichersYamlTest.java        |   17 +-
 .../brooklyn/EntitiesYamlIntegrationTest.java   |    5 +-
 .../camp/brooklyn/EntitiesYamlTest.java         |   83 +-
 ...aWebAppWithDslYamlRebindIntegrationTest.java |   15 +-
 .../brooklyn/JavaWebAppsIntegrationTest.java    |   16 +-
 .../camp/brooklyn/JavaWebAppsMatchingTest.java  |   11 +-
 .../camp/brooklyn/LocationsYamlTest.java        |   34 +-
 .../camp/brooklyn/MapReferenceYamlTest.java     |    9 +-
 .../brooklyn/camp/brooklyn/ObjectsYamlTest.java |   21 +-
 .../camp/brooklyn/PoliciesYamlTest.java         |   13 +-
 .../camp/brooklyn/ReferencedYamlTest.java       |    7 +-
 .../brooklyn/ReferencingYamlTestEntity.java     |    5 +-
 .../brooklyn/ReferencingYamlTestEntityImpl.java |    2 +-
 .../brooklyn/ReloadBrooklynPropertiesTest.java  |    9 +-
 .../camp/brooklyn/TestEntityWithInitConfig.java |   11 +-
 .../brooklyn/TestEntityWithInitConfigImpl.java  |    3 +-
 .../camp/brooklyn/TestReferencingEnricher.java  |    5 +-
 .../camp/brooklyn/TestReferencingPolicy.java    |    5 +-
 .../TestSensorAndEffectorInitializer.java       |   19 +-
 .../brooklyn/VanillaBashNetcatYamlTest.java     |   19 +-
 .../brooklyn/camp/brooklyn/WrapAppTest.java     |   15 +-
 .../catalog/AbstractCatalogXmlTest.java         |   12 +-
 .../CatalogOsgiVersionMoreEntityTest.java       |    8 +-
 .../brooklyn/catalog/CatalogYamlCombiTest.java  |   10 +-
 .../brooklyn/catalog/CatalogYamlEntityTest.java |   14 +-
 .../catalog/CatalogYamlLocationTest.java        |    8 +-
 .../brooklyn/catalog/CatalogYamlPolicyTest.java |    6 +-
 .../brooklyn/catalog/CatalogYamlRebindTest.java |   13 +-
 .../catalog/CatalogYamlTemplateTest.java        |    4 +-
 .../catalog/CatalogYamlVersioningTest.java      |    7 +-
 .../camp/brooklyn/catalog/TestBasicApp.java     |    5 +-
 .../camp/brooklyn/catalog/TestBasicAppImpl.java |    2 +-
 .../test/resources/same-server-entity-test.yaml |    6 +-
 .../test/resources/test-app-with-enricher.yaml  |    4 +-
 ...est-app-with-enrichers-slightly-simpler.yaml |   20 +-
 .../test-cluster-with-member-spec.yaml          |    6 +-
 .../resources/test-entity-basic-template.yaml   |    2 +-
 .../test-entity-reference-map-template.yaml     |    2 +-
 .../resources/test-entity-with-enricher.yaml    |    2 +-
 .../resources/test-entity-with-init-config.yaml |    2 +-
 .../test/resources/test-entity-with-policy.yaml |    2 +-
 .../resources/test-propagating-enricher.yaml    |    4 +-
 .../test-webapp-with-averaging-enricher.yaml    |    4 +-
 .../org/apache/brooklyn/cli/AbstractMain.java   |    4 +-
 .../org/apache/brooklyn/cli/CloudExplorer.java  |    4 +-
 .../org/apache/brooklyn/cli/ItemLister.java     |   10 +-
 .../main/java/org/apache/brooklyn/cli/Main.java |   37 +-
 .../apache/brooklyn/cli/lister/ClassFinder.java |   19 +-
 .../brooklyn/cli/lister/ItemDescriptors.java    |   16 +-
 .../main/resources/brooklyn/default.catalog.bom |   31 +-
 .../java/org/apache/brooklyn/cli/CliTest.java   |   24 +-
 .../src/test/resources/ExampleAppInFile.groovy  |    3 +-
 .../brooklyn/cli/BaseCliIntegrationTest.java    |    2 +-
 .../main/webapp/assets/js/view/script-groovy.js |    2 +-
 .../BrooklynJavascriptGuiLauncherTest.java      |    8 +-
 .../specs/model/catalog-application-spec.js     |    8 +-
 .../specs/model/sensor-summary-spec.js          |    2 +-
 .../brooklyn/launcher/BrooklynLauncher.java     |   69 +-
 .../launcher/BrooklynServerDetails.java         |    2 +-
 .../brooklyn/launcher/BrooklynWebServer.java    |   29 +-
 .../camp/BrooklynCampPlatformLauncher.java      |    7 +-
 .../config/BrooklynDevelopmentModes.java        |    3 +-
 .../launcher/config/BrooklynGlobalConfig.java   |    7 +-
 .../launcher/config/CustomResourceLocator.java  |    5 +-
 .../entity/basic/VanillaSoftwareYamlTest.java   |    8 +-
 .../BrooklynEntityMirrorIntegrationTest.java    |   20 +-
 .../brooklynnode/BrooklynNodeRestTest.java      |   33 +-
 .../database/mssql/MssqlBlueprintLiveTest.java  |    4 +-
 .../BrooklynLauncherHighAvailabilityTest.java   |   21 +-
 .../BrooklynLauncherRebindCatalogTest.java      |    7 +-
 .../BrooklynLauncherRebindTestFixture.java      |   25 +-
 .../BrooklynLauncherRebindTestToFiles.java      |   19 +-
 ...lynLauncherRebindToCloudObjectStoreTest.java |   23 +-
 .../brooklyn/launcher/BrooklynLauncherTest.java |   30 +-
 .../launcher/BrooklynWebServerTest.java         |   14 +-
 .../launcher/SimpleYamlLauncherForTests.java    |    4 +-
 .../brooklyn/launcher/WebAppRunnerTest.java     |    9 +-
 .../blueprints/AbstractBlueprintTest.java       |   22 +-
 .../resources/rebind-test-catalog-additions.bom |    4 +-
 .../src/test/resources/rebind-test-catalog.bom  |    4 +-
 .../qa/load/SimulatedJBoss7ServerImpl.java      |   17 +-
 .../qa/load/SimulatedMySqlNodeImpl.java         |   15 +-
 .../qa/load/SimulatedNginxControllerImpl.java   |   17 +-
 .../brooklyn/qa/load/SimulatedTheeTierApp.java  |   29 +-
 .../brooklyn/qa/longevity/MonitorUtils.java     |    4 +-
 .../SoftlayerObtainPrivateLiveTest.java         |   27 +-
 .../org/apache/brooklyn/qa/load/LoadTest.java   |   17 +-
 .../webcluster/SinusoidalLoadGenerator.java     |    9 +-
 .../qa/longevity/webcluster/WebClusterApp.java  |   19 +-
 .../org/apache/brooklyn/rest/api/ServerApi.java |    4 +-
 .../rest/domain/SummaryComparators.java         |    2 +-
 .../fixtures/catalog-application-list.json      |    6 +-
 .../resources/fixtures/catalog-application.json |    2 +-
 .../resources/fixtures/sensor-summary-list.json |    2 +-
 .../ApplicationResourceIntegrationTest.java     |   12 +-
 .../rest/client/BrooklynApiRestClientTest.java  |   14 +-
 .../apache/brooklyn/rest/BrooklynWebConfig.java |    3 +-
 .../BrooklynPropertiesSecurityFilter.java       |    8 +-
 .../rest/filter/HaHotCheckResourceFilter.java   |    4 +-
 .../rest/filter/HaMasterCheckFilter.java        |    6 +-
 .../brooklyn/rest/filter/LoggingFilter.java     |    2 +-
 .../resources/AbstractBrooklynRestResource.java |   12 +-
 .../brooklyn/rest/resources/AccessResource.java |    4 +-
 .../rest/resources/ActivityResource.java        |    9 +-
 .../rest/resources/ApplicationResource.java     |   35 +-
 .../rest/resources/CatalogResource.java         |    8 +-
 .../rest/resources/EffectorResource.java        |   12 +-
 .../rest/resources/EntityConfigResource.java    |   16 +-
 .../brooklyn/rest/resources/EntityResource.java |   22 +-
 .../rest/resources/LocationResource.java        |    2 +-
 .../rest/resources/PolicyConfigResource.java    |    8 +-
 .../brooklyn/rest/resources/PolicyResource.java |    4 +-
 .../brooklyn/rest/resources/SensorResource.java |   16 +-
 .../brooklyn/rest/resources/ServerResource.java |   47 +-
 .../brooklyn/rest/resources/UsageResource.java  |   12 +-
 .../rest/resources/VersionResource.java         |    2 +-
 ...nUserWithRandomPasswordSecurityProvider.java |    2 +-
 .../provider/DelegatingSecurityProvider.java    |    2 +-
 .../provider/ExplicitUsersSecurityProvider.java |    4 +-
 .../security/provider/LdapSecurityProvider.java |    2 +-
 .../rest/transform/AccessTransformer.java       |    2 +-
 .../rest/transform/ApplicationTransformer.java  |    7 +-
 .../transform/BrooklynFeatureTransformer.java   |    2 +-
 .../rest/transform/CatalogTransformer.java      |   12 +-
 .../rest/transform/EffectorTransformer.java     |   10 +-
 .../rest/transform/EntityTransformer.java       |    2 +-
 .../transform/HighAvailabilityTransformer.java  |    4 +-
 .../rest/transform/LocationTransformer.java     |   14 +-
 .../rest/transform/PolicyTransformer.java       |    4 +-
 .../rest/transform/SensorTransformer.java       |    4 +-
 .../rest/transform/TaskTransformer.java         |   12 +-
 .../rest/util/BrooklynRestResourceUtils.java    |   58 +-
 .../rest/util/DefaultExceptionMapper.java       |    4 +-
 .../brooklyn/rest/util/EntityLocationUtils.java |    4 +-
 .../rest/util/ManagementContextProvider.java    |    2 +-
 .../rest/util/json/BidiSerialization.java       |    4 +-
 .../util/json/BrooklynJacksonJsonProvider.java  |   11 +-
 .../src/main/resources/reset-catalog.xml        |    6 +-
 .../BrooklynPropertiesSecurityFilterTest.java   |    4 +-
 .../brooklyn/rest/BrooklynRestApiLauncher.java  |   12 +-
 .../BrooklynRestApiLauncherTestFixture.java     |   14 +-
 .../apache/brooklyn/rest/HaHotCheckTest.java    |   10 +-
 .../brooklyn/rest/HaMasterCheckFilterTest.java  |   22 +-
 .../brooklyn/rest/domain/ApplicationTest.java   |    7 +-
 .../brooklyn/rest/domain/SensorSummaryTest.java |   18 +-
 .../ApplicationResourceIntegrationTest.java     |    4 +-
 .../rest/resources/ApplicationResourceTest.java |   23 +-
 .../rest/resources/CatalogResetTest.java        |   11 +-
 .../rest/resources/CatalogResourceTest.java     |   22 +-
 .../rest/resources/DescendantsTest.java         |    6 +-
 .../resources/EntityConfigResourceTest.java     |    6 +-
 .../rest/resources/EntityResourceTest.java      |    9 +-
 .../rest/resources/LocationResourceTest.java    |    2 +-
 .../rest/resources/ScriptResourceTest.java      |    6 +-
 .../SensorResourceIntegrationTest.java          |   17 +-
 .../rest/resources/SensorResourceTest.java      |    9 +-
 .../ServerResourceIntegrationTest.java          |   14 +-
 .../rest/resources/ServerResourceTest.java      |   17 +-
 .../rest/resources/ServerShutdownTest.java      |   19 +-
 .../rest/resources/UsageResourceTest.java       |   20 +-
 .../brooklynnode/DeployBlueprintTest.java       |   15 +-
 .../rest/testing/BrooklynRestApiTest.java       |   13 +-
 .../rest/testing/BrooklynRestResourceTest.java  |    4 +-
 .../rest/testing/mocks/CapitalizePolicy.java    |    4 +-
 .../rest/testing/mocks/EverythingGroup.java     |    2 +-
 .../rest/testing/mocks/EverythingGroupImpl.java |    2 +-
 .../rest/testing/mocks/NameMatcherGroup.java    |    5 +-
 .../testing/mocks/NameMatcherGroupImpl.java     |    5 +-
 .../rest/testing/mocks/RestMockApp.java         |    2 +-
 .../rest/testing/mocks/RestMockAppBuilder.java  |    7 +-
 .../testing/mocks/RestMockSimpleEntity.java     |   24 +-
 .../testing/mocks/RestMockSimplePolicy.java     |    7 +-
 .../util/BrooklynRestResourceUtilsTest.java     |   20 +-
 .../rest/util/EntityLocationUtilsTest.java      |   14 +-
 .../json/BrooklynJacksonSerializerTest.java     |   18 +-
 .../apache/brooklyn/test/EntityTestUtils.java   |   10 +-
 .../org/apache/brooklyn/test/TestUtils.groovy   |   47 +-
 .../util/jmx/jmxmp/JmxmpAgentSslTest.java       |    4 +-
 .../brooklyn/util/jmx/jmxmp/JmxmpClient.java    |    2 +-
 .../test/osgi/entities/SimpleApplication.java   |    5 +-
 .../osgi/entities/SimpleApplicationImpl.java    |    4 +-
 .../test/osgi/entities/SimpleEntity.java        |    2 +-
 .../test/osgi/entities/SimpleEntityImpl.java    |    2 +-
 .../test/osgi/entities/SimpleLocation.java      |    7 +-
 .../test/osgi/entities/SimplePolicy.java        |    7 +-
 .../test/osgi/entities/more/MoreEntity.java     |    8 +-
 .../test/osgi/entities/more/MoreEntityImpl.java |    8 +-
 .../test/osgi/entities/more/MoreLocation.java   |    3 +-
 .../test/osgi/entities/more/MorePolicy.java     |    4 +-
 .../test/osgi/entities/more/MoreTemplate.java   |    9 +-
 .../test/osgi/entities/more/MoreEntity.java     |    6 +-
 .../test/osgi/entities/more/MoreEntityImpl.java |    7 +-
 .../test/osgi/entities/more/MoreEntity.java     |    6 +-
 .../test/osgi/entities/more/MoreEntityImpl.java |    7 +-
 .../test/osgi/entities/more/MoreLocation.java   |    2 +-
 .../test/osgi/entities/more/MorePolicy.java     |    2 +-
 .../test/osgi/entities/more/MoreTemplate.java   |    7 +-
 2848 files changed, 170373 insertions(+), 171430 deletions(-)
----------------------------------------------------------------------



[10/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply org.apache package prefix to software-base, tidying package names, and moving a few sensory things to core

Posted by he...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/AbstractChefToyMySqlEntityLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/AbstractChefToyMySqlEntityLiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/AbstractChefToyMySqlEntityLiveTest.java
new file mode 100644
index 0000000..3250ee3
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/AbstractChefToyMySqlEntityLiveTest.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef.mysql;
+
+import org.testng.annotations.Test;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.entity.chef.ChefLiveTestSupport;
+import org.apache.brooklyn.entity.software.base.test.mysql.AbstractToyMySqlEntityTest;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+public abstract class AbstractChefToyMySqlEntityLiveTest extends AbstractToyMySqlEntityTest {
+
+    @Override
+    // mark as live here
+    @Test(groups = "Live")
+    public void testMySqlOnProvisioningLocation() throws Exception {
+        super.testMySqlOnProvisioningLocation();
+    }
+    
+    protected MachineProvisioningLocation<? extends SshMachineLocation> createLocation() {
+        return ChefLiveTestSupport.createLocation(mgmt);
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/ChefSoloDriverMySqlEntityLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/ChefSoloDriverMySqlEntityLiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/ChefSoloDriverMySqlEntityLiveTest.java
new file mode 100644
index 0000000..e6c7b27
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/ChefSoloDriverMySqlEntityLiveTest.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef.mysql;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
+import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper;
+import org.testng.annotations.Test;
+
+public class ChefSoloDriverMySqlEntityLiveTest extends AbstractChefToyMySqlEntityLiveTest {
+
+    // test here just so Eclipse IDE picks it up
+    @Override @Test(groups="Live")
+    public void testMySqlOnProvisioningLocation() throws Exception {
+        super.testMySqlOnProvisioningLocation();
+    }
+
+    @Override
+    protected Integer getPid(Entity mysql) {
+        ProcessTaskWrapper<Integer> t = Entities.submit(mysql, SshEffectorTasks.ssh("sudo cat "+ChefSoloDriverToyMySqlEntity.PID_FILE));
+        return Integer.parseInt(t.block().getStdout().trim());
+    }
+    
+    @Override
+    protected Entity createMysql() {
+        return app.createAndManageChild(EntitySpec.create(Entity.class, ChefSoloDriverToyMySqlEntity.class).
+                additionalInterfaces(SoftwareProcess.class));
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/ChefSoloDriverToyMySqlEntity.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/ChefSoloDriverToyMySqlEntity.java b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/ChefSoloDriverToyMySqlEntity.java
new file mode 100644
index 0000000..c36dc21
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/ChefSoloDriverToyMySqlEntity.java
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef.mysql;
+
+import org.apache.brooklyn.api.mgmt.TaskAdaptable;
+import org.apache.brooklyn.api.mgmt.TaskFactory;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.entity.chef.ChefConfig;
+import org.apache.brooklyn.entity.chef.ChefConfigs;
+import org.apache.brooklyn.entity.chef.ChefSoloDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
+import org.apache.brooklyn.sensor.feed.ssh.SshFeed;
+import org.apache.brooklyn.sensor.feed.ssh.SshPollConfig;
+import org.apache.brooklyn.sensor.ssh.SshEffectorTasks;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.time.Duration;
+
+@Deprecated /** @deprecated since 0.7.0 use see examples {Dynamic,Typed}ToyMySqlEntityChef */
+public class ChefSoloDriverToyMySqlEntity extends SoftwareProcessImpl implements ChefConfig {
+
+    public static final String PID_FILE = "/var/run/mysqld/mysqld.pid";
+    public static final ConfigKey<TaskFactory<? extends TaskAdaptable<Boolean>>> IS_RUNNING_TASK =
+            ConfigKeys.newConfigKeyWithDefault(ChefSoloDriver.IS_RUNNING_TASK, 
+            SshEffectorTasks.isPidFromFileRunning(PID_FILE).runAsRoot());
+
+    public static final ConfigKey<TaskFactory<?>> STOP_TASK =
+            ConfigKeys.newConfigKeyWithDefault(ChefSoloDriver.STOP_TASK, 
+            SshEffectorTasks.ssh("/etc/init.d/mysql stop").allowingNonZeroExitCode().runAsRoot());
+
+    private SshFeed upFeed;
+    
+    @Override
+    public Class<?> getDriverInterface() {
+        return ChefSoloDriver.class;
+    }
+
+    @Override
+    protected void connectSensors() {
+        super.connectSensors();
+        
+        // TODO have a TaskFactoryFeed which reuses the IS_RUNNING_TASK
+        upFeed = SshFeed.builder().entity(this).period(Duration.FIVE_SECONDS.toMilliseconds())
+            .poll(new SshPollConfig<Boolean>(SERVICE_UP)
+                    .command("ps -p `sudo cat /var/run/mysqld/mysqld.pid`")
+                    .setOnSuccess(true).setOnFailureOrException(false))
+            .build();
+    }
+    
+    @Override
+    protected void disconnectSensors() {
+        // TODO nicer way to disconnect
+        if (upFeed != null) upFeed.stop();
+        super.disconnectSensors();
+    }
+    
+    @Override
+    public void init() {
+        super.init();
+        ChefConfigs.addToLaunchRunList(this, "mysql::server");
+        ChefConfigs.addToCookbooksFromGithub(this, "mysql", "build-essential", "openssl");
+        ChefConfigs.setLaunchAttribute(this, "mysql",  
+                MutableMap.of()
+                    .add("server_root_password", "MyPassword")
+                    .add("server_debian_password", "MyPassword")
+                    .add("server_repl_password", "MyPassword")
+                );
+        
+        // TODO other attributes, eg:
+        // node['mysql']['port']
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/DynamicChefAutodetectToyMySqlEntityLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/DynamicChefAutodetectToyMySqlEntityLiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/DynamicChefAutodetectToyMySqlEntityLiveTest.java
new file mode 100644
index 0000000..0102f6e
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/DynamicChefAutodetectToyMySqlEntityLiveTest.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef.mysql;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+
+public class DynamicChefAutodetectToyMySqlEntityLiveTest extends AbstractChefToyMySqlEntityLiveTest {
+
+    private static final Logger log = LoggerFactory.getLogger(DynamicChefAutodetectToyMySqlEntityLiveTest.class);
+    
+    // test here just so Eclipse IDE picks it up
+    @Override @Test(groups="Live")
+    public void testMySqlOnProvisioningLocation() throws Exception {
+        super.testMySqlOnProvisioningLocation();
+    }
+    
+    @Override
+    protected Entity createMysql() {
+        Entity mysql = app.createAndManageChild(DynamicToyMySqlEntityChef.spec());
+        log.debug("created "+mysql);
+        return mysql;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/DynamicChefServerToyMySqlEntityLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/DynamicChefServerToyMySqlEntityLiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/DynamicChefServerToyMySqlEntityLiveTest.java
new file mode 100644
index 0000000..566a96e
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/DynamicChefServerToyMySqlEntityLiveTest.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef.mysql;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.entity.chef.ChefLiveTestSupport;
+import org.apache.brooklyn.entity.chef.ChefServerTasksIntegrationTest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+
+/** Expects knife on the path, but will use Brooklyn registered account,
+ * and that account has the mysql recipe installed.
+ * <p>
+ * See {@link ChefServerTasksIntegrationTest} for more info. */
+public class DynamicChefServerToyMySqlEntityLiveTest extends AbstractChefToyMySqlEntityLiveTest {
+
+    private static final Logger log = LoggerFactory.getLogger(DynamicChefServerToyMySqlEntityLiveTest.class);
+    
+    // test here just so Eclipse IDE picks it up
+    @Override @Test(groups="Live")
+    public void testMySqlOnProvisioningLocation() throws Exception {
+        super.testMySqlOnProvisioningLocation();
+    }
+    
+    @Override
+    protected Entity createMysql() {
+        ChefLiveTestSupport.installBrooklynChefHostedConfig(app);
+        Entity mysql = app.createAndManageChild(DynamicToyMySqlEntityChef.specKnife());
+        log.debug("created "+mysql);
+        return mysql;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/DynamicChefSoloToyMySqlEntityLiveTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/DynamicChefSoloToyMySqlEntityLiveTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/DynamicChefSoloToyMySqlEntityLiveTest.java
new file mode 100644
index 0000000..ba6c6d9
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/DynamicChefSoloToyMySqlEntityLiveTest.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef.mysql;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+
+public class DynamicChefSoloToyMySqlEntityLiveTest extends AbstractChefToyMySqlEntityLiveTest {
+
+    private static final Logger log = LoggerFactory.getLogger(DynamicChefSoloToyMySqlEntityLiveTest.class);
+    
+    // test here just so Eclipse IDE picks it up
+    @Override @Test(groups="Live")
+    public void testMySqlOnProvisioningLocation() throws Exception {
+        super.testMySqlOnProvisioningLocation();
+    }
+    
+    @Override
+    protected Entity createMysql() {
+        Entity mysql = app.createAndManageChild(DynamicToyMySqlEntityChef.specSolo());
+        log.debug("created "+mysql);
+        return mysql;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/DynamicToyMySqlEntityChef.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/DynamicToyMySqlEntityChef.java b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/DynamicToyMySqlEntityChef.java
new file mode 100644
index 0000000..2edd8a1
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/DynamicToyMySqlEntityChef.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef.mysql;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.entity.chef.ChefConfig;
+import org.apache.brooklyn.entity.chef.ChefConfigs;
+import org.apache.brooklyn.entity.chef.ChefEntity;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Builds up a MySql entity via chef using specs only */
+public class DynamicToyMySqlEntityChef implements ChefConfig {
+
+    private static final Logger log = LoggerFactory.getLogger(DynamicToyMySqlEntityChef.class);
+
+    protected static EntitySpec<? extends Entity> specBase() {
+        EntitySpec<ChefEntity> spec = EntitySpec.create(ChefEntity.class);
+        
+        ChefConfigs.addToLaunchRunList(spec, "mysql::server");
+        spec.configure(PID_FILE, "/var/run/mysqld/mysql*.pid");
+        // init.d service name is sometimes mysql, sometimes mysqld, depending ubuntu/centos
+        // we use pid file above instead, but this (with the right name) could be used:
+//        spec.configure(SERVICE_NAME, "mysql");
+        
+        // chef mysql fails on first run but works on second if switching between server and solo modes
+        spec.configure(ChefConfig.CHEF_RUN_CONVERGE_TWICE, true);
+
+        // only used for solo, but safely ignored for knife
+        ChefConfigs.addToCookbooksFromGithub(spec, "mysql", "build-essential", "openssl");
+        // we always need dependent cookbooks set, and mysql requires password set
+        // (TODO for knife we might wish to prefer things from the server)
+        ChefConfigs.addLaunchAttributes(spec, MutableMap.of("mysql",  
+                MutableMap.of()
+                .add("server_root_password", "MyPassword")
+                .add("server_debian_password", "MyPassword")
+                .add("server_repl_password", "MyPassword")
+            ));
+        
+        return spec;
+    }
+
+    public static EntitySpec<? extends Entity> spec() {
+        EntitySpec<? extends Entity> spec = specBase();
+        log.debug("Created entity spec for MySql: "+spec);
+        return spec;
+    }
+
+    public static EntitySpec<? extends Entity> specSolo() {
+        EntitySpec<? extends Entity> spec = specBase();
+        spec.configure(ChefConfig.CHEF_MODE, ChefConfig.ChefModes.SOLO);
+        log.debug("Created entity spec for MySql: "+spec);
+        return spec;
+    }
+
+    public static EntitySpec<? extends Entity> specKnife() {
+        EntitySpec<? extends Entity> spec = specBase();
+        spec.configure(ChefConfig.CHEF_MODE, ChefConfig.ChefModes.KNIFE);
+        log.debug("Created entity spec for MySql: "+spec);
+        return spec;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/TypedToyMySqlEntityChef.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/TypedToyMySqlEntityChef.java b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/TypedToyMySqlEntityChef.java
new file mode 100644
index 0000000..44a622a
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/chef/mysql/TypedToyMySqlEntityChef.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.chef.mysql;
+
+import org.apache.brooklyn.entity.chef.ChefConfig;
+import org.apache.brooklyn.entity.chef.ChefEntityImpl;
+import org.apache.brooklyn.util.git.GithubUrls;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+
+/** Illustrates how to define an entity using Java as a Java class, extending ChefEntityImpl */
+public class TypedToyMySqlEntityChef extends ChefEntityImpl {
+
+    @Override
+    public void init() {
+        super.init();
+
+        String password = "p4ssw0rd";
+        
+        setConfig(CHEF_COOKBOOK_PRIMARY_NAME, "mysql");
+        setConfig(CHEF_COOKBOOK_URLS, ImmutableMap.of(
+            "mysql", GithubUrls.tgz("opscode-cookbooks", "mysql", "v4.0.12"),
+            "openssl", GithubUrls.tgz("opscode-cookbooks", "openssl", "v1.1.0"),
+            "mysql", GithubUrls.tgz("opscode-cookbooks", "build-essential", "v1.4.4")));
+        
+        setConfig(CHEF_LAUNCH_RUN_LIST, ImmutableSet.of("mysql::server"));
+        setConfig(CHEF_LAUNCH_ATTRIBUTES, ImmutableMap.<String,Object>of(
+            "mysql", ImmutableMap.of(
+                "server_root_password", password,
+                "server_repl_password", password,
+                "server_debian_password", password)));
+        
+        setConfig(ChefConfig.PID_FILE, "/var/run/mysqld/mysqld.pid");
+        
+        setConfig(CHEF_MODE, ChefModes.SOLO);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/java/EntityPollingTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/java/EntityPollingTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/java/EntityPollingTest.java
new file mode 100644
index 0000000..b49e235
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/java/EntityPollingTest.java
@@ -0,0 +1,206 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.entity.java.VanillaJavaAppImpl;
+import org.apache.brooklyn.entity.java.VanillaJavaAppSshDriver;
+import org.apache.brooklyn.entity.java.UsesJmx.JmxAgentModes;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.test.jmx.JmxService;
+import org.apache.brooklyn.sensor.core.BasicAttributeSensor;
+import org.apache.brooklyn.sensor.feed.jmx.JmxAttributePollConfig;
+import org.apache.brooklyn.sensor.feed.jmx.JmxFeed;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+public class EntityPollingTest {
+
+    private static final Logger LOG = LoggerFactory.getLogger(EntityPollingTest.class);
+
+    private JmxService jmxService;
+    private TestApplication app;
+    private SoftwareProcess entity;
+    
+    private static final BasicAttributeSensor<String> stringAttribute = new BasicAttributeSensor<String>(
+            String.class, "brooklyn.test.stringAttribute", "Brooklyn testing int attribute");
+    private String objectName = "Brooklyn:type=MyTestMBean,name=myname";
+    
+    private static final ObjectName jmxObjectName;
+    static {
+        try {
+            jmxObjectName = new ObjectName("Brooklyn:type=MyTestMBean,name=myname");
+        } catch (MalformedObjectNameException e) {
+            throw Exceptions.propagate(e);
+        }
+    }
+
+    private static final String attributeName = "myattrib";
+
+    public static class SubVanillaJavaApp extends VanillaJavaAppImpl {
+        private JmxFeed feed;
+        
+        @Override protected void connectSensors() {
+            super.connectSensors();
+   
+            // Add a sensor that we can explicitly set in jmx
+            feed = JmxFeed.builder()
+                .entity(this)
+                .pollAttribute(new JmxAttributePollConfig<String>(stringAttribute)
+                    .objectName(jmxObjectName)
+                    .attributeName(attributeName))
+                .build();
+        }
+
+        @Override
+        public void disconnectSensors() {
+            super.disconnectSensors();
+            if (feed != null) feed.stop();
+        }
+        
+        @SuppressWarnings({ "rawtypes", "unchecked" })
+        @Override
+        public Class getDriverInterface() {
+            return null;
+        }
+
+        @Override
+        public VanillaJavaAppSshDriver newDriver(MachineLocation loc) {
+            return new VanillaJavaAppSshDriver(this, (SshMachineLocation)loc) {
+                @Override public void install() {
+                    // no-op
+                }
+                @Override public void customize() {
+                    // no-op
+                }
+                @Override public void launch() {
+                    // no-op
+                }
+                @Override public boolean isRunning() {
+                    return true;
+                }
+                @Override public void stop() {
+                    // no-op
+                }
+                @Override public void kill() {
+                    // no-op
+                }
+            };
+        }
+    };        
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() {
+        app = TestApplication.Factory.newManagedInstanceForTests();
+        
+        /*
+         * Create an entity, using real entity code, but that swaps out the external process
+         * for a JmxService that we can control in the test.        
+         */
+        entity = app.createAndManageChild(EntitySpec.create(SoftwareProcess.class).impl(SubVanillaJavaApp.class)
+                .configure("rmiRegistryPort", 40123)
+                .configure("mxbeanStatsEnabled", false)
+                .configure(UsesJmx.JMX_AGENT_MODE, JmxAgentModes.JMX_RMI_CUSTOM_AGENT));
+    }
+
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        if (app != null) Entities.destroyAll(app.getManagementContext());
+        if (jmxService != null) jmxService.shutdown();
+    }
+
+    // Tests that the happy path works
+    @Test(groups="Integration")
+    public void testSimpleConnection() throws Exception {
+        jmxService = new JmxService("localhost", 40123);
+        jmxService.registerMBean(ImmutableMap.of(attributeName, "myval"), objectName);
+
+        app.start(ImmutableList.of(new SshMachineLocation(MutableMap.of("address", "localhost"))));
+        
+        // Starts with value defined when registering...
+        EntityTestUtils.assertAttributeEqualsEventually(entity, stringAttribute, "myval");
+    }
+
+    // Test that connect will keep retrying (e.g. start script returns before the JMX server is up)
+    @Test(groups="Integration")
+    public void testEntityWithDelayedJmxStartupWillKeepRetrying() {
+        // In 2 seconds time, we'll start the JMX server
+        Thread t = new Thread(new Runnable() {
+            public void run() {
+                try {
+                    Thread.sleep(2000);
+                    jmxService = new JmxService("localhost", 40123);
+                    jmxService.registerMBean(ImmutableMap.of(attributeName, "myval"), objectName);
+                } catch (Exception e) {
+                    LOG.error("Error in testEntityWithDelayedJmxStartupWillKeepRetrying", e);
+                    throw Exceptions.propagate(e);
+                }
+            }});
+
+        try {
+            t.start();
+            app.start(ImmutableList.of(new SshMachineLocation(MutableMap.of("address", "localhost"))));
+
+            EntityTestUtils.assertAttributeEqualsEventually(entity, stringAttribute, "myval");
+            
+        } finally {
+            t.interrupt();
+        }
+    }
+    
+    @Test(groups="Integration")
+    public void testJmxConnectionGoesDownRequiringReconnect() throws Exception {
+        jmxService = new JmxService("localhost", 40123);
+        jmxService.registerMBean(ImmutableMap.of(attributeName, "myval"), objectName);
+
+        app.start(ImmutableList.of(new SshMachineLocation(MutableMap.of("address", "localhost"))));
+        
+        EntityTestUtils.assertAttributeEqualsEventually(entity, stringAttribute, "myval");
+        
+        // Shutdown the MBeanServer - simulates network failure so can't connect
+        jmxService.shutdown();
+        
+        // TODO Want a better way of determining that the entity is down; ideally should have 
+        // sensor for entity-down that's wired up to a JMX attribute?
+        Thread.sleep(5000);
+
+        // Restart MBeanServer, and set attribute to different value; expect it to be polled again
+        jmxService = new JmxService("localhost", 40123);
+        jmxService.registerMBean(ImmutableMap.of(attributeName, "myval2"), objectName);
+        
+        EntityTestUtils.assertAttributeEqualsEventually(entity, stringAttribute, "myval2");
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/java/ExampleVanillaMain.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/java/ExampleVanillaMain.java b/software/base/src/test/java/org/apache/brooklyn/entity/java/ExampleVanillaMain.java
new file mode 100644
index 0000000..114d45d
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/java/ExampleVanillaMain.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+public class ExampleVanillaMain {
+    public static void main(String[] args) throws Exception {
+        System.out.println("In VanillaJavaExampleMain.main");
+        Thread.sleep(100*1000);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/java/ExampleVanillaMainCpuHungry.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/java/ExampleVanillaMainCpuHungry.java b/software/base/src/test/java/org/apache/brooklyn/entity/java/ExampleVanillaMainCpuHungry.java
new file mode 100644
index 0000000..e45be44
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/java/ExampleVanillaMainCpuHungry.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+public class ExampleVanillaMainCpuHungry {
+    private static final int MAX_TIME_MILLIS = 100*1000;
+    private static final int CALCULATIONS_PER_CYCLE = 100000;
+    private static final int SLEEP_PER_CYCLE_MILLIS = 1;
+    
+    public static void main(String[] args) throws Exception {
+        System.out.println("In ExampleVanillaMainCpuHungry.main");
+        long startTime = System.currentTimeMillis();
+        long count = 0;
+        double total = 0;
+        do {
+            for (int i = 0; i < CALCULATIONS_PER_CYCLE; i++) {
+                total += Math.sqrt(Math.random());
+                count++;
+            }
+            Thread.sleep(SLEEP_PER_CYCLE_MILLIS);
+        } while ((System.currentTimeMillis() - startTime) < MAX_TIME_MILLIS);
+        
+        System.out.println("Did "+count+" random square roots, took "+(System.currentTimeMillis()-startTime)+"ms; total = "+total);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaOptsTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaOptsTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaOptsTest.java
new file mode 100644
index 0000000..a9da253
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaOptsTest.java
@@ -0,0 +1,361 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import static org.testng.Assert.fail;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.entity.java.UsesJmx;
+import org.apache.brooklyn.entity.java.VanillaJavaApp;
+import org.apache.brooklyn.entity.java.VanillaJavaAppImpl;
+import org.apache.brooklyn.entity.java.VanillaJavaAppSshDriver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.collections.MutableSet;
+import org.apache.brooklyn.util.core.internal.ssh.RecordingSshTool;
+import org.apache.brooklyn.util.core.internal.ssh.SshTool;
+import org.apache.brooklyn.util.core.internal.ssh.RecordingSshTool.ExecCmd;
+import org.apache.brooklyn.util.jmx.jmxmp.JmxmpAgent;
+import org.apache.brooklyn.util.text.Strings;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.MapDifference.ValueDifference;
+import com.google.common.collect.Maps;
+
+@SuppressWarnings({ "rawtypes", "unchecked" })
+public class JavaOptsTest extends BrooklynAppUnitTestSupport {
+
+    // TODO Test setting classpath; but this works by customize() copying all the artifacts into /lib/*
+    // so that we can simply set this on the classpath...
+    
+    private static final Logger log = LoggerFactory.getLogger(JavaOptsTest.class);
+    
+    private SshMachineLocation loc;
+    
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        RecordingSshTool.execScriptCmds.clear();
+        super.setUp();
+        loc = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure("address", "localhost")
+                .configure(SshTool.PROP_TOOL_CLASS, RecordingSshTool.class.getName()));
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    @Override
+    public void tearDown() throws Exception {
+        super.tearDown();
+        RecordingSshTool.execScriptCmds.clear();
+    }
+    
+    @Test
+    public void testSimpleLaunchesJavaProcess() {
+        VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
+            .configure("main", "my.Main").configure("useJmx", false));
+        app.start(ImmutableList.of(loc));
+        
+        String runDir = javaProcess.getRunDir();
+        Map<String,String> expectedEnvs = ImmutableMap.<String,String>of();
+        List<String> expectedCmds = ImmutableList.of(String.format("java $JAVA_OPTS -cp \"%1$s/lib\" my.Main  >> %1$s/console 2>&1 </dev/null &", runDir));
+        
+        assertHasExpectedCmds(expectedCmds, expectedEnvs);
+    }
+    
+    @Test
+    public void testPassesJavaArgs() {
+        VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
+            .configure("main", "my.Main").configure("useJmx", false).configure("args", ImmutableList.of("a1", "a2")));
+        app.start(ImmutableList.of(loc));
+        
+        String runDir = javaProcess.getRunDir();
+        Map<String,String> expectedEnvs = ImmutableMap.<String,String>of();
+        List<String> expectedCmds = ImmutableList.of(String.format("java $JAVA_OPTS -cp \"%1$s/lib\" my.Main \"a1\" \"a2\" >> %1$s/console 2>&1 </dev/null &", runDir));
+        
+        assertHasExpectedCmds(expectedCmds, expectedEnvs);
+    }
+    
+    @Test
+    public void testPassesJavaOpts() {
+        VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
+            .configure("main", "my.Main").configure("useJmx", false).configure("javaOpts", ImmutableList.of("-abc")));
+        app.start(ImmutableList.of(loc));
+        
+        String runDir = javaProcess.getRunDir();
+        String defaultJavaOpts = "-Xms128m -Xmx512m -XX:MaxPermSize=512m";
+        String expectedJavaOpts = defaultJavaOpts+" -abc";
+        Map<String,String> expectedEnvs = ImmutableMap.<String,String>of("JAVA_OPTS", expectedJavaOpts);
+        List<String> expectedCmds = ImmutableList.of(String.format("java $JAVA_OPTS -cp \"%1$s/lib\" my.Main  >> %1$s/console 2>&1 </dev/null &", runDir));
+        
+        assertHasExpectedCmds(expectedCmds, expectedEnvs);
+    }
+
+    @Test
+    public void testPassesJavaSysProps() {
+        VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
+            .configure("main", "my.Main").configure("useJmx", false).configure("javaSysProps", ImmutableMap.of("mykey", "myval")));
+
+        app.start(ImmutableList.of(loc));
+        
+        String runDir = javaProcess.getRunDir();
+        String defaultJavaOpts = "-Xms128m -Xmx512m -XX:MaxPermSize=512m";
+        String expectedJavaOpts = defaultJavaOpts+" -Dmykey=myval";
+        Map<String,String> expectedEnvs = ImmutableMap.<String,String>of("JAVA_OPTS", expectedJavaOpts);
+        List<String> expectedCmds = ImmutableList.of(String.format("java $JAVA_OPTS -cp \"%1$s/lib\" my.Main  >> %1$s/console 2>&1 </dev/null &", runDir));
+        
+        assertHasExpectedCmds(expectedCmds, expectedEnvs);
+    }
+    
+    @Test
+    public void testPassesJavaOptsOverridingDefaults() {
+        VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class)
+            .configure("main", "my.Main").configure("useJmx", false).configure("javaOpts", ImmutableList.of("-Xmx567m", "-XX:MaxPermSize=567m")));
+        app.start(ImmutableList.of(loc));
+        
+        String runDir = javaProcess.getRunDir();
+        Object expectedJavaOpts = MutableSet.of("-Xms128m", "-Xmx567m", "-XX:MaxPermSize=567m");
+        Map<String,Object> expectedEnvs = ImmutableMap.<String,Object>of("JAVA_OPTS", expectedJavaOpts);
+        List<String> expectedCmds = ImmutableList.of(String.format("java $JAVA_OPTS -cp \"%1$s/lib\" my.Main  >> %1$s/console 2>&1 </dev/null &", runDir));
+
+        assertHasExpectedCmds(expectedCmds, expectedEnvs);
+    }
+    
+    public static class TestingJavaOptsVanillaJavaAppImpl extends VanillaJavaAppImpl {
+        @Override public VanillaJavaAppSshDriver newDriver(MachineLocation loc) {
+            return new VanillaJavaAppSshDriver(this, (SshMachineLocation)loc) {
+                @Override protected List<String> getCustomJavaConfigOptions() {
+                    return MutableList.<String>builder()
+                        .addAll(super.getCustomJavaConfigOptions())
+                        .add("-server")
+                        .build();
+                };
+            };
+        }
+    }
+    
+    @Test
+    public void testPassesJavaOptsObeyingMutualExclusions() {
+        VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class, TestingJavaOptsVanillaJavaAppImpl.class)
+            .configure("main", "my.Main").configure("useJmx", false).configure("javaOpts", ImmutableList.of("-client")));
+        app.start(ImmutableList.of(loc));
+        
+        String runDir = javaProcess.getRunDir();
+        String defaultJavaOpts = "-Xms128m -Xmx512m -XX:MaxPermSize=512m";
+        String expectedJavaOpts = defaultJavaOpts+" -client";
+        Map<String,String> expectedEnvs = ImmutableMap.<String,String>of("JAVA_OPTS", expectedJavaOpts);
+        List<String> expectedCmds = ImmutableList.of(String.format("java $JAVA_OPTS -cp \"%1$s/lib\" my.Main  >> %1$s/console 2>&1 </dev/null &", runDir));
+        
+        assertHasExpectedCmds(expectedCmds, expectedEnvs);
+    }
+    
+    /**
+     * Asserts that one of the scripts executed had these commands, and these environment variables.
+     * There could be other commands in between though.
+     */
+    private void assertHasExpectedCmds(List<String> expectedCmds, Map<String,?> expectedEnvs) {
+        if (RecordingSshTool.execScriptCmds.isEmpty())
+            fail("No commands recorded");
+        
+        for (ExecCmd cmd : RecordingSshTool.execScriptCmds) {
+            // TODO Check expectedCmds in-order
+            
+            // check if expectedEnv is a set, then the string value contains all elements in the set
+            Map<Object, ValueDifference<Object>> difference = Maps.<Object,Object>difference(cmd.env, expectedEnvs).entriesDiffering();
+            boolean same = difference.isEmpty();
+            if (!same) {
+                Set<Object> differingKeys = new LinkedHashSet<Object>(difference.keySet());
+                Iterator<Object> ki = differingKeys.iterator();
+                while (ki.hasNext()) {
+                    Object key = ki.next();
+                    Object expectationHere = expectedEnvs.get(key);
+                    Object valueHere = cmd.env.get(key);
+                    if (valueHere==null) break;
+                    
+                    if (expectationHere instanceof Set) {
+                        Set mutableExpectationHere = new LinkedHashSet(((Set)expectationHere));
+                        Iterator si = ((Set)mutableExpectationHere).iterator();
+                        while (si.hasNext()) {
+                            Object oneExpectationHere = si.next();
+                            if (valueHere.toString().contains(Strings.toString(oneExpectationHere)))
+                                si.remove();
+                            else break;
+                        }
+                        if (mutableExpectationHere.isEmpty())
+                            differingKeys.remove(key);
+                        else
+                            // not the same
+                            break;
+                    } else {
+                        // not the same
+                        break;
+                    }
+                }
+                if (differingKeys.isEmpty())
+                    same = true;
+            }
+            
+            if (cmd.commands.containsAll(expectedCmds) && same) {
+                return;
+            }
+        }
+        
+        for (ExecCmd cmd : RecordingSshTool.execScriptCmds) {
+            log.info("Command:");
+            log.info("\tEnv:");
+            for (Map.Entry<?,?> entry : cmd.env.entrySet()) {
+                log.info("\t\t"+entry.getKey()+" = "+entry.getValue());
+            }
+            log.info("\tCmds:");
+            for (String c : cmd.commands) {
+                log.info("\t\t"+c);
+            }
+        }
+        
+        fail("Cmd not present: expected="+expectedCmds+"/"+expectedEnvs+"; actual="+RecordingSshTool.execScriptCmds);
+    }
+
+    public static class TestingNoSensorsVanillaJavaAppImpl extends VanillaJavaAppImpl {
+        protected void connectSensors() {
+            /* nothing here */
+            setAttribute(SERVICE_UP, true);
+        }
+    }
+    
+    private void assertJmxWithPropsHasPhrases(Map props,
+            List<String> expectedPhrases,
+            List<String> forbiddenPhrases) {
+        if (!props.containsKey("main")) props.put("main", "my.Main");
+        @SuppressWarnings({ "unused" })
+        VanillaJavaApp javaProcess = app.createAndManageChild(EntitySpec.create(VanillaJavaApp.class, TestingNoSensorsVanillaJavaAppImpl.class)
+            .configure(props));
+        app.start(ImmutableList.of(loc));
+        
+        List<String> phrases = new ArrayList<String>(expectedPhrases);
+        Set<String> forbiddenPhrasesFound = new LinkedHashSet<String>();
+        for (ExecCmd cmd : RecordingSshTool.execScriptCmds) {
+            String biggun = ""+cmd.env+" "+cmd.commands;
+            Iterator<String> pi = phrases.iterator();
+            while (pi.hasNext()) {
+                String phrase = pi.next();
+                if (biggun.contains(phrase)) pi.remove();
+            }
+            if (forbiddenPhrases!=null)
+                for (String p: forbiddenPhrases)
+                    if (biggun.contains(p)) forbiddenPhrasesFound.add(p);
+        }
+        
+        if (!phrases.isEmpty()) {
+            log.warn("Missing phrases in commands: "+phrases+"\nCOMMANDS: "+RecordingSshTool.execScriptCmds);
+            fail("Missing phrases in commands: "+phrases);
+        }
+        if (!forbiddenPhrasesFound.isEmpty()) {
+            log.warn("Forbidden phrases found in commands: "+forbiddenPhrasesFound+"\nCOMMANDS: "+RecordingSshTool.execScriptCmds);
+            fail("Forbidden phrases found in commands: "+forbiddenPhrasesFound);
+        }
+    }
+    
+    private static final List<String> EXPECTED_BASIC_JMX_OPTS = Arrays.asList(
+            "-Dcom.sun.management.jmxremote",
+            "-Dcom.sun.management.jmxremote.ssl=false",
+            "-Dcom.sun.management.jmxremote.authenticate=false"
+        );
+
+    private static final List<String> FORBIDDEN_BASIC_JMX_OPTS = Arrays.asList(
+            "-Dcom.sun.management.jmxremote.ssl=true",
+            
+            // often breaks things, as this is an advertised hostname usually;
+            // it typically listens on all interfaces anyway
+            "-Djava.rmi.server.hostname=0.0.0.0"
+        );
+
+    @Test
+    public void testBasicJmxFromFlag() {
+        assertJmxWithPropsHasPhrases(
+                MutableMap.builder().
+                put("useJmx", true).
+                build(), 
+            EXPECTED_BASIC_JMX_OPTS,
+            FORBIDDEN_BASIC_JMX_OPTS);
+    }
+
+    @Test
+    public void testBasicJmxFromConfig() {
+        assertJmxWithPropsHasPhrases(
+                MutableMap.builder().
+                put(UsesJmx.USE_JMX, true).
+                build(), 
+            EXPECTED_BASIC_JMX_OPTS,
+            FORBIDDEN_BASIC_JMX_OPTS);
+    }
+
+    @Test
+    public void testBasicJmxConfigFromDefault() {
+        assertJmxWithPropsHasPhrases(
+                MutableMap.builder().
+                build(), 
+            EXPECTED_BASIC_JMX_OPTS,
+            FORBIDDEN_BASIC_JMX_OPTS);
+    }
+    
+    @Test
+    public void testSecureJmxConfigFromDefault() {
+        final List<String> EXPECTED_SECURE_JMX_OPTS = Arrays.asList(
+                "-Dcom.sun.management.jmxremote",
+                "-Dbrooklyn.jmxmp.port=31009",
+                "-Dcom.sun.management.jmxremote.ssl=true",
+                "-D"+JmxmpAgent.AUTHENTICATE_CLIENTS_PROPERTY+"=true",
+                "keyStore", "/jmx-keystore",
+                "trustStore", "/jmx-truststore",
+                "-javaagent", "brooklyn-jmxmp-agent"
+            );
+
+        final List<String> FORBIDDEN_SECURE_JMX_OPTS = Arrays.asList(
+                "-Dcom.sun.management.jmxremote.authenticate=true",
+                "-Dcom.sun.management.jmxremote.ssl=false",
+                // hostname isn't forbidden -- but it is generally not used now
+                "-Djava.rmi.server.hostname="
+            );
+        
+        assertJmxWithPropsHasPhrases(
+                MutableMap.builder()
+                        .put(UsesJmx.JMX_SSL_ENABLED, true)
+                        .put(UsesJmx.JMX_PORT, 31009)
+                        .build(), 
+                EXPECTED_SECURE_JMX_OPTS,
+                FORBIDDEN_SECURE_JMX_OPTS);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriverIntegrationTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriverIntegrationTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriverIntegrationTest.java
new file mode 100644
index 0000000..68cdc61
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/java/JavaSoftwareProcessSshDriverIntegrationTest.java
@@ -0,0 +1,173 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.internal.EntityLocal;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.location.MachineProvisioningLocation;
+import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.entity.core.BrooklynConfigKeys;
+import org.apache.brooklyn.entity.java.JavaSoftwareProcessSshDriver;
+import org.apache.brooklyn.entity.software.base.SoftwareProcess;
+import org.apache.brooklyn.entity.software.base.lifecycle.MyEntity;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.text.Strings;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.SshMachineLocation;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableList;
+
+public class JavaSoftwareProcessSshDriverIntegrationTest extends BrooklynAppLiveTestSupport {
+
+    private static final long TIMEOUT_MS = 10 * 1000;
+
+    private static final Logger LOG = LoggerFactory.getLogger(JavaSoftwareProcessSshDriverIntegrationTest.class);
+
+    private MachineProvisioningLocation<?> localhost;
+
+    private static class ConcreteJavaSoftwareProcessSshDriver extends JavaSoftwareProcessSshDriver {
+        public ConcreteJavaSoftwareProcessSshDriver(EntityLocal entity, SshMachineLocation machine) {
+            super(entity, machine);
+        }
+        @Override protected String getLogFileLocation() { return null; }
+        @Override public boolean isRunning() { return false; }
+        @Override public void stop() {}
+        @Override public void install() {}
+        @Override public void customize() {}
+        @Override public void launch() {}
+    }
+
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        localhost = app.newLocalhostProvisioningLocation();
+    }
+
+    @Test(groups = "Integration")
+    public void testJavaStartStopSshDriverStartsAndStopsApp() throws Exception {
+        final MyEntity entity = app.createAndManageChild(EntitySpec.create(MyEntity.class));
+        app.start(ImmutableList.of(localhost));
+        Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
+            public void run() {
+                assertTrue(entity.getAttribute(SoftwareProcess.SERVICE_UP));
+            }});
+
+        entity.stop();
+        assertFalse(entity.getAttribute(SoftwareProcess.SERVICE_UP));
+    }
+
+    @Test(groups = "Integration")
+    public void testGetJavaVersion() throws Exception {
+        SshMachineLocation sshLocation = app.getManagementContext().getLocationManager().createLocation(
+                LocationSpec.create(SshMachineLocation.class).configure("address", "localhost"));
+        JavaSoftwareProcessSshDriver driver = new ConcreteJavaSoftwareProcessSshDriver(app, sshLocation);
+        Optional<String> version = driver.getInstalledJavaVersion();
+        assertNotNull(version);
+        assertTrue(version.isPresent());
+        LOG.info("{}.testGetJavaVersion found: {} on localhost", getClass(), version.get());
+    }
+
+    @Test(groups = "Integration")
+    public void testStartsInMgmtSpecifiedDirectory() throws Exception {
+        String dir = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4));
+        tearDown();
+        mgmt = new LocalManagementContextForTests();
+        mgmt.getBrooklynProperties().put(BrooklynConfigKeys.ONBOX_BASE_DIR, dir);
+        setUp();
+
+        doTestSpecifiedDirectory(dir, dir);
+        Os.deleteRecursively(dir);
+    }
+
+    @Test(groups = "Integration")
+    public void testStartsInAppSpecifiedDirectoryUnderHome() throws Exception {
+        String dir = Os.mergePathsUnix("~/.brooklyn-test-"+Strings.makeRandomId(4));
+        try {
+            app.config().set(BrooklynConfigKeys.ONBOX_BASE_DIR, dir);
+            doTestSpecifiedDirectory(dir, dir);
+        } finally {
+            Os.deleteRecursively(dir);
+        }
+    }
+
+    @Test(groups = "Integration")
+    public void testStartsInDifferentRunAndInstallSpecifiedDirectories() throws Exception {
+        String dir1 = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4));
+        String dir2 = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4));
+        app.config().set(BrooklynConfigKeys.INSTALL_DIR, dir1);
+        app.config().set(BrooklynConfigKeys.RUN_DIR, dir2);
+        doTestSpecifiedDirectory(dir1, dir2);
+        Os.deleteRecursively(dir1);
+        Os.deleteRecursively(dir2);
+    }
+
+    @Test(groups = "Integration")
+    public void testStartsInLegacySpecifiedDirectory() throws Exception {
+        String dir1 = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4));
+        String dir2 = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4));
+        tearDown();
+        mgmt = new LocalManagementContextForTests();
+        mgmt.getBrooklynProperties().put("brooklyn.dirs.install", dir1);
+        mgmt.getBrooklynProperties().put("brooklyn.dirs.run", dir2);
+        setUp();
+
+        app.config().set(BrooklynConfigKeys.RUN_DIR, dir2);
+        doTestSpecifiedDirectory(dir1, dir2);
+        Os.deleteRecursively(dir1);
+        Os.deleteRecursively(dir2);
+    }
+
+    protected void doTestSpecifiedDirectory(final String installDirPrefix, final String runDirPrefix) throws Exception {
+        final MyEntity entity = app.createAndManageChild(EntitySpec.create(MyEntity.class));
+        app.start(ImmutableList.of(localhost));
+        Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
+            public void run() {
+                assertTrue(entity.getAttribute(SoftwareProcess.SERVICE_UP));
+
+                String installDir = entity.getAttribute(SoftwareProcess.INSTALL_DIR);
+                Assert.assertNotNull(installDir);
+
+                String runDir = entity.getAttribute(SoftwareProcess.RUN_DIR);
+                Assert.assertNotNull(runDir);
+            }});
+
+        String installDir = entity.getAttribute(SoftwareProcess.INSTALL_DIR);
+        String runDir = entity.getAttribute(SoftwareProcess.RUN_DIR);
+        LOG.info("dirs for " + app + " are: install=" + installDir + ", run=" + runDir);
+        assertTrue(installDir.startsWith(Os.tidyPath(installDirPrefix)), "INSTALL_DIR is "+installDir+", does not start with expected prefix "+installDirPrefix);
+        assertTrue(runDir.startsWith(Os.tidyPath(runDirPrefix)), "RUN_DIR is "+runDir+", does not start with expected prefix "+runDirPrefix);
+
+        entity.stop();
+        assertFalse(entity.getAttribute(SoftwareProcess.SERVICE_UP));
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/java/JmxSupportTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/java/JmxSupportTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/java/JmxSupportTest.java
new file mode 100644
index 0000000..39d6089
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/java/JmxSupportTest.java
@@ -0,0 +1,135 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import static org.testng.Assert.assertEquals;
+
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.JmxSupport;
+import org.apache.brooklyn.entity.java.UsesJmx.JmxAgentModes;
+import org.apache.brooklyn.util.core.ResourceUtils;
+import org.apache.brooklyn.util.core.flags.TypeCoercions;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.javalang.JavaClassNames;
+import org.apache.brooklyn.util.maven.MavenRetriever;
+import org.apache.brooklyn.util.stream.Streams;
+import org.apache.brooklyn.util.text.Strings;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.Test;
+
+@Test
+public class JmxSupportTest {
+
+    private static final Logger log = LoggerFactory.getLogger(JmxSupportTest.class);
+    
+    private TestApplication app;
+
+    @AfterMethod(alwaysRun = true)
+    public void tearDown() {
+        if (app!=null) Entities.destroyAll(app.getManagementContext());
+    }
+    
+    // defaults to JMXMP for most locations (or, in this case, if it does not yet know the location)
+    public void testJmxAutodetect() {
+        app = TestApplication.Factory.newManagedInstanceForTests();
+        JmxSupport support = new JmxSupport(app, null);
+        
+        Assert.assertEquals(support.getJmxAgentMode(), JmxAgentModes.JMXMP_AND_RMI);
+    }
+
+    public void testJmxmpJarExistence() {
+        app = TestApplication.Factory.newManagedInstanceForTests();
+        app.setConfig(JmxSupport.JMX_AGENT_MODE, JmxAgentModes.JMXMP);
+        JmxSupport support = new JmxSupport(app, null);
+        
+        Assert.assertEquals(support.getJmxAgentJarMavenArtifact().getArtifactId(),
+                "brooklyn-jmxmp-agent");
+        
+        Assert.assertTrue(ResourceUtils.create(this).doesUrlExist(support.getJmxAgentJarUrl()), support.getJmxAgentJarUrl());
+        Assert.assertTrue(support.getJmxAgentJarUrl().contains("-shaded-"), support.getJmxAgentJarUrl());
+    }
+    
+    public void testJmxrmiJarExistence() {
+        app = TestApplication.Factory.newManagedInstanceForTests();
+        JmxSupport support = new JmxSupport(app, null);
+        app.setConfig(JmxSupport.JMX_AGENT_MODE, JmxAgentModes.JMX_RMI_CUSTOM_AGENT);
+        
+        Assert.assertEquals(support.getJmxAgentJarMavenArtifact().getArtifactId(),
+                "brooklyn-jmxrmi-agent");
+        
+        Assert.assertTrue(ResourceUtils.create(this).doesUrlExist(support.getJmxAgentJarUrl()), support.getJmxAgentJarUrl());
+    }
+
+    @Test
+    public void testCoerceStringtoJmxAgentModes() {
+        // Test coercions
+        assertEquals(TypeCoercions.coerce("AUTODETECT", JmxAgentModes.class), JmxAgentModes.AUTODETECT);
+        assertEquals(TypeCoercions.coerce("JMXMP_AND_RMI", JmxAgentModes.class), JmxAgentModes.JMXMP_AND_RMI);
+        assertEquals(TypeCoercions.coerce("JMX_RMI_CUSTOM_AGENT", JmxAgentModes.class), JmxAgentModes.JMX_RMI_CUSTOM_AGENT);
+
+        // Test different case format options
+        assertEquals(TypeCoercions.coerce("jmxRmiCustomAgent", JmxAgentModes.class), JmxAgentModes.JMX_RMI_CUSTOM_AGENT);
+        assertEquals(TypeCoercions.coerce("jmx_rmi_custom_agent", JmxAgentModes.class), JmxAgentModes.JMX_RMI_CUSTOM_AGENT);
+        assertEquals(TypeCoercions.coerce("jmx-rmi-custom-agent", JmxAgentModes.class), JmxAgentModes.JMX_RMI_CUSTOM_AGENT);
+        assertEquals(TypeCoercions.coerce("JmxRmiCustomAgent", JmxAgentModes.class), JmxAgentModes.JMX_RMI_CUSTOM_AGENT);
+    }
+
+
+    @Test(groups="Integration")
+    public void testJmxmpJarHostedValidity() {
+        app = TestApplication.Factory.newManagedInstanceForTests();
+        app.setConfig(JmxSupport.JMX_AGENT_MODE, JmxAgentModes.JMXMP);
+        JmxSupport support = new JmxSupport(app, null);
+
+        // make sure we get a valid jar, big enough (no redirect, and classifier correclty set for this!)
+        // (we don't want the unshaded jar, that would be no good!)
+        checkValidArchive(MavenRetriever.hostedUrl(support.getJmxAgentJarMavenArtifact()), 100*1000);
+    }
+    
+    @Test(groups="Integration")
+    public void testJmxrmiJarHostedValidity() {
+        app = TestApplication.Factory.newManagedInstanceForTests();
+        JmxSupport support = new JmxSupport(app, null);
+        app.setConfig(JmxSupport.JMX_AGENT_MODE, JmxAgentModes.JMX_RMI_CUSTOM_AGENT);
+        
+        // make sure we get a valid jar, big enough (no redirect)
+        checkValidArchive(MavenRetriever.hostedUrl(support.getJmxAgentJarMavenArtifact()), 4000);
+    }
+
+    private void checkValidArchive(String url, long minSize) {
+        byte[] bytes;
+        try {
+            bytes = Streams.readFully(ResourceUtils.create(this).getResourceFromUrl(url));
+            log.info("read "+bytes.length+" bytes from "+url+" for "+JavaClassNames.callerNiceClassAndMethod(1));
+        } catch (Exception e) {
+            log.warn("Unable to read URL "+url+" for " +JavaClassNames.callerNiceClassAndMethod(1)+
+                    "; this test may require hosted (sonatype/mavencentral) repo to be populated");
+            Assert.fail("Unable to read URL "+url+"; this test may require hosted (sonatype/mavencentral) repo to be populated");
+            throw Exceptions.propagate(e);
+        }
+        // confirm this follow redirects!
+        Assert.assertTrue(bytes.length > minSize, "download of "+url+" is suspect ("+Strings.makeSizeString(bytes.length)+")");
+        // (could also check it is a zip etc)
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/java/SslKeyConfigTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/java/SslKeyConfigTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/java/SslKeyConfigTest.java
new file mode 100644
index 0000000..24ce2c9
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/java/SslKeyConfigTest.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.security.Key;
+import java.security.KeyStore;
+import java.security.cert.Certificate;
+
+import org.apache.brooklyn.util.core.crypto.FluentKeySigner;
+import org.apache.brooklyn.util.core.crypto.SecureKeys;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+public class SslKeyConfigTest {
+
+    @Test
+    public void testWriteKeyAndCertThenReadThem() throws Exception {
+        FluentKeySigner signer = new FluentKeySigner("brooklyn-test").selfsign();
+        
+        KeyStore ks = SecureKeys.newKeyStore();
+        ks.setKeyEntry("key1", 
+                signer.getKey().getPrivate(), "s3cr3t".toCharArray(), new Certificate[] { signer.getAuthorityCertificate() });
+        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+        ks.store(bytes, "5t0r3".toCharArray());
+        
+        KeyStore ks2 = SecureKeys.newKeyStore(new ByteArrayInputStream(bytes.toByteArray()), "5t0r3");
+        String firstAlias = ks2.aliases().nextElement();
+        Assert.assertEquals(firstAlias, "key1");
+        Key k = ks2.getKey(firstAlias, "s3cr3t".toCharArray());
+        Assert.assertEquals(k, signer.getKey().getPrivate());
+        Certificate[] cc = ks2.getCertificateChain(firstAlias);
+        Assert.assertEquals(cc, new Certificate[] { signer.getAuthorityCertificate() });
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppRebindTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppRebindTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppRebindTest.java
new file mode 100644
index 0000000..d3a97d3
--- /dev/null
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/java/VanillaJavaAppRebindTest.java
@@ -0,0 +1,173 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.entity.java;
+
+import static org.testng.Assert.assertTrue;
+
+import java.io.File;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.entity.core.Entities;
+import org.apache.brooklyn.entity.java.VanillaJavaApp;
+import org.apache.brooklyn.entity.java.VanillaJavaAppImpl;
+import org.apache.brooklyn.entity.java.JavaOptsTest.TestingJavaOptsVanillaJavaAppImpl;
+import org.apache.brooklyn.policy.enricher.RollingTimeWindowMeanEnricher;
+import org.apache.brooklyn.sensor.core.Sensors;
+import org.apache.brooklyn.test.EntityTestUtils;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.ResourceUtils;
+import org.apache.brooklyn.util.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
+
+import com.google.common.base.Predicates;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.io.Files;
+
+public class VanillaJavaAppRebindTest {
+
+    private static final Logger LOG = LoggerFactory.getLogger(VanillaJavaAppRebindTest.class);
+    
+    private static String BROOKLYN_THIS_CLASSPATH = null;
+    private static Class<?> MAIN_CLASS = ExampleVanillaMain.class;
+
+    private ClassLoader classLoader = getClass().getClassLoader();
+    private LocalManagementContext managementContext;
+    private File mementoDir;
+    private TestApplication app;
+    private LocalhostMachineProvisioningLocation loc;
+    
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        mementoDir = Files.createTempDir();
+        managementContext = RebindTestUtils.newPersistingManagementContext(mementoDir, classLoader);
+        
+        if (BROOKLYN_THIS_CLASSPATH==null) {
+            BROOKLYN_THIS_CLASSPATH = ResourceUtils.create(MAIN_CLASS).getClassLoaderDir();
+        }
+        app = TestApplication.Factory.newManagedInstanceForTests(managementContext);
+        loc = app.newLocalhostProvisioningLocation(MutableMap.of("address", "localhost"));
+    }
+
+    @AfterMethod(alwaysRun = true)
+    public void tearDown() throws Exception {
+        if (app != null) Entities.destroyAll(app.getManagementContext());
+        if (mementoDir != null) RebindTestUtils.deleteMementoDir(mementoDir);
+    }
+    
+    private void rebind() throws Exception {
+        RebindTestUtils.waitForPersisted(app);
+        managementContext.terminate();
+        
+        app = (TestApplication) RebindTestUtils.rebind(mementoDir, getClass().getClassLoader());
+        managementContext = (LocalManagementContext) app.getManagementContext();
+        loc = (LocalhostMachineProvisioningLocation) Iterables.get(app.getLocations(), 0, null);
+    }
+    
+    @Test(groups="Integration")
+    public void testRebindToJavaApp() throws Exception {
+        VanillaJavaApp javaProcess = app.addChild(EntitySpec.create(VanillaJavaApp.class, TestingJavaOptsVanillaJavaAppImpl.class)
+            .configure("main", MAIN_CLASS.getCanonicalName()).configure("classpath", ImmutableList.of(BROOKLYN_THIS_CLASSPATH)));
+
+        Entities.manage(javaProcess);
+        app.start(ImmutableList.of(loc));
+
+        rebind();
+        VanillaJavaApp javaProcess2 = (VanillaJavaApp) Iterables.find(app.getChildren(), Predicates.instanceOf(VanillaJavaApp.class));
+        
+        EntityTestUtils.assertAttributeEqualsEventually(javaProcess2, VanillaJavaApp.SERVICE_UP, true);
+    }
+
+    @Test(groups="Integration")
+    public void testRebindToKilledJavaApp() throws Exception {
+        VanillaJavaApp javaProcess = app.addChild(EntitySpec.create(VanillaJavaApp.class, TestingJavaOptsVanillaJavaAppImpl.class)
+            .configure("main", MAIN_CLASS.getCanonicalName()).configure("classpath", ImmutableList.of(BROOKLYN_THIS_CLASSPATH)));
+        Entities.manage(javaProcess);
+        app.start(ImmutableList.of(loc));
+        javaProcess.kill();
+        
+        long starttime = System.currentTimeMillis();
+        rebind();
+        long rebindTime = System.currentTimeMillis() - starttime;
+        
+        VanillaJavaApp javaProcess2 = (VanillaJavaApp) Iterables.find(app.getChildren(), Predicates.instanceOf(VanillaJavaApp.class));
+        EntityTestUtils.assertAttributeEqualsEventually(javaProcess2, VanillaJavaApp.SERVICE_UP, false);
+        
+        // check that it was quick (previously it hung)
+        assertTrue(rebindTime < 30*1000, "rebindTime="+rebindTime);
+    }
+    
+    
+    @Test(groups="Integration")
+    public void testEnrichersOnRebindJavaApp() throws Exception {
+        VanillaJavaApp javaProcess = app.addChild(EntitySpec.create(VanillaJavaApp.class, EnrichedVanillaJavaAppImpl.class)
+            .configure("main", MAIN_CLASS.getCanonicalName()).configure("classpath", ImmutableList.of(BROOKLYN_THIS_CLASSPATH)));
+
+        Entities.manage(javaProcess);
+        app.start(ImmutableList.of(loc));
+
+        EntityTestUtils.assertAttributeEventuallyNonNull(javaProcess, EnrichedVanillaJavaAppImpl.AVG1);
+        EntityTestUtils.assertAttributeEventuallyNonNull(javaProcess, EnrichedVanillaJavaAppImpl.AVG2);
+        LOG.info("Got avg "+javaProcess.getAttribute(EnrichedVanillaJavaAppImpl.AVG1));
+
+        rebind();
+        VanillaJavaApp javaProcess2 = (VanillaJavaApp) Iterables.find(app.getChildren(), Predicates.instanceOf(VanillaJavaApp.class));
+
+        // check sensors working
+        EntityTestUtils.assertAttributeChangesEventually(javaProcess2, EnrichedVanillaJavaAppImpl.PROCESS_CPU_TIME); 
+        LOG.info("Avg now "+javaProcess2.getAttribute(EnrichedVanillaJavaAppImpl.AVG1));
+        
+        // check enrichers are functioning
+        EntityTestUtils.assertAttributeChangesEventually(javaProcess2, EnrichedVanillaJavaAppImpl.AVG1); 
+        EntityTestUtils.assertAttributeChangesEventually(javaProcess2, EnrichedVanillaJavaAppImpl.AVG2);
+        LOG.info("Avg now "+javaProcess2.getAttribute(EnrichedVanillaJavaAppImpl.AVG1));
+        
+        // and check we don't have too many
+        Assert.assertEquals(javaProcess2.getEnrichers().size(), javaProcess.getEnrichers().size());
+    }
+
+    public static class EnrichedVanillaJavaAppImpl extends VanillaJavaAppImpl {
+        private static final AttributeSensor<Double> AVG1 = Sensors.newDoubleSensor("avg1");
+        private static final AttributeSensor<Double> AVG2 = Sensors.newDoubleSensor("avg2");
+        
+        @Override
+        public void onManagementStarted() {
+            super.onManagementStarted();
+            LOG.info("mgmt started for "+this);
+            addEnricher(new RollingTimeWindowMeanEnricher<Double>(this, PROCESS_CPU_TIME, AVG1, Duration.TEN_SECONDS));
+        }
+        @Override
+        protected void connectSensors() {
+            super.connectSensors();
+            LOG.info("connecting sensors for "+this);
+            addEnricher(new RollingTimeWindowMeanEnricher<Double>(this, PROCESS_CPU_TIME, AVG2, Duration.TEN_SECONDS));
+        }
+    }
+
+}